mirror of
https://github.com/me-no-dev/ESPAsyncWebServer.git
synced 2025-07-30 10:47:31 +02:00
Merge pull request #1464 from mathieucarbou/move
Prepare move to https://github.com/ESP32Async/ESPAsyncWebServer
This commit is contained in:
22
.clang-format
Normal file
22
.clang-format
Normal file
@ -0,0 +1,22 @@
|
||||
Language: Cpp
|
||||
BasedOnStyle: LLVM
|
||||
|
||||
AccessModifierOffset: -2
|
||||
AlignConsecutiveMacros: true
|
||||
AllowAllArgumentsOnNextLine: false
|
||||
AllowAllParametersOfDeclarationOnNextLine: false
|
||||
AllowShortIfStatementsOnASingleLine: false
|
||||
AllowShortLambdasOnASingleLine: Inline
|
||||
BinPackArguments: false
|
||||
ColumnLimit: 0
|
||||
ContinuationIndentWidth: 2
|
||||
FixNamespaceComments: false
|
||||
IndentAccessModifiers: true
|
||||
IndentCaseLabels: true
|
||||
IndentPPDirectives: BeforeHash
|
||||
IndentWidth: 2
|
||||
NamespaceIndentation: All
|
||||
PointerAlignment: Left
|
||||
ReferenceAlignment: Left
|
||||
TabWidth: 2
|
||||
UseTab: Never
|
40
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
40
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Only for bugs founds in the library! Otherwise, please go to the discussions section!
|
||||
title: "[BUG]"
|
||||
labels: triage
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**Only for bugs found in the library! Otherwise, please go to the [discussions section](https://github.com/ESP32Async/ESPAsyncWebServer/discussions)!**
|
||||
|
||||
**Please make sure to go through the recommendations before opening a bug report:**
|
||||
|
||||
[https://github.com/ESP32Async/ESPAsyncWebServer?tab=readme-ov-file#important-recommendations](https://github.com/ESP32Async/ESPAsyncWebServer?tab=readme-ov-file#important-recommendations)
|
||||
|
||||
**Description**
|
||||
|
||||
_A clear and concise description of what the bug is._
|
||||
|
||||
**Link:** _A link to your source code where the issue happens_
|
||||
|
||||
**Board**: _esp32dev, esp32s3, ?_
|
||||
|
||||
**Ethernet adapter used ?** _If yes, please specify which one_
|
||||
|
||||
**Stack trace**
|
||||
|
||||
Please provide a **decoded stack trace** taken with `monitor_filters = esp32_exception_decoder`.
|
||||
**Any issue opened with a non readable stack trace will be ignored because not helpful at all.**
|
||||
|
||||
As an alternative, you can use [https://maximeborges.github.io/esp-stacktrace-decoder/](https://maximeborges.github.io/esp-stacktrace-decoder/).
|
||||
|
||||
**Additional notes**
|
||||
|
||||
Add any other context about the problem here.
|
||||
|
||||
# WARNING
|
||||
|
||||
**ANY ISSUE POSTED WITH AN ENCODED STACK TRACE WILL BE CLOSED !**
|
||||
|
||||
**PLEASE MAKE THE EFFORT TO DECODE YOUR STACK TRACE**
|
9
.github/ISSUE_TEMPLATE/question.md
vendored
Normal file
9
.github/ISSUE_TEMPLATE/question.md
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
---
|
||||
name: Question
|
||||
about: "For questions: please go to the discussions section!"
|
||||
title: "[Q]"
|
||||
labels: question
|
||||
assignees: ""
|
||||
---
|
||||
|
||||
**For questions: please go to the [discussions section](https://github.com/ESP32Async/ESPAsyncWebServer/discussions)!**
|
10
.github/dependabot.yml
vendored
Normal file
10
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,10 @@
|
||||
# Set update schedule for GitHub Actions
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
# Check for updates to GitHub Actions every week
|
||||
interval: "weekly"
|
36
.github/scripts/install-arduino-core-esp32.sh
vendored
36
.github/scripts/install-arduino-core-esp32.sh
vendored
@ -1,36 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
export ARDUINO_ESP32_PATH="$ARDUINO_USR_PATH/hardware/espressif/esp32"
|
||||
if [ ! -d "$ARDUINO_ESP32_PATH" ]; then
|
||||
echo "Installing ESP32 Arduino Core ..."
|
||||
script_init_path="$PWD"
|
||||
mkdir -p "$ARDUINO_USR_PATH/hardware/espressif"
|
||||
cd "$ARDUINO_USR_PATH/hardware/espressif"
|
||||
|
||||
echo "Installing Python Serial ..."
|
||||
pip install pyserial > /dev/null
|
||||
|
||||
if [ "$OS_IS_WINDOWS" == "1" ]; then
|
||||
echo "Installing Python Requests ..."
|
||||
pip install requests > /dev/null
|
||||
fi
|
||||
|
||||
if [ "$GITHUB_REPOSITORY" == "espressif/arduino-esp32" ]; then
|
||||
echo "Linking Core..."
|
||||
ln -s $GITHUB_WORKSPACE esp32
|
||||
else
|
||||
echo "Cloning Core Repository..."
|
||||
git clone https://github.com/espressif/arduino-esp32.git esp32 > /dev/null 2>&1
|
||||
fi
|
||||
|
||||
echo "Updating Submodules ..."
|
||||
cd esp32
|
||||
git submodule update --init --recursive > /dev/null 2>&1
|
||||
|
||||
echo "Installing Platform Tools ..."
|
||||
cd tools && python get.py
|
||||
cd $script_init_path
|
||||
|
||||
echo "ESP32 Arduino has been installed in '$ARDUINO_ESP32_PATH'"
|
||||
echo ""
|
||||
fi
|
29
.github/scripts/install-arduino-core-esp8266.sh
vendored
29
.github/scripts/install-arduino-core-esp8266.sh
vendored
@ -1,29 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Installing ESP8266 Arduino Core ..."
|
||||
script_init_path="$PWD"
|
||||
mkdir -p "$ARDUINO_USR_PATH/hardware/esp8266com"
|
||||
cd "$ARDUINO_USR_PATH/hardware/esp8266com"
|
||||
|
||||
echo "Installing Python Serial ..."
|
||||
pip install pyserial > /dev/null
|
||||
|
||||
if [ "$OS_IS_WINDOWS" == "1" ]; then
|
||||
echo "Installing Python Requests ..."
|
||||
pip install requests > /dev/null
|
||||
fi
|
||||
|
||||
echo "Cloning Core Repository ..."
|
||||
git clone https://github.com/esp8266/Arduino.git esp8266 > /dev/null 2>&1
|
||||
|
||||
echo "Updating submodules ..."
|
||||
cd esp8266
|
||||
git submodule update --init --recursive > /dev/null 2>&1
|
||||
|
||||
echo "Installing Platform Tools ..."
|
||||
cd tools
|
||||
python get.py > /dev/null
|
||||
cd $script_init_path
|
||||
|
||||
echo "ESP8266 Arduino has been installed in '$ARDUINO_USR_PATH/hardware/esp8266com'"
|
||||
echo ""
|
228
.github/scripts/install-arduino-ide.sh
vendored
228
.github/scripts/install-arduino-ide.sh
vendored
@ -1,228 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#OSTYPE: 'linux-gnu', ARCH: 'x86_64' => linux64
|
||||
#OSTYPE: 'msys', ARCH: 'x86_64' => win32
|
||||
#OSTYPE: 'darwin18', ARCH: 'i386' => macos
|
||||
|
||||
OSBITS=`arch`
|
||||
if [[ "$OSTYPE" == "linux"* ]]; then
|
||||
export OS_IS_LINUX="1"
|
||||
ARCHIVE_FORMAT="tar.xz"
|
||||
if [[ "$OSBITS" == "i686" ]]; then
|
||||
OS_NAME="linux32"
|
||||
elif [[ "$OSBITS" == "x86_64" ]]; then
|
||||
OS_NAME="linux64"
|
||||
elif [[ "$OSBITS" == "armv7l" || "$OSBITS" == "aarch64" ]]; then
|
||||
OS_NAME="linuxarm"
|
||||
else
|
||||
OS_NAME="$OSTYPE-$OSBITS"
|
||||
echo "Unknown OS '$OS_NAME'"
|
||||
exit 1
|
||||
fi
|
||||
elif [[ "$OSTYPE" == "darwin"* ]]; then
|
||||
export OS_IS_MACOS="1"
|
||||
ARCHIVE_FORMAT="zip"
|
||||
OS_NAME="macosx"
|
||||
elif [[ "$OSTYPE" == "cygwin" ]] || [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "win32" ]]; then
|
||||
export OS_IS_WINDOWS="1"
|
||||
ARCHIVE_FORMAT="zip"
|
||||
OS_NAME="windows"
|
||||
else
|
||||
OS_NAME="$OSTYPE-$OSBITS"
|
||||
echo "Unknown OS '$OS_NAME'"
|
||||
exit 1
|
||||
fi
|
||||
export OS_NAME
|
||||
|
||||
ARDUINO_BUILD_DIR="$HOME/.arduino/build.tmp"
|
||||
ARDUINO_CACHE_DIR="$HOME/.arduino/cache.tmp"
|
||||
|
||||
if [ "$OS_IS_MACOS" == "1" ]; then
|
||||
export ARDUINO_IDE_PATH="/Applications/Arduino.app/Contents/Java"
|
||||
export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
|
||||
elif [ "$OS_IS_WINDOWS" == "1" ]; then
|
||||
export ARDUINO_IDE_PATH="$HOME/arduino_ide"
|
||||
export ARDUINO_USR_PATH="$HOME/Documents/Arduino"
|
||||
else
|
||||
export ARDUINO_IDE_PATH="$HOME/arduino_ide"
|
||||
export ARDUINO_USR_PATH="$HOME/Arduino"
|
||||
fi
|
||||
|
||||
if [ ! -d "$ARDUINO_IDE_PATH" ]; then
|
||||
echo "Installing Arduino IDE on $OS_NAME ..."
|
||||
echo "Downloading 'arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT' to 'arduino.$ARCHIVE_FORMAT' ..."
|
||||
if [ "$OS_IS_LINUX" == "1" ]; then
|
||||
wget -O "arduino.$ARCHIVE_FORMAT" "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
|
||||
echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
|
||||
tar xf "arduino.$ARCHIVE_FORMAT" > /dev/null
|
||||
mv arduino-nightly "$ARDUINO_IDE_PATH"
|
||||
else
|
||||
curl -o "arduino.$ARCHIVE_FORMAT" -L "https://www.arduino.cc/download.php?f=/arduino-nightly-$OS_NAME.$ARCHIVE_FORMAT" > /dev/null 2>&1
|
||||
echo "Extracting 'arduino.$ARCHIVE_FORMAT' ..."
|
||||
unzip "arduino.$ARCHIVE_FORMAT" > /dev/null
|
||||
if [ "$OS_IS_MACOS" == "1" ]; then
|
||||
mv "Arduino.app" "/Applications/Arduino.app"
|
||||
else
|
||||
mv arduino-nightly "$ARDUINO_IDE_PATH"
|
||||
fi
|
||||
fi
|
||||
rm -rf "arduino.$ARCHIVE_FORMAT"
|
||||
|
||||
mkdir -p "$ARDUINO_USR_PATH/libraries"
|
||||
mkdir -p "$ARDUINO_USR_PATH/hardware"
|
||||
|
||||
echo "Arduino IDE Installed in '$ARDUINO_IDE_PATH'"
|
||||
echo ""
|
||||
fi
|
||||
|
||||
function build_sketch(){ # build_sketch <fqbn> <path-to-ino> <build-flags> [extra-options]
|
||||
if [ "$#" -lt 2 ]; then
|
||||
echo "ERROR: Illegal number of parameters"
|
||||
echo "USAGE: build_sketch <fqbn> <path-to-ino> <build-flags> [extra-options]"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local fqbn="$1"
|
||||
local sketch="$2"
|
||||
local build_flags="$3"
|
||||
local xtra_opts="$4"
|
||||
local win_opts=""
|
||||
if [ "$OS_IS_WINDOWS" == "1" ]; then
|
||||
local ctags_version=`ls "$ARDUINO_IDE_PATH/tools-builder/ctags/"`
|
||||
local preprocessor_version=`ls "$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/"`
|
||||
win_opts="-prefs=runtime.tools.ctags.path=$ARDUINO_IDE_PATH/tools-builder/ctags/$ctags_version -prefs=runtime.tools.arduino-preprocessor.path=$ARDUINO_IDE_PATH/tools-builder/arduino-preprocessor/$preprocessor_version"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Compiling '"$(basename "$sketch")"' ..."
|
||||
mkdir -p "$ARDUINO_BUILD_DIR"
|
||||
mkdir -p "$ARDUINO_CACHE_DIR"
|
||||
$ARDUINO_IDE_PATH/arduino-builder -compile -logger=human -core-api-version=10810 \
|
||||
-fqbn=$fqbn \
|
||||
-warnings="all" \
|
||||
-tools "$ARDUINO_IDE_PATH/tools-builder" \
|
||||
-tools "$ARDUINO_IDE_PATH/tools" \
|
||||
-built-in-libraries "$ARDUINO_IDE_PATH/libraries" \
|
||||
-hardware "$ARDUINO_IDE_PATH/hardware" \
|
||||
-hardware "$ARDUINO_USR_PATH/hardware" \
|
||||
-libraries "$ARDUINO_USR_PATH/libraries" \
|
||||
-build-cache "$ARDUINO_CACHE_DIR" \
|
||||
-build-path "$ARDUINO_BUILD_DIR" \
|
||||
-prefs=compiler.cpp.extra_flags="$build_flags" \
|
||||
$win_opts $xtra_opts "$sketch"
|
||||
}
|
||||
|
||||
function count_sketches() # count_sketches <examples-path>
|
||||
{
|
||||
local examples="$1"
|
||||
rm -rf sketches.txt
|
||||
if [ ! -d "$examples" ]; then
|
||||
touch sketches.txt
|
||||
return 0
|
||||
fi
|
||||
local sketches=$(find $examples -name *.ino)
|
||||
local sketchnum=0
|
||||
for sketch in $sketches; do
|
||||
local sketchdir=$(dirname $sketch)
|
||||
local sketchdirname=$(basename $sketchdir)
|
||||
local sketchname=$(basename $sketch)
|
||||
if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then
|
||||
continue
|
||||
fi;
|
||||
if [[ -f "$sketchdir/.test.skip" ]]; then
|
||||
continue
|
||||
fi
|
||||
echo $sketch >> sketches.txt
|
||||
sketchnum=$(($sketchnum + 1))
|
||||
done
|
||||
return $sketchnum
|
||||
}
|
||||
|
||||
function build_sketches() # build_sketches <fqbn> <examples-path> <chunk> <total-chunks> [extra-options]
|
||||
{
|
||||
local fqbn=$1
|
||||
local examples=$2
|
||||
local chunk_idex=$3
|
||||
local chunks_num=$4
|
||||
local xtra_opts=$5
|
||||
|
||||
if [ "$#" -lt 2 ]; then
|
||||
echo "ERROR: Illegal number of parameters"
|
||||
echo "USAGE: build_sketches <fqbn> <examples-path> [<chunk> <total-chunks>] [extra-options]"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ "$#" -lt 4 ]; then
|
||||
chunk_idex="0"
|
||||
chunks_num="1"
|
||||
xtra_opts=$3
|
||||
fi
|
||||
|
||||
if [ "$chunks_num" -le 0 ]; then
|
||||
echo "ERROR: Chunks count must be positive number"
|
||||
return 1
|
||||
fi
|
||||
if [ "$chunk_idex" -ge "$chunks_num" ]; then
|
||||
echo "ERROR: Chunk index must be less than chunks count"
|
||||
return 1
|
||||
fi
|
||||
|
||||
set +e
|
||||
count_sketches "$examples"
|
||||
local sketchcount=$?
|
||||
set -e
|
||||
local sketches=$(cat sketches.txt)
|
||||
rm -rf sketches.txt
|
||||
|
||||
local chunk_size=$(( $sketchcount / $chunks_num ))
|
||||
local all_chunks=$(( $chunks_num * $chunk_size ))
|
||||
if [ "$all_chunks" -lt "$sketchcount" ]; then
|
||||
chunk_size=$(( $chunk_size + 1 ))
|
||||
fi
|
||||
|
||||
local start_index=$(( $chunk_idex * $chunk_size ))
|
||||
if [ "$sketchcount" -le "$start_index" ]; then
|
||||
echo "Skipping job"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
|
||||
if [ "$end_index" -gt "$sketchcount" ]; then
|
||||
end_index=$sketchcount
|
||||
fi
|
||||
|
||||
local start_num=$(( $start_index + 1 ))
|
||||
echo "Found $sketchcount Sketches";
|
||||
echo "Chunk Count : $chunks_num"
|
||||
echo "Chunk Size : $chunk_size"
|
||||
echo "Start Sketch: $start_num"
|
||||
echo "End Sketch : $end_index"
|
||||
|
||||
local sketchnum=0
|
||||
for sketch in $sketches; do
|
||||
local sketchdir=$(dirname $sketch)
|
||||
local sketchdirname=$(basename $sketchdir)
|
||||
local sketchname=$(basename $sketch)
|
||||
if [ "${sketchdirname}.ino" != "$sketchname" ] \
|
||||
|| [ -f "$sketchdir/.test.skip" ]; then
|
||||
continue
|
||||
fi
|
||||
sketchnum=$(($sketchnum + 1))
|
||||
if [ "$sketchnum" -le "$start_index" ] \
|
||||
|| [ "$sketchnum" -gt "$end_index" ]; then
|
||||
continue
|
||||
fi
|
||||
local sketchBuildFlags=""
|
||||
if [ -f "$sketchdir/.test.build_flags" ]; then
|
||||
while read line; do
|
||||
sketchBuildFlags="$sketchBuildFlags $line"
|
||||
done < "$sketchdir/.test.build_flags"
|
||||
fi
|
||||
build_sketch "$fqbn" "$sketch" "$sketchBuildFlags" "$xtra_opts"
|
||||
local result=$?
|
||||
if [ $result -ne 0 ]; then
|
||||
return $result
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
140
.github/scripts/install-platformio.sh
vendored
140
.github/scripts/install-platformio.sh
vendored
@ -1,140 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Installing Python Wheel ..."
|
||||
pip install wheel > /dev/null 2>&1
|
||||
|
||||
echo "Installing PlatformIO ..."
|
||||
pip install -U platformio > /dev/null 2>&1
|
||||
|
||||
echo "PlatformIO has been installed"
|
||||
echo ""
|
||||
|
||||
|
||||
function build_pio_sketch(){ # build_pio_sketch <board> <path-to-ino> <build-flags>
|
||||
if [ "$#" -lt 3 ]; then
|
||||
echo "ERROR: Illegal number of parameters"
|
||||
echo "USAGE: build_pio_sketch <board> <path-to-ino> <build-flags>"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local board="$1"
|
||||
local sketch="$2"
|
||||
local buildFlags="$3"
|
||||
local sketch_dir=$(dirname "$sketch")
|
||||
echo ""
|
||||
echo "Compiling '"$(basename "$sketch")"' ..."
|
||||
python -m platformio ci -l '.' --board "$board" "$sketch_dir" --project-option="board_build.partitions = huge_app.csv" --project-option="build_flags=$buildFlags"
|
||||
}
|
||||
|
||||
function count_sketches() # count_sketches <examples-path>
|
||||
{
|
||||
local examples="$1"
|
||||
rm -rf sketches.txt
|
||||
if [ ! -d "$examples" ]; then
|
||||
touch sketches.txt
|
||||
return 0
|
||||
fi
|
||||
local sketches=$(find $examples -name *.ino)
|
||||
local sketchnum=0
|
||||
for sketch in $sketches; do
|
||||
local sketchdir=$(dirname $sketch)
|
||||
local sketchdirname=$(basename $sketchdir)
|
||||
local sketchname=$(basename $sketch)
|
||||
if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then
|
||||
continue
|
||||
fi;
|
||||
if [[ -f "$sketchdir/.test.skip" ]]; then
|
||||
continue
|
||||
fi
|
||||
echo $sketch >> sketches.txt
|
||||
sketchnum=$(($sketchnum + 1))
|
||||
done
|
||||
return $sketchnum
|
||||
}
|
||||
|
||||
function build_pio_sketches() # build_pio_sketches <board> <examples-path> <chunk> <total-chunks>
|
||||
{
|
||||
if [ "$#" -lt 2 ]; then
|
||||
echo "ERROR: Illegal number of parameters"
|
||||
echo "USAGE: build_pio_sketches <board> <examples-path> [<chunk> <total-chunks>]"
|
||||
return 1
|
||||
fi
|
||||
|
||||
local board=$1
|
||||
local examples=$2
|
||||
local chunk_idex=$3
|
||||
local chunks_num=$4
|
||||
|
||||
if [ "$#" -lt 4 ]; then
|
||||
chunk_idex="0"
|
||||
chunks_num="1"
|
||||
fi
|
||||
|
||||
if [ "$chunks_num" -le 0 ]; then
|
||||
echo "ERROR: Chunks count must be positive number"
|
||||
return 1
|
||||
fi
|
||||
if [ "$chunk_idex" -ge "$chunks_num" ]; then
|
||||
echo "ERROR: Chunk index must be less than chunks count"
|
||||
return 1
|
||||
fi
|
||||
|
||||
set +e
|
||||
count_sketches "$examples"
|
||||
local sketchcount=$?
|
||||
set -e
|
||||
local sketches=$(cat sketches.txt)
|
||||
rm -rf sketches.txt
|
||||
|
||||
local chunk_size=$(( $sketchcount / $chunks_num ))
|
||||
local all_chunks=$(( $chunks_num * $chunk_size ))
|
||||
if [ "$all_chunks" -lt "$sketchcount" ]; then
|
||||
chunk_size=$(( $chunk_size + 1 ))
|
||||
fi
|
||||
|
||||
local start_index=$(( $chunk_idex * $chunk_size ))
|
||||
if [ "$sketchcount" -le "$start_index" ]; then
|
||||
echo "Skipping job"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size ))
|
||||
if [ "$end_index" -gt "$sketchcount" ]; then
|
||||
end_index=$sketchcount
|
||||
fi
|
||||
|
||||
local start_num=$(( $start_index + 1 ))
|
||||
echo "Found $sketchcount Sketches";
|
||||
echo "Chunk Count : $chunks_num"
|
||||
echo "Chunk Size : $chunk_size"
|
||||
echo "Start Sketch: $start_num"
|
||||
echo "End Sketch : $end_index"
|
||||
|
||||
local sketchnum=0
|
||||
for sketch in $sketches; do
|
||||
local sketchdir=$(dirname $sketch)
|
||||
local sketchdirname=$(basename $sketchdir)
|
||||
local sketchname=$(basename $sketch)
|
||||
if [ "${sketchdirname}.ino" != "$sketchname" ] \
|
||||
|| [ -f "$sketchdir/.test.skip" ]; then
|
||||
continue
|
||||
fi
|
||||
local sketchBuildFlags=""
|
||||
if [ -f "$sketchdir/.test.build_flags" ]; then
|
||||
while read line; do
|
||||
sketchBuildFlags="$sketchBuildFlags $line"
|
||||
done < "$sketchdir/.test.build_flags"
|
||||
fi
|
||||
sketchnum=$(($sketchnum + 1))
|
||||
if [ "$sketchnum" -le "$start_index" ] \
|
||||
|| [ "$sketchnum" -gt "$end_index" ]; then
|
||||
continue
|
||||
fi
|
||||
build_pio_sketch "$board" "$sketch" "$sketchBuildFlags"
|
||||
local result=$?
|
||||
if [ $result -ne 0 ]; then
|
||||
return $result
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
71
.github/scripts/on-push.sh
vendored
71
.github/scripts/on-push.sh
vendored
@ -1,71 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
if [ ! -z "$TRAVIS_BUILD_DIR" ]; then
|
||||
export GITHUB_WORKSPACE="$TRAVIS_BUILD_DIR"
|
||||
export GITHUB_REPOSITORY="$TRAVIS_REPO_SLUG"
|
||||
elif [ -z "$GITHUB_WORKSPACE" ]; then
|
||||
export GITHUB_WORKSPACE="$PWD"
|
||||
export GITHUB_REPOSITORY="me-no-dev/ESPAsyncWebServer"
|
||||
fi
|
||||
|
||||
TARGET_PLATFORM="$1"
|
||||
CHUNK_INDEX=$2
|
||||
CHUNKS_CNT=$3
|
||||
BUILD_PIO=0
|
||||
if [ "$#" -lt 1 ]; then
|
||||
TARGET_PLATFORM="esp32"
|
||||
fi
|
||||
if [ "$#" -lt 3 ] || [ "$CHUNKS_CNT" -le 0 ]; then
|
||||
CHUNK_INDEX=0
|
||||
CHUNKS_CNT=1
|
||||
elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then
|
||||
CHUNK_INDEX=$CHUNKS_CNT
|
||||
elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then
|
||||
BUILD_PIO=1
|
||||
fi
|
||||
|
||||
if [ "$BUILD_PIO" -eq 0 ]; then
|
||||
# ArduinoIDE Test
|
||||
source ./.github/scripts/install-arduino-ide.sh
|
||||
|
||||
echo "Installing ESPAsyncWebServer ..."
|
||||
cp -rf "$GITHUB_WORKSPACE" "$ARDUINO_USR_PATH/libraries/ESPAsyncWebServer"
|
||||
echo "Installing ArduinoJson ..."
|
||||
git clone https://github.com/bblanchon/ArduinoJson "$ARDUINO_USR_PATH/libraries/ArduinoJson" > /dev/null 2>&1
|
||||
|
||||
if [[ "$TARGET_PLATFORM" == "esp32" ]]; then
|
||||
echo "Installing AsyncTCP ..."
|
||||
git clone https://github.com/me-no-dev/AsyncTCP "$ARDUINO_USR_PATH/libraries/AsyncTCP" > /dev/null 2>&1
|
||||
FQBN="espressif:esp32:esp32:PSRAM=enabled,PartitionScheme=huge_app"
|
||||
source ./.github/scripts/install-arduino-core-esp32.sh
|
||||
echo "BUILDING ESP32 EXAMPLES"
|
||||
else
|
||||
echo "Installing ESPAsyncTCP ..."
|
||||
git clone https://github.com/me-no-dev/ESPAsyncTCP "$ARDUINO_USR_PATH/libraries/ESPAsyncTCP" > /dev/null 2>&1
|
||||
FQBN="esp8266com:esp8266:generic:eesz=4M1M,ip=lm2f"
|
||||
source ./.github/scripts/install-arduino-core-esp8266.sh
|
||||
echo "BUILDING ESP8266 EXAMPLES"
|
||||
fi
|
||||
build_sketches "$FQBN" "$GITHUB_WORKSPACE/examples" "$CHUNK_INDEX" "$CHUNKS_CNT"
|
||||
else
|
||||
# PlatformIO Test
|
||||
source ./.github/scripts/install-platformio.sh
|
||||
|
||||
python -m platformio lib --storage-dir "$GITHUB_WORKSPACE" install
|
||||
echo "Installing ArduinoJson ..."
|
||||
python -m platformio lib -g install https://github.com/bblanchon/ArduinoJson.git > /dev/null 2>&1
|
||||
if [[ "$TARGET_PLATFORM" == "esp32" ]]; then
|
||||
BOARD="esp32dev"
|
||||
echo "Installing AsyncTCP ..."
|
||||
python -m platformio lib -g install https://github.com/me-no-dev/AsyncTCP.git > /dev/null 2>&1
|
||||
echo "BUILDING ESP32 EXAMPLES"
|
||||
else
|
||||
BOARD="esp12e"
|
||||
echo "Installing ESPAsyncTCP ..."
|
||||
python -m platformio lib -g install https://github.com/me-no-dev/ESPAsyncTCP.git > /dev/null 2>&1
|
||||
echo "BUILDING ESP8266 EXAMPLES"
|
||||
fi
|
||||
build_pio_sketches "$BOARD" "$GITHUB_WORKSPACE/examples"
|
||||
fi
|
31
.github/stale.yml
vendored
31
.github/stale.yml
vendored
@ -1,31 +0,0 @@
|
||||
# Configuration for probot-stale - https://github.com/probot/stale
|
||||
|
||||
daysUntilStale: 60
|
||||
daysUntilClose: 14
|
||||
limitPerRun: 30
|
||||
staleLabel: stale
|
||||
exemptLabels:
|
||||
- pinned
|
||||
- security
|
||||
- "to be implemented"
|
||||
- "for reference"
|
||||
- "move to PR"
|
||||
- "enhancement"
|
||||
|
||||
only: issues
|
||||
onlyLabels: []
|
||||
exemptProjects: false
|
||||
exemptMilestones: false
|
||||
exemptAssignees: false
|
||||
|
||||
markComment: >
|
||||
[STALE_SET] This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed in 14 days if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
|
||||
unmarkComment: >
|
||||
[STALE_CLR] This issue has been removed from the stale queue. Please ensure activity to keep it openin the future.
|
||||
|
||||
closeComment: >
|
||||
[STALE_DEL] This stale issue has been automatically closed. Thank you for your contributions.
|
||||
|
157
.github/workflows/ci.yml
vendored
Normal file
157
.github/workflows/ci.yml
vendored
Normal file
@ -0,0 +1,157 @@
|
||||
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
|
||||
|
||||
name: Build
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
arduino:
|
||||
name: Arduino
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- core: esp32:esp32
|
||||
board: esp32:esp32:esp32
|
||||
index_url: https://espressif.github.io/arduino-esp32/package_esp32_index.json
|
||||
# - core: esp32:esp32
|
||||
# board: esp32:esp32:esp32
|
||||
# index_url: https://espressif.github.io/arduino-esp32/package_esp32_dev_index.json
|
||||
- core: esp8266:esp8266
|
||||
board: esp8266:esp8266:huzzah
|
||||
index_url: https://arduino.esp8266.com/stable/package_esp8266com_index.json
|
||||
- name: package_rp2040_index.json
|
||||
core: rp2040:rp2040
|
||||
board: rp2040:rp2040:rpipicow
|
||||
index_url: https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Arduino Lint
|
||||
uses: arduino/arduino-lint-action@v2
|
||||
with:
|
||||
library-manager: update
|
||||
|
||||
- name: Install arduino-cli
|
||||
run: curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh
|
||||
|
||||
- name: Update core index
|
||||
run: arduino-cli core update-index --additional-urls "${{ matrix.index_url }}"
|
||||
|
||||
- name: Install core
|
||||
run: arduino-cli core install --additional-urls "${{ matrix.index_url }}" ${{ matrix.core }}
|
||||
|
||||
- name: Install ArduinoJson
|
||||
run: arduino-cli lib install ArduinoJson
|
||||
|
||||
- name: Install AsyncTCP (ESP32)
|
||||
if: ${{ matrix.core == 'esp32:esp32' }}
|
||||
run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ESP32Async/AsyncTCP#v3.3.2
|
||||
|
||||
- name: Install ESPAsyncTCP (ESP8266)
|
||||
if: ${{ matrix.core == 'esp8266:esp8266' }}
|
||||
run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/ESP32Async/ESPAsyncTCP#v2.0.0
|
||||
|
||||
- name: Install AsyncTCP (RP2040)
|
||||
if: ${{ matrix.core == 'rp2040:rp2040' }}
|
||||
run: ARDUINO_LIBRARY_ENABLE_UNSAFE_INSTALL=true arduino-cli lib install --git-url https://github.com/khoih-prog/AsyncTCP_RP2040W#v1.2.0
|
||||
|
||||
- name: Build CaptivePortal
|
||||
run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/CaptivePortal/CaptivePortal.ino"
|
||||
|
||||
- name: Build SimpleServer
|
||||
run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/SimpleServer/SimpleServer.ino"
|
||||
|
||||
- name: Build Filters
|
||||
run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/Filters/Filters.ino"
|
||||
|
||||
- name: Build StreamFiles
|
||||
run: arduino-cli compile --library . --warnings none -b ${{ matrix.board }} "examples/StreamFiles/StreamFiles.ino"
|
||||
|
||||
platformio:
|
||||
name: "pio:${{ matrix.env }}:${{ matrix.board }}"
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- env: ci-arduino-2
|
||||
board: esp32dev
|
||||
- env: ci-arduino-2
|
||||
board: esp32-s2-saola-1
|
||||
- env: ci-arduino-2
|
||||
board: esp32-s3-devkitc-1
|
||||
- env: ci-arduino-2
|
||||
board: esp32-c3-devkitc-02
|
||||
|
||||
- env: ci-arduino-3
|
||||
board: esp32dev
|
||||
- env: ci-arduino-3
|
||||
board: esp32-s2-saola-1
|
||||
- env: ci-arduino-3
|
||||
board: esp32-s3-devkitc-1
|
||||
- env: ci-arduino-3
|
||||
board: esp32-c3-devkitc-02
|
||||
- env: ci-arduino-3
|
||||
board: esp32-c6-devkitc-1
|
||||
- env: ci-arduino-3
|
||||
board: esp32-h2-devkitm-1
|
||||
|
||||
- env: ci-arduino-3-no-json
|
||||
board: esp32dev
|
||||
|
||||
- env: ci-arduino-311
|
||||
board: esp32dev
|
||||
- env: ci-arduino-311
|
||||
board: esp32-s2-saola-1
|
||||
- env: ci-arduino-311
|
||||
board: esp32-s3-devkitc-1
|
||||
- env: ci-arduino-311
|
||||
board: esp32-c3-devkitc-02
|
||||
- env: ci-arduino-311
|
||||
board: esp32-c6-devkitc-1
|
||||
- env: ci-arduino-311
|
||||
board: esp32-h2-devkitm-1
|
||||
|
||||
- env: ci-esp8266
|
||||
board: huzzah
|
||||
- env: ci-esp8266
|
||||
board: d1_mini
|
||||
|
||||
- env: ci-raspberrypi
|
||||
board: rpipicow
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Cache PlatformIO
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
key: ${{ runner.os }}-pio
|
||||
path: |
|
||||
~/.cache/pip
|
||||
~/.platformio
|
||||
|
||||
- name: Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.x"
|
||||
|
||||
- name: Build
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
pip install --upgrade platformio
|
||||
|
||||
- run: PLATFORMIO_SRC_DIR=examples/CaptivePortal PIO_BOARD=${{ matrix.board }} pio run -e ${{ matrix.env }}
|
||||
- run: PLATFORMIO_SRC_DIR=examples/SimpleServer PIO_BOARD=${{ matrix.board }} pio run -e ${{ matrix.env }}
|
||||
- run: PLATFORMIO_SRC_DIR=examples/Filters PIO_BOARD=${{ matrix.board }} pio run -e ${{ matrix.env }}
|
||||
- run: PLATFORMIO_SRC_DIR=examples/StreamFiles PIO_BOARD=${{ matrix.board }} pio run -e ${{ matrix.env }}
|
34
.github/workflows/push.yml
vendored
34
.github/workflows/push.yml
vendored
@ -1,34 +0,0 @@
|
||||
name: ESP Async Web Server CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- release/*
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
|
||||
build-arduino:
|
||||
name: Arduino for ${{ matrix.board }} on ${{ matrix.os }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest, windows-latest, macOS-latest]
|
||||
board: [esp32, esp8266]
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- name: Build Tests
|
||||
run: bash ./.github/scripts/on-push.sh ${{ matrix.board }} 0 1
|
||||
|
||||
# build-pio:
|
||||
# name: PlatformIO for ${{ matrix.board }} on ${{ matrix.os }}
|
||||
# runs-on: ${{ matrix.os }}
|
||||
# strategy:
|
||||
# matrix:
|
||||
# os: [ubuntu-latest, windows-latest, macOS-latest]
|
||||
# board: [esp32, esp8266]
|
||||
# steps:
|
||||
# - uses: actions/checkout@v1
|
||||
# - name: Build Tests
|
||||
# run: bash ./.github/scripts/on-push.sh ${{ matrix.board }} 1 1
|
24
.github/workflows/stale.yaml
vendored
Normal file
24
.github/workflows/stale.yaml
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
name: "Close stale issues and PRs"
|
||||
on:
|
||||
schedule:
|
||||
- cron: "30 1 * * *"
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
stale-issue-message: "This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days."
|
||||
stale-pr-message: "This PR is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days."
|
||||
close-issue-message: "This issue was closed because it has been stalled for 7 days with no activity."
|
||||
close-pr-message: "This PR was closed because it has been stalled for 7 days with no activity."
|
||||
days-before-issue-stale: 30
|
||||
days-before-pr-stale: 30
|
||||
days-before-issue-close: 7
|
||||
days-before-pr-close: 7
|
||||
|
||||
permissions:
|
||||
# contents: write # only for delete-branch option
|
||||
issues: write
|
||||
pull-requests: write
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,2 +1,5 @@
|
||||
.vscode
|
||||
.DS_Store
|
||||
.lh
|
||||
/.pio
|
||||
/.vscode
|
||||
/logs
|
||||
|
2
.gitpod.Dockerfile
vendored
Normal file
2
.gitpod.Dockerfile
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
FROM gitpod/workspace-python-3.11
|
||||
USER gitpod
|
9
.gitpod.yml
Normal file
9
.gitpod.yml
Normal file
@ -0,0 +1,9 @@
|
||||
tasks:
|
||||
- command: pip install --upgrade pip && pip install -U platformio && platformio run
|
||||
|
||||
image:
|
||||
file: .gitpod.Dockerfile
|
||||
|
||||
vscode:
|
||||
extensions:
|
||||
- shardulm94.trailing-spaces
|
46
.travis.yml
46
.travis.yml
@ -1,46 +0,0 @@
|
||||
sudo: false
|
||||
|
||||
language: python
|
||||
|
||||
os:
|
||||
- linux
|
||||
|
||||
git:
|
||||
depth: false
|
||||
|
||||
stages:
|
||||
- build
|
||||
|
||||
jobs:
|
||||
include:
|
||||
|
||||
- name: "Build Arduino ESP32"
|
||||
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
|
||||
stage: build
|
||||
script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp32
|
||||
|
||||
- name: "Build Arduino ESP8266"
|
||||
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
|
||||
stage: build
|
||||
script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp8266
|
||||
|
||||
- name: "Build Platformio ESP32"
|
||||
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
|
||||
stage: build
|
||||
script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp32 1 1
|
||||
|
||||
- name: "Build Platformio ESP8266"
|
||||
if: tag IS blank AND (type = pull_request OR (type = push AND branch = master))
|
||||
stage: build
|
||||
script: bash $TRAVIS_BUILD_DIR/.github/scripts/on-push.sh esp8266 1 1
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: change
|
||||
on_failure: change
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/60e65d0c78ea0a920347
|
||||
on_success: change # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: never # options: [always|never|change] default: always
|
129
CODE_OF_CONDUCT.md
Normal file
129
CODE_OF_CONDUCT.md
Normal file
@ -0,0 +1,129 @@
|
||||
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
https://sidweb.nl/cms3/en/contact.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
165
LICENSE
Normal file
165
LICENSE
Normal file
@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
1989
README.ESP32Async.md
Normal file
1989
README.ESP32Async.md
Normal file
File diff suppressed because it is too large
Load Diff
@ -1 +0,0 @@
|
||||
theme: jekyll-theme-cayman
|
@ -1,3 +0,0 @@
|
||||
COMPONENT_ADD_INCLUDEDIRS := src
|
||||
COMPONENT_SRCDIRS := src
|
||||
CXXFLAGS += -fno-rtti
|
BIN
docs/logo.png
Normal file
BIN
docs/logo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 479 KiB |
BIN
docs/logo.webp
Normal file
BIN
docs/logo.webp
Normal file
Binary file not shown.
After Width: | Height: | Size: 131 KiB |
BIN
docs/perf-c10-asynctcpsock.png
Normal file
BIN
docs/perf-c10-asynctcpsock.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 310 KiB |
BIN
docs/perf-c10.png
Normal file
BIN
docs/perf-c10.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 295 KiB |
@ -1,10 +1,13 @@
|
||||
#include <DNSServer.h>
|
||||
#ifdef ESP32
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <WiFi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <WebServer.h>
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
#include "ESPAsyncWebServer.h"
|
||||
|
||||
@ -12,36 +15,44 @@ DNSServer dnsServer;
|
||||
AsyncWebServer server(80);
|
||||
|
||||
class CaptiveRequestHandler : public AsyncWebHandler {
|
||||
public:
|
||||
CaptiveRequestHandler() {}
|
||||
virtual ~CaptiveRequestHandler() {}
|
||||
public:
|
||||
bool canHandle(__unused AsyncWebServerRequest* request) const override {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool canHandle(AsyncWebServerRequest *request){
|
||||
//request->addInterestingHeader("ANY");
|
||||
return true;
|
||||
}
|
||||
|
||||
void handleRequest(AsyncWebServerRequest *request) {
|
||||
AsyncResponseStream *response = request->beginResponseStream("text/html");
|
||||
response->print("<!DOCTYPE html><html><head><title>Captive Portal</title></head><body>");
|
||||
response->print("<p>This is out captive portal front page.</p>");
|
||||
response->printf("<p>You were trying to reach: http://%s%s</p>", request->host().c_str(), request->url().c_str());
|
||||
response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
|
||||
response->print("</body></html>");
|
||||
request->send(response);
|
||||
}
|
||||
void handleRequest(AsyncWebServerRequest* request) {
|
||||
AsyncResponseStream* response = request->beginResponseStream("text/html");
|
||||
response->print("<!DOCTYPE html><html><head><title>Captive Portal</title></head><body>");
|
||||
response->print("<p>This is out captive portal front page.</p>");
|
||||
response->printf("<p>You were trying to reach: http://%s%s</p>", request->host().c_str(), request->url().c_str());
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
|
||||
#endif
|
||||
response->print("</body></html>");
|
||||
request->send(response);
|
||||
}
|
||||
};
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println();
|
||||
Serial.println("Configuring access point...");
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
if (!WiFi.softAP("esp-captive")) {
|
||||
Serial.println("Soft AP creation failed.");
|
||||
while (1)
|
||||
;
|
||||
}
|
||||
|
||||
void setup(){
|
||||
//your other setup stuff...
|
||||
WiFi.softAP("esp-captive");
|
||||
dnsServer.start(53, "*", WiFi.softAPIP());
|
||||
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);//only when requested from AP
|
||||
//more handlers...
|
||||
#endif
|
||||
|
||||
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER); // only when requested from AP
|
||||
// more handlers...
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop(){
|
||||
void loop() {
|
||||
dnsServer.processNextRequest();
|
||||
}
|
||||
|
@ -1,221 +0,0 @@
|
||||
#include <ArduinoOTA.h>
|
||||
#ifdef ESP32
|
||||
#include <FS.h>
|
||||
#include <SPIFFS.h>
|
||||
#include <ESPmDNS.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#include <ESP8266mDNS.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <SPIFFSEditor.h>
|
||||
|
||||
// SKETCH BEGIN
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket ws("/ws");
|
||||
AsyncEventSource events("/events");
|
||||
|
||||
void onWsEvent(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len){
|
||||
if(type == WS_EVT_CONNECT){
|
||||
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
|
||||
client->printf("Hello Client %u :)", client->id());
|
||||
client->ping();
|
||||
} else if(type == WS_EVT_DISCONNECT){
|
||||
Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id());
|
||||
} else if(type == WS_EVT_ERROR){
|
||||
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t*)arg), (char*)data);
|
||||
} else if(type == WS_EVT_PONG){
|
||||
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len)?(char*)data:"");
|
||||
} else if(type == WS_EVT_DATA){
|
||||
AwsFrameInfo * info = (AwsFrameInfo*)arg;
|
||||
String msg = "";
|
||||
if(info->final && info->index == 0 && info->len == len){
|
||||
//the whole message is in a single frame and we got all of it's data
|
||||
Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT)?"text":"binary", info->len);
|
||||
|
||||
if(info->opcode == WS_TEXT){
|
||||
for(size_t i=0; i < info->len; i++) {
|
||||
msg += (char) data[i];
|
||||
}
|
||||
} else {
|
||||
char buff[3];
|
||||
for(size_t i=0; i < info->len; i++) {
|
||||
sprintf(buff, "%02x ", (uint8_t) data[i]);
|
||||
msg += buff ;
|
||||
}
|
||||
}
|
||||
Serial.printf("%s\n",msg.c_str());
|
||||
|
||||
if(info->opcode == WS_TEXT)
|
||||
client->text("I got your text message");
|
||||
else
|
||||
client->binary("I got your binary message");
|
||||
} else {
|
||||
//message is comprised of multiple frames or the frame is split into multiple packets
|
||||
if(info->index == 0){
|
||||
if(info->num == 0)
|
||||
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
|
||||
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
|
||||
}
|
||||
|
||||
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len);
|
||||
|
||||
if(info->opcode == WS_TEXT){
|
||||
for(size_t i=0; i < len; i++) {
|
||||
msg += (char) data[i];
|
||||
}
|
||||
} else {
|
||||
char buff[3];
|
||||
for(size_t i=0; i < len; i++) {
|
||||
sprintf(buff, "%02x ", (uint8_t) data[i]);
|
||||
msg += buff ;
|
||||
}
|
||||
}
|
||||
Serial.printf("%s\n",msg.c_str());
|
||||
|
||||
if((info->index + len) == info->len){
|
||||
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
|
||||
if(info->final){
|
||||
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
|
||||
if(info->message_opcode == WS_TEXT)
|
||||
client->text("I got your text message");
|
||||
else
|
||||
client->binary("I got your binary message");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const char* ssid = "*******";
|
||||
const char* password = "*******";
|
||||
const char * hostName = "esp-async";
|
||||
const char* http_username = "admin";
|
||||
const char* http_password = "admin";
|
||||
|
||||
void setup(){
|
||||
Serial.begin(115200);
|
||||
Serial.setDebugOutput(true);
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
WiFi.softAP(hostName);
|
||||
WiFi.begin(ssid, password);
|
||||
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||
Serial.printf("STA: Failed!\n");
|
||||
WiFi.disconnect(false);
|
||||
delay(1000);
|
||||
WiFi.begin(ssid, password);
|
||||
}
|
||||
|
||||
//Send OTA events to the browser
|
||||
ArduinoOTA.onStart([]() { events.send("Update Start", "ota"); });
|
||||
ArduinoOTA.onEnd([]() { events.send("Update End", "ota"); });
|
||||
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
||||
char p[32];
|
||||
sprintf(p, "Progress: %u%%\n", (progress/(total/100)));
|
||||
events.send(p, "ota");
|
||||
});
|
||||
ArduinoOTA.onError([](ota_error_t error) {
|
||||
if(error == OTA_AUTH_ERROR) events.send("Auth Failed", "ota");
|
||||
else if(error == OTA_BEGIN_ERROR) events.send("Begin Failed", "ota");
|
||||
else if(error == OTA_CONNECT_ERROR) events.send("Connect Failed", "ota");
|
||||
else if(error == OTA_RECEIVE_ERROR) events.send("Recieve Failed", "ota");
|
||||
else if(error == OTA_END_ERROR) events.send("End Failed", "ota");
|
||||
});
|
||||
ArduinoOTA.setHostname(hostName);
|
||||
ArduinoOTA.begin();
|
||||
|
||||
MDNS.addService("http","tcp",80);
|
||||
|
||||
SPIFFS.begin();
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
|
||||
events.onConnect([](AsyncEventSourceClient *client){
|
||||
client->send("hello!",NULL,millis(),1000);
|
||||
});
|
||||
server.addHandler(&events);
|
||||
|
||||
#ifdef ESP32
|
||||
server.addHandler(new SPIFFSEditor(SPIFFS, http_username,http_password));
|
||||
#elif defined(ESP8266)
|
||||
server.addHandler(new SPIFFSEditor(http_username,http_password));
|
||||
#endif
|
||||
|
||||
server.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", String(ESP.getFreeHeap()));
|
||||
});
|
||||
|
||||
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm");
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *request){
|
||||
Serial.printf("NOT_FOUND: ");
|
||||
if(request->method() == HTTP_GET)
|
||||
Serial.printf("GET");
|
||||
else if(request->method() == HTTP_POST)
|
||||
Serial.printf("POST");
|
||||
else if(request->method() == HTTP_DELETE)
|
||||
Serial.printf("DELETE");
|
||||
else if(request->method() == HTTP_PUT)
|
||||
Serial.printf("PUT");
|
||||
else if(request->method() == HTTP_PATCH)
|
||||
Serial.printf("PATCH");
|
||||
else if(request->method() == HTTP_HEAD)
|
||||
Serial.printf("HEAD");
|
||||
else if(request->method() == HTTP_OPTIONS)
|
||||
Serial.printf("OPTIONS");
|
||||
else
|
||||
Serial.printf("UNKNOWN");
|
||||
Serial.printf(" http://%s%s\n", request->host().c_str(), request->url().c_str());
|
||||
|
||||
if(request->contentLength()){
|
||||
Serial.printf("_CONTENT_TYPE: %s\n", request->contentType().c_str());
|
||||
Serial.printf("_CONTENT_LENGTH: %u\n", request->contentLength());
|
||||
}
|
||||
|
||||
int headers = request->headers();
|
||||
int i;
|
||||
for(i=0;i<headers;i++){
|
||||
AsyncWebHeader* h = request->getHeader(i);
|
||||
Serial.printf("_HEADER[%s]: %s\n", h->name().c_str(), h->value().c_str());
|
||||
}
|
||||
|
||||
int params = request->params();
|
||||
for(i=0;i<params;i++){
|
||||
AsyncWebParameter* p = request->getParam(i);
|
||||
if(p->isFile()){
|
||||
Serial.printf("_FILE[%s]: %s, size: %u\n", p->name().c_str(), p->value().c_str(), p->size());
|
||||
} else if(p->isPost()){
|
||||
Serial.printf("_POST[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
} else {
|
||||
Serial.printf("_GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
|
||||
}
|
||||
}
|
||||
|
||||
request->send(404);
|
||||
});
|
||||
server.onFileUpload([](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){
|
||||
if(!index)
|
||||
Serial.printf("UploadStart: %s\n", filename.c_str());
|
||||
Serial.printf("%s", (const char*)data);
|
||||
if(final)
|
||||
Serial.printf("UploadEnd: %s (%u)\n", filename.c_str(), index+len);
|
||||
});
|
||||
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total){
|
||||
if(!index)
|
||||
Serial.printf("BodyStart: %u\n", total);
|
||||
Serial.printf("%s", (const char*)data);
|
||||
if(index + len == total)
|
||||
Serial.printf("BodyEnd: %u\n", total);
|
||||
});
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop(){
|
||||
ArduinoOTA.handle();
|
||||
ws.cleanupClients();
|
||||
}
|
@ -1,2 +0,0 @@
|
||||
/*.js.gz
|
||||
/.exclude.files
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Before Width: | Height: | Size: 1.1 KiB |
@ -1,131 +0,0 @@
|
||||
<!--
|
||||
FSWebServer - Example Index Page
|
||||
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
|
||||
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
|
||||
-->
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
|
||||
<title>WebSocketTester</title>
|
||||
<style type="text/css" media="screen">
|
||||
body {
|
||||
margin:0;
|
||||
padding:0;
|
||||
background-color: black;
|
||||
}
|
||||
|
||||
#dbg, #input_div, #input_el {
|
||||
font-family: monaco;
|
||||
font-size: 12px;
|
||||
line-height: 13px;
|
||||
color: #AAA;
|
||||
}
|
||||
|
||||
#dbg, #input_div {
|
||||
margin:0;
|
||||
padding:0;
|
||||
padding-left:4px;
|
||||
}
|
||||
|
||||
#input_el {
|
||||
width:98%;
|
||||
background-color: rgba(0,0,0,0);
|
||||
border: 0px;
|
||||
}
|
||||
#input_el:focus {
|
||||
outline: none;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
var ws = null;
|
||||
function ge(s){ return document.getElementById(s);}
|
||||
function ce(s){ return document.createElement(s);}
|
||||
function stb(){ window.scrollTo(0, document.body.scrollHeight || document.documentElement.scrollHeight); }
|
||||
function sendBlob(str){
|
||||
var buf = new Uint8Array(str.length);
|
||||
for (var i = 0; i < str.length; ++i) buf[i] = str.charCodeAt(i);
|
||||
ws.send(buf);
|
||||
}
|
||||
function addMessage(m){
|
||||
var msg = ce("div");
|
||||
msg.innerText = m;
|
||||
ge("dbg").appendChild(msg);
|
||||
stb();
|
||||
}
|
||||
function startSocket(){
|
||||
ws = new WebSocket('ws://'+document.location.host+'/ws',['arduino']);
|
||||
ws.binaryType = "arraybuffer";
|
||||
ws.onopen = function(e){
|
||||
addMessage("Connected");
|
||||
};
|
||||
ws.onclose = function(e){
|
||||
addMessage("Disconnected");
|
||||
};
|
||||
ws.onerror = function(e){
|
||||
console.log("ws error", e);
|
||||
addMessage("Error");
|
||||
};
|
||||
ws.onmessage = function(e){
|
||||
var msg = "";
|
||||
if(e.data instanceof ArrayBuffer){
|
||||
msg = "BIN:";
|
||||
var bytes = new Uint8Array(e.data);
|
||||
for (var i = 0; i < bytes.length; i++) {
|
||||
msg += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
} else {
|
||||
msg = "TXT:"+e.data;
|
||||
}
|
||||
addMessage(msg);
|
||||
};
|
||||
ge("input_el").onkeydown = function(e){
|
||||
stb();
|
||||
if(e.keyCode == 13 && ge("input_el").value != ""){
|
||||
ws.send(ge("input_el").value);
|
||||
ge("input_el").value = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
function startEvents(){
|
||||
var es = new EventSource('/events');
|
||||
es.onopen = function(e) {
|
||||
addMessage("Events Opened");
|
||||
};
|
||||
es.onerror = function(e) {
|
||||
if (e.target.readyState != EventSource.OPEN) {
|
||||
addMessage("Events Closed");
|
||||
}
|
||||
};
|
||||
es.onmessage = function(e) {
|
||||
addMessage("Event: " + e.data);
|
||||
};
|
||||
es.addEventListener('ota', function(e) {
|
||||
addMessage("Event[ota]: " + e.data);
|
||||
}, false);
|
||||
}
|
||||
function onBodyLoad(){
|
||||
startSocket();
|
||||
startEvents();
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body id="body" onload="onBodyLoad()">
|
||||
<pre id="dbg"></pre>
|
||||
<div id="input_div">
|
||||
$<input type="text" value="" id="input_el">
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
124
examples/Filters/Filters.ino
Normal file
124
examples/Filters/Filters.ino
Normal file
@ -0,0 +1,124 @@
|
||||
// Reproduced issue https://github.com/ESP32Async/ESPAsyncWebServer/issues/26
|
||||
|
||||
#include <DNSServer.h>
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <WiFi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <WebServer.h>
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
#include "ESPAsyncWebServer.h"
|
||||
|
||||
DNSServer dnsServer;
|
||||
AsyncWebServer server(80);
|
||||
|
||||
class CaptiveRequestHandler : public AsyncWebHandler {
|
||||
public:
|
||||
bool canHandle(__unused AsyncWebServerRequest* request) const override {
|
||||
return true;
|
||||
}
|
||||
|
||||
void handleRequest(AsyncWebServerRequest* request) override {
|
||||
AsyncResponseStream* response = request->beginResponseStream("text/html");
|
||||
response->print("<!DOCTYPE html><html><head><title>Captive Portal</title></head><body>");
|
||||
response->print("<p>This is out captive portal front page.</p>");
|
||||
response->printf("<p>You were trying to reach: http://%s%s</p>", request->host().c_str(), request->url().c_str());
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
response->printf("<p>Try opening <a href='http://%s'>this link</a> instead</p>", WiFi.softAPIP().toString().c_str());
|
||||
#endif
|
||||
response->print("</body></html>");
|
||||
request->send(response);
|
||||
}
|
||||
};
|
||||
|
||||
bool hit1 = false;
|
||||
bool hit2 = false;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
server
|
||||
.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
Serial.println("Captive portal request...");
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println("WiFi.localIP(): " + WiFi.localIP().toString());
|
||||
#endif
|
||||
Serial.println("request->client()->localIP(): " + request->client()->localIP().toString());
|
||||
#if ESP_IDF_VERSION_MAJOR >= 5
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type()));
|
||||
#endif
|
||||
Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type()));
|
||||
#endif
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER");
|
||||
Serial.println(WiFi.localIP() == request->client()->localIP());
|
||||
Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString());
|
||||
#endif
|
||||
request->send(200, "text/plain", "This is the captive portal");
|
||||
hit1 = true;
|
||||
})
|
||||
.setFilter(ON_AP_FILTER);
|
||||
|
||||
server
|
||||
.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
Serial.println("Website request...");
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println("WiFi.localIP(): " + WiFi.localIP().toString());
|
||||
#endif
|
||||
Serial.println("request->client()->localIP(): " + request->client()->localIP().toString());
|
||||
#if ESP_IDF_VERSION_MAJOR >= 5
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println("WiFi.type(): " + String((int)WiFi.localIP().type()));
|
||||
#endif
|
||||
Serial.println("request->client()->type(): " + String((int)request->client()->localIP().type()));
|
||||
#endif
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
Serial.println(WiFi.localIP() == request->client()->localIP() ? "should be: ON_STA_FILTER" : "should be: ON_AP_FILTER");
|
||||
Serial.println(WiFi.localIP() == request->client()->localIP());
|
||||
Serial.println(WiFi.localIP().toString() == request->client()->localIP().toString());
|
||||
#endif
|
||||
request->send(200, "text/plain", "This is the website");
|
||||
hit2 = true;
|
||||
})
|
||||
.setFilter(ON_STA_FILTER);
|
||||
|
||||
// assert(WiFi.softAP("esp-captive-portal"));
|
||||
// dnsServer.start(53, "*", WiFi.softAPIP());
|
||||
// server.begin();
|
||||
// Serial.println("Captive portal started!");
|
||||
|
||||
// while (!hit1) {
|
||||
// dnsServer.processNextRequest();
|
||||
// yield();
|
||||
// }
|
||||
// delay(1000); // Wait for the client to process the response
|
||||
|
||||
// Serial.println("Captive portal opened, stopping it and connecting to WiFi...");
|
||||
// dnsServer.stop();
|
||||
// WiFi.softAPdisconnect();
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
WiFi.persistent(false);
|
||||
WiFi.begin("IoT");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
}
|
||||
Serial.println("Connected to WiFi with IP address: " + WiFi.localIP().toString());
|
||||
#endif
|
||||
|
||||
server.begin();
|
||||
|
||||
// while (!hit2) {
|
||||
// delay(10);
|
||||
// }
|
||||
// delay(1000); // Wait for the client to process the response
|
||||
// ESP.restart();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
99
examples/Issue162/Issue162.ino
Normal file
99
examples/Issue162/Issue162.ino
Normal file
@ -0,0 +1,99 @@
|
||||
/**
|
||||
*
|
||||
* Connect to AP and run in bash:
|
||||
*
|
||||
* > while true; do echo "PING"; sleep 0.1; done | websocat ws://192.168.4.1/ws
|
||||
*
|
||||
*/
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP8266
|
||||
#include <ESP8266WiFi.h>
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include <list>
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket ws("/ws");
|
||||
|
||||
void onWsEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||
if (type == WS_EVT_CONNECT) {
|
||||
Serial.printf("Client #%" PRIu32 " connected.\n", client->id());
|
||||
} else if (type == WS_EVT_DISCONNECT) {
|
||||
Serial.printf("Client #%" PRIu32 " disconnected.\n", client->id());
|
||||
} else if (type == WS_EVT_ERROR) {
|
||||
Serial.printf("Client #%" PRIu32 " error.\n", client->id());
|
||||
} else if (type == WS_EVT_DATA) {
|
||||
Serial.printf("Client #%" PRIu32 " len: %u\n", client->id(), len);
|
||||
} else if (type == WS_EVT_PONG) {
|
||||
Serial.printf("Client #%" PRIu32 " pong.\n", client->id());
|
||||
} else if (type == WS_EVT_PING) {
|
||||
Serial.printf("Client #%" PRIu32 " ping.\n", client->id());
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP("esp-captive");
|
||||
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
|
||||
server.on("/close_all_ws_clients", HTTP_GET | HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
Serial.println("Closing all WebSocket clients...");
|
||||
ws.closeAll();
|
||||
request->send(200, "application/json", "{\"status\":\"all clients closed\"}");
|
||||
});
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/html", R"rawliteral(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head></head>
|
||||
<script>
|
||||
let ws = new WebSocket("ws://" + window.location.host + "/ws");
|
||||
|
||||
ws.addEventListener("open", (e) => {
|
||||
console.log("WebSocket connected", e);
|
||||
});
|
||||
|
||||
ws.addEventListener("error", (e) => {
|
||||
console.log("WebSocket error", e);
|
||||
});
|
||||
|
||||
ws.addEventListener("close", (e) => {
|
||||
console.log("WebSocket close", e);
|
||||
});
|
||||
|
||||
ws.addEventListener("message", (e) => {
|
||||
console.log("WebSocket message", e);
|
||||
});
|
||||
|
||||
function closeAllWsClients() {
|
||||
fetch("/close_all_ws_clients", {
|
||||
method : "POST",
|
||||
});
|
||||
};
|
||||
</script>
|
||||
<body>
|
||||
<button onclick = "closeAllWsClients()" style = "width: 200px"> ws close all</button><p></p>
|
||||
</body>
|
||||
</html>
|
||||
)rawliteral");
|
||||
});
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
uint32_t lastTime = 0;
|
||||
void loop() {
|
||||
if (millis() - lastTime > 5000) {
|
||||
lastTime = millis();
|
||||
Serial.printf("Client count: %u\n", ws.count());
|
||||
}
|
||||
ws.cleanupClients();
|
||||
}
|
127
examples/Issue85/Issue85.ino
Normal file
127
examples/Issue85/Issue85.ino
Normal file
@ -0,0 +1,127 @@
|
||||
/**
|
||||
*
|
||||
* Connect to AP and run in bash:
|
||||
*
|
||||
* > while true; do echo "PING"; sleep 0.1; done | websocat ws://192.168.4.1/ws
|
||||
*
|
||||
*/
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP8266
|
||||
#include <ESP8266WiFi.h>
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include <list>
|
||||
|
||||
size_t msgCount = 0;
|
||||
size_t window = 100;
|
||||
std::list<uint32_t> times;
|
||||
|
||||
void connect_wifi() {
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP("esp-captive");
|
||||
|
||||
// Serial.print("Connecting");
|
||||
// while (WiFi.status() != WL_CONNECTED) {
|
||||
// delay(500);
|
||||
// Serial.print(".");
|
||||
// }
|
||||
// Serial.println();
|
||||
|
||||
// Serial.print("Connected, IP address: ");
|
||||
// Serial.println(WiFi.localIP());
|
||||
}
|
||||
|
||||
void notFound(AsyncWebServerRequest* request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket ws("/ws");
|
||||
|
||||
// initial stack
|
||||
char* stack_start;
|
||||
|
||||
void printStackSize() {
|
||||
char stack;
|
||||
Serial.print(F("stack size "));
|
||||
Serial.print(stack_start - &stack);
|
||||
Serial.print(F(" | Heap free:"));
|
||||
Serial.print(ESP.getFreeHeap());
|
||||
#ifdef ESP8266
|
||||
Serial.print(F(" frag:"));
|
||||
Serial.print(ESP.getHeapFragmentation());
|
||||
Serial.print(F(" maxFreeBlock:"));
|
||||
Serial.print(ESP.getMaxFreeBlockSize());
|
||||
#endif
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void onWsEventEmpty(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||
msgCount++;
|
||||
Serial.printf("count: %d\n", msgCount);
|
||||
|
||||
times.push_back(millis());
|
||||
while (times.size() > window)
|
||||
times.pop_front();
|
||||
if (times.size() == window)
|
||||
Serial.printf("%f req/s\n", 1000.0 * window / (times.back() - times.front()));
|
||||
|
||||
printStackSize();
|
||||
|
||||
client->text("PONG");
|
||||
}
|
||||
|
||||
void serve_upload(AsyncWebServerRequest* request, const String& filename, size_t index, uint8_t* data, size_t len, bool final) {
|
||||
Serial.print("> onUpload ");
|
||||
Serial.print("index: ");
|
||||
Serial.print(index);
|
||||
Serial.print(" len:");
|
||||
Serial.print(len);
|
||||
Serial.print(" final:");
|
||||
Serial.print(final);
|
||||
Serial.println();
|
||||
}
|
||||
|
||||
void setup() {
|
||||
char stack;
|
||||
stack_start = &stack;
|
||||
|
||||
Serial.begin(115200);
|
||||
Serial.println("\n\n\nStart");
|
||||
Serial.printf("stack_start: %p\n", stack_start);
|
||||
|
||||
connect_wifi();
|
||||
|
||||
server.onNotFound(notFound);
|
||||
|
||||
ws.onEvent(onWsEventEmpty);
|
||||
server.addHandler(&ws);
|
||||
|
||||
server.on("/upload", HTTP_POST, [](AsyncWebServerRequest* request) { request->send(200); }, serve_upload);
|
||||
|
||||
server.begin();
|
||||
Serial.println("Server started");
|
||||
}
|
||||
|
||||
String msg = "";
|
||||
uint32_t count = 0;
|
||||
void loop() {
|
||||
// ws.cleanupClients();
|
||||
// count += 1;
|
||||
// // Concatenate some string, and clear it after some time
|
||||
// static unsigned long millis_string = millis();
|
||||
// if (millis() - millis_string > 1) {
|
||||
// millis_string += 100;
|
||||
// if (count % 100 == 0) {
|
||||
// // printStackSize();
|
||||
// // Serial.print(msg);
|
||||
// msg = String();
|
||||
// } else {
|
||||
// msg += 'T';
|
||||
// }
|
||||
// }
|
||||
}
|
257
examples/SSE_perftest/SSE_perftest.ino
Normal file
257
examples/SSE_perftest/SSE_perftest.ino
Normal file
@ -0,0 +1,257 @@
|
||||
//
|
||||
// SSE server with a load generator
|
||||
// it will auto adjust message push rate to minimize discards across all connected clients
|
||||
// per second stats is printed to a serial console and also published as SSE ping message
|
||||
// open /sse URL to start events generator
|
||||
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <WiFi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <WebServer.h>
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
#include <ArduinoJson.h>
|
||||
#include <AsyncJson.h>
|
||||
#include <AsyncMessagePack.h>
|
||||
#endif
|
||||
|
||||
#include <LittleFS.h>
|
||||
|
||||
const char* htmlContent PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sample HTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
const char* staticContent PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sample HTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, %IP%</h1>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
AsyncWebServer server(80);
|
||||
AsyncEventSource events("/events");
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
const char* PARAM_MESSAGE PROGMEM = "message";
|
||||
const char* SSE_HTLM PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Server-Sent Events</title>
|
||||
<script>
|
||||
if (!!window.EventSource) {
|
||||
var source = new EventSource('/events');
|
||||
source.addEventListener('open', function(e) {
|
||||
console.log("Events Connected");
|
||||
}, false);
|
||||
source.addEventListener('error', function(e) {
|
||||
if (e.target.readyState != EventSource.OPEN) {
|
||||
console.log("Events Disconnected");
|
||||
}
|
||||
}, false);
|
||||
source.addEventListener('message', function(e) {
|
||||
console.log("message", e);
|
||||
}, false);
|
||||
source.addEventListener('heartbeat', function(e) {
|
||||
console.log("heartbeat", e.data);
|
||||
}, false);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Open your browser console!</h1>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
static const char* SSE_MSG = R"(Alice felt that this could not be denied, so she tried another question. 'What sort of people live about here?' 'In THAT direction,' the Cat said, waving its right paw round, 'lives a Hatter: and in THAT direction,' waving the other paw, 'lives a March Hare. Visit either you like: they're both mad.'
|
||||
'But I don't want to go among mad people,' Alice remarked. 'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.' 'How do you know I'm mad?' said Alice.
|
||||
'You must be,' said the Cat, `or you wouldn't have come here.' Alice didn't think that proved it at all; however, she went on 'And how do you know that you're mad?' 'To begin with,' said the Cat, 'a dog's not mad. You grant that?'
|
||||
)";
|
||||
|
||||
void notFound(AsyncWebServerRequest* request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
static const char characters[] = "0123456789ABCDEF";
|
||||
static size_t charactersIndex = 0;
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
/*
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin("SSID", "passwd");
|
||||
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||
Serial.printf("WiFi Failed!\n");
|
||||
return;
|
||||
}
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
*/
|
||||
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP("esp-captive");
|
||||
#endif
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/html", staticContent);
|
||||
});
|
||||
|
||||
events.onConnect([](AsyncEventSourceClient* client) {
|
||||
if (client->lastId()) {
|
||||
Serial.printf("SSE Client reconnected! Last message ID that it gat is: %" PRIu32 "\n", client->lastId());
|
||||
}
|
||||
client->send("hello!", NULL, millis(), 1000);
|
||||
});
|
||||
|
||||
server.on("/sse", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/html", SSE_HTLM);
|
||||
});
|
||||
|
||||
// go to http://192.168.4.1/sse
|
||||
server.addHandler(&events);
|
||||
|
||||
server.onNotFound(notFound);
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
uint32_t lastSSE = 0;
|
||||
uint32_t deltaSSE = 25;
|
||||
uint32_t messagesSSE = 4; // how many messages to q each time
|
||||
uint32_t sse_disc{0}, sse_enq{0}, sse_penq{0}, sse_second{0};
|
||||
|
||||
AsyncEventSource::SendStatus enqueue() {
|
||||
AsyncEventSource::SendStatus state = events.send(SSE_MSG, "message");
|
||||
if (state == AsyncEventSource::SendStatus::DISCARDED)
|
||||
++sse_disc;
|
||||
else if (state == AsyncEventSource::SendStatus::ENQUEUED) {
|
||||
++sse_enq;
|
||||
} else
|
||||
++sse_penq;
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
uint32_t now = millis();
|
||||
if (now - lastSSE >= deltaSSE) {
|
||||
// enqueue messages
|
||||
for (uint32_t i = 0; i != messagesSSE; ++i) {
|
||||
auto err = enqueue();
|
||||
if (err == AsyncEventSource::SendStatus::DISCARDED || err == AsyncEventSource::SendStatus::PARTIALLY_ENQUEUED) {
|
||||
// throttle messaging a bit
|
||||
lastSSE = now + deltaSSE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
lastSSE = millis();
|
||||
}
|
||||
|
||||
if (now - sse_second > 1000) {
|
||||
String s;
|
||||
s.reserve(100);
|
||||
s = "Ping:";
|
||||
s += now / 1000;
|
||||
s += " clients:";
|
||||
s += events.count();
|
||||
s += " disc:";
|
||||
s += sse_disc;
|
||||
s += " enq:";
|
||||
s += sse_enq;
|
||||
s += " partial:";
|
||||
s += sse_penq;
|
||||
s += " avg wait:";
|
||||
s += events.avgPacketsWaiting();
|
||||
s += " heap:";
|
||||
s += ESP.getFreeHeap() / 1024;
|
||||
|
||||
events.send(s, "heartbeat", now);
|
||||
Serial.println();
|
||||
Serial.println(s);
|
||||
|
||||
// if we see discards or partial enqueues, let's decrease message rate, else - increase. So that we can come to a max sustained message rate
|
||||
if (sse_disc || sse_penq)
|
||||
++deltaSSE;
|
||||
else if (deltaSSE > 5)
|
||||
--deltaSSE;
|
||||
|
||||
sse_disc = sse_enq = sse_penq = 0;
|
||||
sse_second = now;
|
||||
}
|
||||
}
|
794
examples/SimpleServer/SimpleServer.ino
Normal file
794
examples/SimpleServer/SimpleServer.ino
Normal file
@ -0,0 +1,794 @@
|
||||
//
|
||||
// A simple server implementation showing how to:
|
||||
// * serve static messages
|
||||
// * read GET and POST parameters
|
||||
// * handle missing pages / 404s
|
||||
//
|
||||
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <WiFi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <WebServer.h>
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
#include <ArduinoJson.h>
|
||||
#include <AsyncJson.h>
|
||||
#include <AsyncMessagePack.h>
|
||||
#endif
|
||||
|
||||
#include <LittleFS.h>
|
||||
|
||||
const char* htmlContent PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sample HTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin euismod, purus a euismod
|
||||
rhoncus, urna ipsum cursus massa, eu dictum tellus justo ac justo. Quisque ullamcorper
|
||||
arcu nec tortor ullamcorper, vel fermentum justo fermentum. Vivamus sed velit ut elit
|
||||
accumsan congue ut ut enim. Ut eu justo eu lacus varius gravida ut a tellus. Nulla facilisi.
|
||||
Integer auctor consectetur ultricies. Fusce feugiat, mi sit amet bibendum viverra, orci leo
|
||||
dapibus elit, id varius sem dui id lacus.</p>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
const size_t htmlContentLength = strlen_P(htmlContent);
|
||||
|
||||
const char* staticContent PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sample HTML</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, %IP%</h1>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
AsyncWebServer server(80);
|
||||
AsyncEventSource events("/events");
|
||||
AsyncWebSocket ws("/ws");
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Middlewares
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// log incoming requests
|
||||
AsyncLoggingMiddleware requestLogger;
|
||||
|
||||
// CORS
|
||||
AsyncCorsMiddleware cors;
|
||||
|
||||
// maximum 5 requests per 10 seconds
|
||||
AsyncRateLimitMiddleware rateLimit;
|
||||
|
||||
// filter out specific headers from the incoming request
|
||||
AsyncHeaderFilterMiddleware headerFilter;
|
||||
|
||||
// remove all headers from the incoming request except the ones provided in the constructor
|
||||
AsyncHeaderFreeMiddleware headerFree;
|
||||
|
||||
// basicAuth
|
||||
AsyncAuthenticationMiddleware basicAuth;
|
||||
AsyncAuthenticationMiddleware basicAuthHash;
|
||||
|
||||
// simple digest authentication
|
||||
AsyncAuthenticationMiddleware digestAuth;
|
||||
AsyncAuthenticationMiddleware digestAuthHash;
|
||||
|
||||
// complex authentication which adds request attributes for the next middlewares and handler
|
||||
AsyncMiddlewareFunction complexAuth([](AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
if (!request->authenticate("user", "password")) {
|
||||
return request->requestAuthentication();
|
||||
}
|
||||
request->setAttribute("user", "Mathieu");
|
||||
request->setAttribute("role", "staff");
|
||||
|
||||
next();
|
||||
|
||||
request->getResponse()->addHeader("X-Rate-Limit", "200");
|
||||
});
|
||||
|
||||
AsyncAuthorizationMiddleware authz([](AsyncWebServerRequest* request) { return request->getAttribute("role") == "staff"; });
|
||||
|
||||
int wsClients = 0;
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
const char* PARAM_MESSAGE PROGMEM = "message";
|
||||
const char* SSE_HTLM PROGMEM = R"(
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Server-Sent Events</title>
|
||||
<script>
|
||||
if (!!window.EventSource) {
|
||||
var source = new EventSource('/events');
|
||||
source.addEventListener('open', function(e) {
|
||||
console.log("Events Connected");
|
||||
}, false);
|
||||
source.addEventListener('error', function(e) {
|
||||
if (e.target.readyState != EventSource.OPEN) {
|
||||
console.log("Events Disconnected");
|
||||
}
|
||||
}, false);
|
||||
source.addEventListener('message', function(e) {
|
||||
console.log("message", e.data);
|
||||
}, false);
|
||||
source.addEventListener('heartbeat', function(e) {
|
||||
console.log("heartbeat", e.data);
|
||||
}, false);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Open your browser console!</h1>
|
||||
</body>
|
||||
</html>
|
||||
)";
|
||||
|
||||
void notFound(AsyncWebServerRequest* request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
AsyncCallbackJsonWebHandler* jsonHandler = new AsyncCallbackJsonWebHandler("/json2");
|
||||
AsyncCallbackMessagePackWebHandler* msgPackHandler = new AsyncCallbackMessagePackWebHandler("/msgpack2");
|
||||
#endif
|
||||
|
||||
static const char characters[] = "0123456789ABCDEF";
|
||||
static size_t charactersIndex = 0;
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
// WiFi.mode(WIFI_STA);
|
||||
// WiFi.begin("YOUR_SSID", "YOUR_PASSWORD");
|
||||
// if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||
// Serial.printf("WiFi Failed!\n");
|
||||
// return;
|
||||
// }
|
||||
// Serial.print("IP Address: ");
|
||||
// Serial.println(WiFi.localIP());
|
||||
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP("esp-captive");
|
||||
#endif
|
||||
|
||||
#ifdef ESP32
|
||||
LittleFS.begin(true);
|
||||
#else
|
||||
LittleFS.begin();
|
||||
#endif
|
||||
|
||||
{
|
||||
File f = LittleFS.open("/index.txt", "w");
|
||||
if (f) {
|
||||
for (size_t c = 0; c < sizeof(characters); c++) {
|
||||
for (size_t i = 0; i < 1024; i++) {
|
||||
f.print(characters[c]);
|
||||
}
|
||||
}
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
File f = LittleFS.open("/index.html", "w");
|
||||
if (f) {
|
||||
f.print(staticContent);
|
||||
f.close();
|
||||
}
|
||||
}
|
||||
|
||||
// curl -v -X GET http://192.168.4.1/handler-not-sending-response
|
||||
server.on("/handler-not-sending-response", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
// handler forgot to send a response to the client => 501 Not Implemented
|
||||
});
|
||||
|
||||
// This is possible to replace a response.
|
||||
// the previous one will be deleted.
|
||||
// response sending happens when the handler returns.
|
||||
// curl -v -X GET http://192.168.4.1/replace
|
||||
server.on("/replace", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world");
|
||||
// oups! finally we want to send a different response
|
||||
request->send(400, "text/plain", "validation error");
|
||||
#ifndef TARGET_RP2040
|
||||
Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap());
|
||||
#endif
|
||||
});
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// Request header manipulations
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
|
||||
// curl -v -X GET -H "x-remove-me: value" http://192.168.4.1/headers
|
||||
server.on("/headers", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
Serial.printf("Request Headers:\n");
|
||||
for (auto& h : request->getHeaders())
|
||||
Serial.printf("Request Header: %s = %s\n", h.name().c_str(), h.value().c_str());
|
||||
|
||||
// remove x-remove-me header
|
||||
request->removeHeader("x-remove-me");
|
||||
Serial.printf("Request Headers:\n");
|
||||
for (auto& h : request->getHeaders())
|
||||
Serial.printf("Request Header: %s = %s\n", h.name().c_str(), h.value().c_str());
|
||||
|
||||
std::vector<const char*> headers;
|
||||
request->getHeaderNames(headers);
|
||||
for (auto& h : headers)
|
||||
Serial.printf("Request Header Name: %s\n", h);
|
||||
|
||||
request->send(200);
|
||||
});
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
// Middlewares at server level (will apply to all requests)
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
|
||||
requestLogger.setOutput(Serial);
|
||||
|
||||
basicAuth.setUsername("admin");
|
||||
basicAuth.setPassword("admin");
|
||||
basicAuth.setRealm("MyApp");
|
||||
basicAuth.setAuthFailureMessage("Authentication failed");
|
||||
basicAuth.setAuthType(AsyncAuthType::AUTH_BASIC);
|
||||
basicAuth.generateHash();
|
||||
|
||||
basicAuthHash.setUsername("admin");
|
||||
basicAuthHash.setPasswordHash("YWRtaW46YWRtaW4="); // BASE64(admin:admin)
|
||||
basicAuthHash.setRealm("MyApp");
|
||||
basicAuthHash.setAuthFailureMessage("Authentication failed");
|
||||
basicAuthHash.setAuthType(AsyncAuthType::AUTH_BASIC);
|
||||
|
||||
digestAuth.setUsername("admin");
|
||||
digestAuth.setPassword("admin");
|
||||
digestAuth.setRealm("MyApp");
|
||||
digestAuth.setAuthFailureMessage("Authentication failed");
|
||||
digestAuth.setAuthType(AsyncAuthType::AUTH_DIGEST);
|
||||
digestAuth.generateHash();
|
||||
|
||||
digestAuthHash.setUsername("admin");
|
||||
digestAuthHash.setPasswordHash("f499b71f9a36d838b79268e145e132f7"); // MD5(user:realm:pass)
|
||||
digestAuthHash.setRealm("MyApp");
|
||||
digestAuthHash.setAuthFailureMessage("Authentication failed");
|
||||
digestAuthHash.setAuthType(AsyncAuthType::AUTH_DIGEST);
|
||||
|
||||
rateLimit.setMaxRequests(5);
|
||||
rateLimit.setWindowSize(10);
|
||||
|
||||
headerFilter.filter("X-Remove-Me");
|
||||
headerFree.keep("X-Keep-Me");
|
||||
headerFree.keep("host");
|
||||
|
||||
cors.setOrigin("http://192.168.4.1");
|
||||
cors.setMethods("POST, GET, OPTIONS, DELETE");
|
||||
cors.setHeaders("X-Custom-Header");
|
||||
cors.setAllowCredentials(false);
|
||||
cors.setMaxAge(600);
|
||||
|
||||
#ifndef PERF_TEST
|
||||
// global middleware
|
||||
server.addMiddleware(&requestLogger);
|
||||
server.addMiddlewares({&rateLimit, &cors, &headerFilter});
|
||||
#endif
|
||||
|
||||
// Test CORS preflight request
|
||||
// curl -v -X OPTIONS -H "origin: http://192.168.4.1" http://192.168.4.1/middleware/cors
|
||||
server.on("/middleware/cors", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world!");
|
||||
});
|
||||
|
||||
// curl -v -X GET -H "x-remove-me: value" http://192.168.4.1/middleware/test-header-filter
|
||||
// - requestLogger will log the incoming headers (including x-remove-me)
|
||||
// - headerFilter will remove x-remove-me header
|
||||
// - handler will log the remaining headers
|
||||
server.on("/middleware/test-header-filter", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
for (auto& h : request->getHeaders())
|
||||
Serial.printf("Request Header: %s = %s\n", h.name().c_str(), h.value().c_str());
|
||||
request->send(200);
|
||||
});
|
||||
|
||||
// curl -v -X GET -H "x-keep-me: value" http://192.168.4.1/middleware/test-header-free
|
||||
// - requestLogger will log the incoming headers (including x-keep-me)
|
||||
// - headerFree will remove all headers except x-keep-me and host
|
||||
// - handler will log the remaining headers (x-keep-me and host)
|
||||
server.on("/middleware/test-header-free", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
for (auto& h : request->getHeaders())
|
||||
Serial.printf("Request Header: %s = %s\n", h.name().c_str(), h.value().c_str());
|
||||
request->send(200);
|
||||
})
|
||||
.addMiddleware(&headerFree);
|
||||
|
||||
// basic authentication method
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" -u admin:admin http://192.168.4.1/middleware/auth-basic
|
||||
server.on("/middleware/auth-basic", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world!");
|
||||
})
|
||||
.addMiddleware(&basicAuth);
|
||||
|
||||
// basic authentication method with hash
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" -u admin:admin http://192.168.4.1/middleware/auth-basic-hash
|
||||
server.on("/middleware/auth-basic-hash", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world!");
|
||||
})
|
||||
.addMiddleware(&basicAuthHash);
|
||||
|
||||
// digest authentication
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" -u admin:admin --digest http://192.168.4.1/middleware/auth-digest
|
||||
server.on("/middleware/auth-digest", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world!");
|
||||
})
|
||||
.addMiddleware(&digestAuth);
|
||||
|
||||
// digest authentication with hash
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" -u admin:admin --digest http://192.168.4.1/middleware/auth-digest-hash
|
||||
server.on("/middleware/auth-digest-hash", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/plain", "Hello, world!");
|
||||
})
|
||||
.addMiddleware(&digestAuthHash);
|
||||
|
||||
// test digest auth with cors
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" --digest -u user:password http://192.168.4.1/middleware/auth-custom
|
||||
server.on("/middleware/auth-custom", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String buffer = "Hello ";
|
||||
buffer.concat(request->getAttribute("user"));
|
||||
buffer.concat(" with role: ");
|
||||
buffer.concat(request->getAttribute("role"));
|
||||
request->send(200, "text/plain", buffer);
|
||||
})
|
||||
.addMiddlewares({&complexAuth, &authz});
|
||||
|
||||
///////////////////////////////////////////////////////////////////////
|
||||
|
||||
// curl -v -X GET -H "origin: http://192.168.4.1" http://192.168.4.1/redirect
|
||||
// curl -v -X POST -H "origin: http://192.168.4.1" http://192.168.4.1/redirect
|
||||
server.on("/redirect", HTTP_GET | HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
request->redirect("/");
|
||||
});
|
||||
|
||||
// PERF TEST:
|
||||
// > brew install autocannon
|
||||
// > autocannon -c 10 -w 10 -d 20 http://192.168.4.1
|
||||
// > autocannon -c 16 -w 16 -d 20 http://192.168.4.1
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/html", htmlContent);
|
||||
});
|
||||
|
||||
// curl -v -X GET http://192.168.4.1/index.txt
|
||||
server.serveStatic("/index.txt", LittleFS, "/index.txt");
|
||||
|
||||
// curl -v -X GET http://192.168.4.1/index-private.txt
|
||||
server.serveStatic("/index-private.txt", LittleFS, "/index.txt").setAuthentication("admin", "admin");
|
||||
|
||||
// ServeStatic static is used to serve static output which never changes over time.
|
||||
// This special endpoints automatyically adds caching headers.
|
||||
// If a template processor is used, it must enure that the outputed content will always be the ame over time and never changes.
|
||||
// Otherwise, do not use serveStatic.
|
||||
// Example below: IP never changes.
|
||||
// curl -v -X GET http://192.168.4.1/index-static.html
|
||||
server.serveStatic("/index-static.html", LittleFS, "/index.html").setTemplateProcessor([](const String& var) -> String {
|
||||
if (var == "IP") {
|
||||
// for CI, commented out since H2 board doesn ot support WiFi
|
||||
// return WiFi.localIP().toString();
|
||||
// return WiFi.softAPIP().toString();
|
||||
return "127.0.0..1";
|
||||
}
|
||||
return emptyString;
|
||||
});
|
||||
|
||||
// to serve a template with dynamic content (output changes over time), use normal
|
||||
// Example below: content changes over tinme do not use serveStatic.
|
||||
// curl -v -X GET http://192.168.4.1/index-dynamic.html
|
||||
server.on("/index-dynamic.html", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(LittleFS, "/index.html", "text/html", false, [](const String& var) -> String {
|
||||
if (var == "IP")
|
||||
return String(random(0, 1000));
|
||||
return emptyString;
|
||||
});
|
||||
});
|
||||
|
||||
// Issue #14: assert failed: tcp_update_rcv_ann_wnd (needs help to test fix)
|
||||
// > curl -v http://192.168.4.1/issue-14
|
||||
pinMode(4, OUTPUT);
|
||||
server.on("/issue-14", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
digitalWrite(4, HIGH);
|
||||
request->send(LittleFS, "/index.txt", "text/pain");
|
||||
delay(500);
|
||||
digitalWrite(4, LOW);
|
||||
});
|
||||
|
||||
/*
|
||||
Chunked encoding test: sends 16k of characters.
|
||||
❯ curl -N -v -X GET -H "origin: http://192.168.4.1" http://192.168.4.1/chunk
|
||||
*/
|
||||
server.on("/chunk", HTTP_HEAD | HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
AsyncWebServerResponse* response = request->beginChunkedResponse("text/html", [](uint8_t* buffer, size_t maxLen, size_t index) -> size_t {
|
||||
if (index >= 16384)
|
||||
return 0;
|
||||
memset(buffer, characters[charactersIndex], maxLen);
|
||||
charactersIndex = (charactersIndex + 1) % sizeof(characters);
|
||||
return maxLen;
|
||||
});
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// curl -N -v -X GET http://192.168.4.1/chunked.html --output -
|
||||
// curl -N -v -X GET -H "if-none-match: 4272" http://192.168.4.1/chunked.html --output -
|
||||
server.on("/chunked.html", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String len = String(htmlContentLength);
|
||||
|
||||
if (request->header(asyncsrv::T_INM) == len) {
|
||||
request->send(304);
|
||||
return;
|
||||
}
|
||||
|
||||
AsyncWebServerResponse* response = request->beginChunkedResponse("text/html", [](uint8_t* buffer, size_t maxLen, size_t index) -> size_t {
|
||||
Serial.printf("%u / %u\n", index, htmlContentLength);
|
||||
|
||||
// finished ?
|
||||
if (htmlContentLength <= index) {
|
||||
Serial.println("finished");
|
||||
return 0;
|
||||
}
|
||||
|
||||
// serve a maximum of 1024 or maxLen bytes of the remaining content
|
||||
const int chunkSize = min((size_t)1024, min(maxLen, htmlContentLength - index));
|
||||
Serial.printf("sending: %u\n", chunkSize);
|
||||
|
||||
memcpy(buffer, htmlContent + index, chunkSize);
|
||||
|
||||
return chunkSize;
|
||||
});
|
||||
|
||||
response->addHeader(asyncsrv::T_Cache_Control, "public,max-age=60");
|
||||
response->addHeader(asyncsrv::T_ETag, len);
|
||||
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// time curl -N -v -G -d 'd=3000' -d 'l=10000' http://192.168.4.1/slow.html --output -
|
||||
server.on("/slow.html", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
uint32_t d = request->getParam("d")->value().toInt();
|
||||
uint32_t l = request->getParam("l")->value().toInt();
|
||||
Serial.printf("d = %" PRIu32 ", l = %" PRIu32 "\n", d, l);
|
||||
AsyncWebServerResponse* response = request->beginChunkedResponse("text/html", [d, l](uint8_t* buffer, size_t maxLen, size_t index) -> size_t {
|
||||
Serial.printf("%u\n", index);
|
||||
// finished ?
|
||||
if (index >= l)
|
||||
return 0;
|
||||
|
||||
// slow down the task by 2 seconds
|
||||
// to simulate some heavy processing, like SD card reading
|
||||
delay(d);
|
||||
|
||||
memset(buffer, characters[charactersIndex], 256);
|
||||
charactersIndex = (charactersIndex + 1) % sizeof(characters);
|
||||
return 256;
|
||||
});
|
||||
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
/*
|
||||
❯ curl -I -X HEAD http://192.168.4.1/download
|
||||
HTTP/1.1 200 OK
|
||||
Content-Length: 1024
|
||||
Content-Type: application/octet-stream
|
||||
Connection: close
|
||||
Accept-Ranges: bytes
|
||||
*/
|
||||
// Ref: https://github.com/mathieucarbou/ESPAsyncWebServer/pull/80
|
||||
server.on("/download", HTTP_HEAD | HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
if (request->method() == HTTP_HEAD) {
|
||||
AsyncWebServerResponse* response = request->beginResponse(200, "application/octet-stream");
|
||||
response->addHeader(asyncsrv::T_Accept_Ranges, "bytes");
|
||||
response->addHeader(asyncsrv::T_Content_Length, 10);
|
||||
response->setContentLength(1024); // overrides previous one
|
||||
response->addHeader(asyncsrv::T_Content_Type, "foo");
|
||||
response->setContentType("application/octet-stream"); // overrides previous one
|
||||
// ...
|
||||
request->send(response);
|
||||
} else {
|
||||
// ...
|
||||
}
|
||||
});
|
||||
|
||||
// Send a GET request to <IP>/get?message=<message>
|
||||
server.on("/get", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String message;
|
||||
if (request->hasParam(PARAM_MESSAGE)) {
|
||||
message = request->getParam(PARAM_MESSAGE)->value();
|
||||
} else {
|
||||
message = "No message sent";
|
||||
}
|
||||
request->send(200, "text/plain", "Hello, GET: " + message);
|
||||
});
|
||||
|
||||
// Send a POST request to <IP>/post with a form field message set to <message>
|
||||
server.on("/post", HTTP_POST, [](AsyncWebServerRequest* request) {
|
||||
String message;
|
||||
if (request->hasParam(PARAM_MESSAGE, true)) {
|
||||
message = request->getParam(PARAM_MESSAGE, true)->value();
|
||||
} else {
|
||||
message = "No message sent";
|
||||
}
|
||||
request->send(200, "text/plain", "Hello, POST: " + message);
|
||||
});
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
// JSON
|
||||
|
||||
// sends JSON
|
||||
// curl -v -X GET http://192.168.4.1/json1
|
||||
server.on("/json1", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
AsyncJsonResponse* response = new AsyncJsonResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["hello"] = "world";
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// curl -v -X GET http://192.168.4.1/json2
|
||||
server.on("/json2", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
AsyncResponseStream* response = request->beginResponseStream("application/json");
|
||||
JsonDocument doc;
|
||||
JsonObject root = doc.to<JsonObject>();
|
||||
root["foo"] = "bar";
|
||||
serializeJson(root, *response);
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// curl -v -X POST -H 'Content-Type: application/json' -d '{"name":"You"}' http://192.168.4.1/json2
|
||||
// curl -v -X PUT -H 'Content-Type: application/json' -d '{"name":"You"}' http://192.168.4.1/json2
|
||||
jsonHandler->setMethod(HTTP_POST | HTTP_PUT);
|
||||
jsonHandler->onRequest([](AsyncWebServerRequest* request, JsonVariant& json) {
|
||||
serializeJson(json, Serial);
|
||||
AsyncJsonResponse* response = new AsyncJsonResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["hello"] = json.as<JsonObject>()["name"];
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// MessagePack
|
||||
|
||||
// receives MessagePack and sends MessagePack
|
||||
msgPackHandler->onRequest([](AsyncWebServerRequest* request, JsonVariant& json) {
|
||||
// JsonObject jsonObj = json.as<JsonObject>();
|
||||
// ...
|
||||
|
||||
AsyncMessagePackResponse* response = new AsyncMessagePackResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["hello"] = "world";
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
// sends MessagePack
|
||||
server.on("/msgpack1", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
AsyncMessagePackResponse* response = new AsyncMessagePackResponse();
|
||||
JsonObject root = response->getRoot().to<JsonObject>();
|
||||
root["hello"] = "world";
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
#endif
|
||||
|
||||
events.onConnect([](AsyncEventSourceClient* client) {
|
||||
if (client->lastId()) {
|
||||
Serial.printf("SSE Client reconnected! Last message ID that it gat is: %" PRIu32 "\n", client->lastId());
|
||||
}
|
||||
client->send("hello!", NULL, millis(), 1000);
|
||||
});
|
||||
|
||||
server.on("/sse", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
request->send(200, "text/html", SSE_HTLM);
|
||||
});
|
||||
|
||||
ws.onEvent([](AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||
(void)len;
|
||||
if (type == WS_EVT_CONNECT) {
|
||||
wsClients++;
|
||||
ws.textAll("new client connected");
|
||||
Serial.println("ws connect");
|
||||
client->setCloseClientOnQueueFull(false);
|
||||
client->ping();
|
||||
} else if (type == WS_EVT_DISCONNECT) {
|
||||
wsClients--;
|
||||
ws.textAll("client disconnected");
|
||||
Serial.println("ws disconnect");
|
||||
} else if (type == WS_EVT_ERROR) {
|
||||
Serial.println("ws error");
|
||||
} else if (type == WS_EVT_PONG) {
|
||||
Serial.println("ws pong");
|
||||
} else if (type == WS_EVT_DATA) {
|
||||
AwsFrameInfo* info = (AwsFrameInfo*)arg;
|
||||
String msg = "";
|
||||
if (info->final && info->index == 0 && info->len == len) {
|
||||
if (info->opcode == WS_TEXT) {
|
||||
data[len] = 0;
|
||||
Serial.printf("ws text: %s\n", (char*)data);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// SSS endpoints
|
||||
// sends a message every 10 ms
|
||||
//
|
||||
// go to http://192.168.4.1/sse
|
||||
// > curl -v -N -H "Accept: text/event-stream" http://192.168.4.1/events
|
||||
//
|
||||
// some perf tests:
|
||||
// launch 16 concurrent workers for 30 seconds
|
||||
// > for i in {1..10}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done;
|
||||
// > for i in {1..16}; do ( count=$(gtimeout 30 curl -s -N -H "Accept: text/event-stream" http://192.168.4.1/events 2>&1 | grep -c "^data:"); echo "Total: $count events, $(echo "$count / 4" | bc -l) events / second" ) & done;
|
||||
//
|
||||
// With AsyncTCP, with 16 workers: a lot of "Event message queue overflow: discard message", no crash
|
||||
//
|
||||
// Total: 1711 events, 427.75 events / second
|
||||
// Total: 1711 events, 427.75 events / second
|
||||
// Total: 1626 events, 406.50 events / second
|
||||
// Total: 1562 events, 390.50 events / second
|
||||
// Total: 1706 events, 426.50 events / second
|
||||
// Total: 1659 events, 414.75 events / second
|
||||
// Total: 1624 events, 406.00 events / second
|
||||
// Total: 1706 events, 426.50 events / second
|
||||
// Total: 1487 events, 371.75 events / second
|
||||
// Total: 1573 events, 393.25 events / second
|
||||
// Total: 1569 events, 392.25 events / second
|
||||
// Total: 1559 events, 389.75 events / second
|
||||
// Total: 1560 events, 390.00 events / second
|
||||
// Total: 1562 events, 390.50 events / second
|
||||
// Total: 1626 events, 406.50 events / second
|
||||
//
|
||||
// With AsyncTCP, with 10 workers:
|
||||
//
|
||||
// Total: 2038 events, 509.50 events / second
|
||||
// Total: 2120 events, 530.00 events / second
|
||||
// Total: 2119 events, 529.75 events / second
|
||||
// Total: 2038 events, 509.50 events / second
|
||||
// Total: 2037 events, 509.25 events / second
|
||||
// Total: 2119 events, 529.75 events / second
|
||||
// Total: 2119 events, 529.75 events / second
|
||||
// Total: 2120 events, 530.00 events / second
|
||||
// Total: 2038 events, 509.50 events / second
|
||||
// Total: 2038 events, 509.50 events / second
|
||||
//
|
||||
// With AsyncTCPSock, with 16 workers: ESP32 CRASH !!!
|
||||
//
|
||||
// With AsyncTCPSock, with 10 workers:
|
||||
//
|
||||
// Total: 1242 events, 310.50 events / second
|
||||
// Total: 1242 events, 310.50 events / second
|
||||
// Total: 1242 events, 310.50 events / second
|
||||
// Total: 1242 events, 310.50 events / second
|
||||
// Total: 1181 events, 295.25 events / second
|
||||
// Total: 1182 events, 295.50 events / second
|
||||
// Total: 1240 events, 310.00 events / second
|
||||
// Total: 1181 events, 295.25 events / second
|
||||
// Total: 1181 events, 295.25 events / second
|
||||
// Total: 1183 events, 295.75 events / second
|
||||
//
|
||||
server.addHandler(&events);
|
||||
|
||||
// Run in terminal 1: websocat ws://192.168.4.1/ws => stream data
|
||||
// Run in terminal 2: websocat ws://192.168.4.1/ws => stream data
|
||||
// Run in terminal 3: websocat ws://192.168.4.1/ws => should fail:
|
||||
/*
|
||||
❯ websocat ws://192.168.4.1/ws
|
||||
websocat: WebSocketError: WebSocketError: Received unexpected status code (503 Service Unavailable)
|
||||
websocat: error running
|
||||
*/
|
||||
server.addHandler(&ws).addMiddleware([](AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
if (ws.count() > 2) {
|
||||
// too many clients - answer back immediately and stop processing next middlewares and handler
|
||||
request->send(503, "text/plain", "Server is busy");
|
||||
} else {
|
||||
// process next middleware and at the end the handler
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
// Reset connection on HTTP request:
|
||||
// for i in {1..20}; do curl -v -X GET https://192.168.4.1:80; done;
|
||||
// The heap size should not decrease over time.
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
server.addHandler(jsonHandler);
|
||||
server.addHandler(msgPackHandler);
|
||||
#endif
|
||||
|
||||
server.onNotFound(notFound);
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
uint32_t lastSSE = 0;
|
||||
uint32_t deltaSSE = 10;
|
||||
|
||||
uint32_t lastWS = 0;
|
||||
uint32_t deltaWS = 100;
|
||||
|
||||
uint32_t lastHeap = 0;
|
||||
|
||||
void loop() {
|
||||
uint32_t now = millis();
|
||||
if (now - lastSSE >= deltaSSE) {
|
||||
events.send(String("ping-") + now, "heartbeat", now);
|
||||
lastSSE = millis();
|
||||
}
|
||||
if (now - lastWS >= deltaWS) {
|
||||
ws.printfAll("kp%.4f", (10.0 / 3.0));
|
||||
// for (auto& client : ws.getClients()) {
|
||||
// client.printf("kp%.4f", (10.0 / 3.0));
|
||||
// }
|
||||
lastWS = millis();
|
||||
}
|
||||
#ifdef ESP32
|
||||
if (now - lastHeap >= 2000) {
|
||||
Serial.printf("Free heap: %" PRIu32 "\n", ESP.getFreeHeap());
|
||||
lastHeap = now;
|
||||
}
|
||||
#endif
|
||||
}
|
37
examples/StreamFiles/StreamConcat.h
Normal file
37
examples/StreamFiles/StreamConcat.h
Normal file
@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <Stream.h>
|
||||
|
||||
class StreamConcat : public Stream {
|
||||
public:
|
||||
StreamConcat(Stream* s1, Stream* s2) : _s1(s1), _s2(s2) {}
|
||||
|
||||
size_t write(__unused const uint8_t* p, __unused size_t n) override { return 0; }
|
||||
size_t write(__unused uint8_t c) override { return 0; }
|
||||
void flush() override {}
|
||||
|
||||
int available() override { return _s1->available() + _s2->available(); }
|
||||
|
||||
int read() override {
|
||||
int c = _s1->read();
|
||||
return c != -1 ? c : _s2->read();
|
||||
}
|
||||
|
||||
#if defined(TARGET_RP2040)
|
||||
size_t readBytes(char* buffer, size_t length) {
|
||||
#else
|
||||
size_t readBytes(char* buffer, size_t length) override {
|
||||
#endif
|
||||
size_t count = _s1->readBytes(buffer, length);
|
||||
return count > 0 ? count : _s2->readBytes(buffer, length);
|
||||
}
|
||||
|
||||
int peek() override {
|
||||
int c = _s1->peek();
|
||||
return c != -1 ? c : _s2->peek();
|
||||
}
|
||||
|
||||
private:
|
||||
Stream* _s1;
|
||||
Stream* _s2;
|
||||
};
|
89
examples/StreamFiles/StreamFiles.ino
Normal file
89
examples/StreamFiles/StreamFiles.ino
Normal file
@ -0,0 +1,89 @@
|
||||
#include <Arduino.h>
|
||||
#include <DNSServer.h>
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#include <WiFi.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <WebServer.h>
|
||||
#include <WiFi.h>
|
||||
#endif
|
||||
|
||||
#include <StreamString.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <LittleFS.h>
|
||||
|
||||
#include "StreamConcat.h"
|
||||
|
||||
DNSServer dnsServer;
|
||||
AsyncWebServer server(80);
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
LittleFS.begin();
|
||||
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
WiFi.mode(WIFI_AP);
|
||||
WiFi.softAP("esp-captive");
|
||||
|
||||
dnsServer.start(53, "*", WiFi.softAPIP());
|
||||
#endif
|
||||
|
||||
File file1 = LittleFS.open("/header.html", "w");
|
||||
file1.print("<html><head><title>ESP Captive Portal</title><meta http-equiv=\"refresh\" content=\"1\"></head><body>");
|
||||
file1.close();
|
||||
|
||||
File file2 = LittleFS.open("/body.html", "w");
|
||||
file2.print("<h1>Welcome to ESP Captive Portal</h1>");
|
||||
file2.close();
|
||||
|
||||
File file3 = LittleFS.open("/footer.html", "w");
|
||||
file3.print("</body></html>");
|
||||
file3.close();
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
File header = LittleFS.open("/header.html", "r");
|
||||
File body = LittleFS.open("/body.html", "r");
|
||||
StreamConcat stream1(&header, &body);
|
||||
|
||||
StreamString content;
|
||||
#if defined(TARGET_RP2040)
|
||||
content.printf("FreeHeap: %d", rp2040.getFreeHeap());
|
||||
#else
|
||||
content.printf("FreeHeap: %" PRIu32, ESP.getFreeHeap());
|
||||
#endif
|
||||
StreamConcat stream2 = StreamConcat(&stream1, &content);
|
||||
|
||||
File footer = LittleFS.open("/footer.html", "r");
|
||||
StreamConcat stream3 = StreamConcat(&stream2, &footer);
|
||||
|
||||
request->send(stream3, "text/html", stream3.available());
|
||||
header.close();
|
||||
body.close();
|
||||
footer.close();
|
||||
});
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest* request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
});
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
uint32_t last = 0;
|
||||
|
||||
void loop() {
|
||||
// dnsServer.processNextRequest();
|
||||
|
||||
if (millis() - last > 2000) {
|
||||
#if defined(TARGET_RP2040)
|
||||
Serial.printf("FreeHeap: %d", rp2040.getFreeHeap());
|
||||
#else
|
||||
Serial.printf("FreeHeap: %" PRIu32, ESP.getFreeHeap());
|
||||
#endif
|
||||
last = millis();
|
||||
}
|
||||
}
|
@ -1 +0,0 @@
|
||||
-DASYNCWEBSERVER_REGEX=1
|
@ -1 +0,0 @@
|
||||
-DASYNCWEBSERVER_REGEX=1
|
@ -1,77 +0,0 @@
|
||||
//
|
||||
// A simple server implementation with regex routes:
|
||||
// * serve static messages
|
||||
// * read GET and POST parameters
|
||||
// * handle missing pages / 404s
|
||||
//
|
||||
|
||||
// Add buildflag ASYNCWEBSERVER_REGEX to enable the regex support
|
||||
|
||||
// For platformio: platformio.ini:
|
||||
// build_flags =
|
||||
// -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
|
||||
// Linux: ~/.arduino15/packages/espxxxx/hardware/espxxxx/{version}/platform.local.txt
|
||||
//
|
||||
// compiler.cpp.extra_flags=-DASYNCWEBSERVER_REGEX=1
|
||||
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP32
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
AsyncWebServer server(80);
|
||||
|
||||
const char* ssid = "YOUR_SSID";
|
||||
const char* password = "YOUR_PASSWORD";
|
||||
|
||||
const char* PARAM_MESSAGE = "message";
|
||||
|
||||
void notFound(AsyncWebServerRequest *request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||
Serial.printf("WiFi Failed!\n");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", "Hello, world");
|
||||
});
|
||||
|
||||
// Send a GET request to <IP>/sensor/<number>
|
||||
server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
|
||||
String sensorNumber = request->pathArg(0);
|
||||
request->send(200, "text/plain", "Hello, sensor: " + sensorNumber);
|
||||
});
|
||||
|
||||
// Send a GET request to <IP>/sensor/<number>/action/<action>
|
||||
server.on("^\\/sensor\\/([0-9]+)\\/action\\/([a-zA-Z0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
|
||||
String sensorNumber = request->pathArg(0);
|
||||
String action = request->pathArg(1);
|
||||
request->send(200, "text/plain", "Hello, sensor: " + sensorNumber + ", with action: " + action);
|
||||
});
|
||||
|
||||
server.onNotFound(notFound);
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
@ -1,74 +0,0 @@
|
||||
//
|
||||
// A simple server implementation showing how to:
|
||||
// * serve static messages
|
||||
// * read GET and POST parameters
|
||||
// * handle missing pages / 404s
|
||||
//
|
||||
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP32
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#elif defined(ESP8266)
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ESPAsyncTCP.h>
|
||||
#endif
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
AsyncWebServer server(80);
|
||||
|
||||
const char* ssid = "YOUR_SSID";
|
||||
const char* password = "YOUR_PASSWORD";
|
||||
|
||||
const char* PARAM_MESSAGE = "message";
|
||||
|
||||
void notFound(AsyncWebServerRequest *request) {
|
||||
request->send(404, "text/plain", "Not found");
|
||||
}
|
||||
|
||||
void setup() {
|
||||
|
||||
Serial.begin(115200);
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(ssid, password);
|
||||
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
|
||||
Serial.printf("WiFi Failed!\n");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
|
||||
request->send(200, "text/plain", "Hello, world");
|
||||
});
|
||||
|
||||
// Send a GET request to <IP>/get?message=<message>
|
||||
server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
|
||||
String message;
|
||||
if (request->hasParam(PARAM_MESSAGE)) {
|
||||
message = request->getParam(PARAM_MESSAGE)->value();
|
||||
} else {
|
||||
message = "No message sent";
|
||||
}
|
||||
request->send(200, "text/plain", "Hello, GET: " + message);
|
||||
});
|
||||
|
||||
// Send a POST request to <IP>/post with a form field message set to <message>
|
||||
server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request){
|
||||
String message;
|
||||
if (request->hasParam(PARAM_MESSAGE, true)) {
|
||||
message = request->getParam(PARAM_MESSAGE, true)->value();
|
||||
} else {
|
||||
message = "No message sent";
|
||||
}
|
||||
request->send(200, "text/plain", "Hello, POST: " + message);
|
||||
});
|
||||
|
||||
server.onNotFound(notFound);
|
||||
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
@ -1,3 +0,0 @@
|
||||
JsonArray KEYWORD1
|
||||
add KEYWORD2
|
||||
createArray KEYWORD3
|
60
library.json
60
library.json
@ -1,37 +1,57 @@
|
||||
{
|
||||
"name":"ESP Async WebServer",
|
||||
"description":"Asynchronous HTTP and WebSocket Server Library for ESP8266 and ESP32",
|
||||
"keywords":"http,async,websocket,webserver",
|
||||
"name": "ESPAsyncWebServer",
|
||||
"version": "3.6.0",
|
||||
"description": "Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040. Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc.",
|
||||
"keywords": "http,async,websocket,webserver",
|
||||
"homepage": "https://github.com/ESP32Async/ESPAsyncWebServer",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/ESP32Async/ESPAsyncWebServer.git"
|
||||
},
|
||||
"authors":
|
||||
{
|
||||
"name": "Hristo Gochkov",
|
||||
"name": "ESP32Async",
|
||||
"maintainer": true
|
||||
},
|
||||
"repository":
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://github.com/me-no-dev/ESPAsyncWebServer.git"
|
||||
},
|
||||
"version": "1.2.4",
|
||||
"license": "LGPL-3.0",
|
||||
"frameworks": "arduino",
|
||||
"platforms": ["espressif8266", "espressif32"],
|
||||
"platforms": [
|
||||
"espressif32",
|
||||
"espressif8266",
|
||||
"raspberrypi"
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"owner": "me-no-dev",
|
||||
"name": "ESPAsyncTCP",
|
||||
"version": "^1.2.2",
|
||||
"platforms": "espressif8266"
|
||||
"owner": "ESP32Async",
|
||||
"name": "AsyncTCP",
|
||||
"version": "^3.3.2",
|
||||
"platforms": "espressif32"
|
||||
},
|
||||
{
|
||||
"owner": "me-no-dev",
|
||||
"name": "AsyncTCP",
|
||||
"version": "^1.1.1",
|
||||
"platforms": "espressif32"
|
||||
"owner": "ESP32Async",
|
||||
"name": "ESPAsyncTCP",
|
||||
"version": "^2.0.0",
|
||||
"platforms": "espressif8266"
|
||||
},
|
||||
{
|
||||
"name": "Hash",
|
||||
"platforms": "espressif8266"
|
||||
},
|
||||
{
|
||||
"owner": "khoih-prog",
|
||||
"name": "AsyncTCP_RP2040W",
|
||||
"version": "^1.2.0",
|
||||
"platforms": "raspberrypi"
|
||||
}
|
||||
]
|
||||
],
|
||||
"export": {
|
||||
"include": [
|
||||
"examples",
|
||||
"src",
|
||||
"library.json",
|
||||
"library.properties",
|
||||
"LICENSE",
|
||||
"README.md"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
@ -1,9 +1,11 @@
|
||||
name=ESP Async WebServer
|
||||
version=1.2.4
|
||||
author=Me-No-Dev
|
||||
maintainer=Me-No-Dev
|
||||
sentence=Async Web Server for ESP8266 and ESP31B
|
||||
paragraph=Async Web Server for ESP8266 and ESP31B
|
||||
includes=ESPAsyncWebServer.h
|
||||
version=3.6.0
|
||||
author=ESP32Async
|
||||
maintainer=ESP32Async
|
||||
sentence=Asynchronous HTTP and WebSocket Server Library for ESP32, ESP8266 and RP2040
|
||||
paragraph=Supports: WebSocket, SSE, Authentication, Arduino Json 7, File Upload, Static File serving, URL Rewrite, URL Redirect, etc
|
||||
category=Other
|
||||
url=https://github.com/me-no-dev/ESPAsyncWebServer
|
||||
url=https://github.com/ESP32Async/ESPAsyncWebServer
|
||||
architectures=*
|
||||
license=LGPL-3.0
|
7
partitions-4MB.csv
Normal file
7
partitions-4MB.csv
Normal file
@ -0,0 +1,7 @@
|
||||
# Name ,Type ,SubType ,Offset ,Size ,Flags
|
||||
nvs ,data ,nvs ,36K ,20K ,
|
||||
otadata ,data ,ota ,56K ,8K ,
|
||||
app0 ,app ,ota_0 ,64K ,1856K ,
|
||||
app1 ,app ,ota_1 ,1920K ,1856K ,
|
||||
spiffs ,data ,spiffs ,3776K ,256K ,
|
||||
coredump ,data ,coredump ,4032K ,64K ,
|
|
129
platformio.ini
Normal file
129
platformio.ini
Normal file
@ -0,0 +1,129 @@
|
||||
[platformio]
|
||||
default_envs = arduino-2, arduino-3, arduino-311, esp8266, raspberrypi
|
||||
lib_dir = .
|
||||
; src_dir = examples/CaptivePortal
|
||||
src_dir = examples/SimpleServer
|
||||
; src_dir = examples/StreamFiles
|
||||
; src_dir = examples/Filters
|
||||
; src_dir = examples/Issue85
|
||||
; src_dir = examples/Issue162
|
||||
|
||||
[env]
|
||||
framework = arduino
|
||||
build_flags =
|
||||
-Og
|
||||
-Wall -Wextra
|
||||
-Wno-unused-parameter
|
||||
; -D CONFIG_ARDUHAL_LOG_COLORS
|
||||
-D CORE_DEBUG_LEVEL=ARDUHAL_LOG_LEVEL_VERBOSE
|
||||
-D CONFIG_ASYNC_TCP_MAX_ACK_TIME=5000
|
||||
-D CONFIG_ASYNC_TCP_PRIORITY=10
|
||||
-D CONFIG_ASYNC_TCP_QUEUE_SIZE=64
|
||||
-D CONFIG_ASYNC_TCP_RUNNING_CORE=1
|
||||
-D CONFIG_ASYNC_TCP_STACK_SIZE=4096
|
||||
upload_protocol = esptool
|
||||
monitor_speed = 115200
|
||||
monitor_filters = esp32_exception_decoder, log2file
|
||||
; monitor_filters = esp8266_exception_decoder, log2file
|
||||
lib_compat_mode = strict
|
||||
lib_ldf_mode = chain
|
||||
lib_deps =
|
||||
; bblanchon/ArduinoJson @ 5.13.4
|
||||
; bblanchon/ArduinoJson @ 6.21.5
|
||||
bblanchon/ArduinoJson @ 7.3.0
|
||||
ESP32Async/AsyncTCP @ 3.3.2
|
||||
board = esp32dev
|
||||
board_build.partitions = partitions-4MB.csv
|
||||
board_build.filesystem = littlefs
|
||||
|
||||
[env:arduino-2]
|
||||
platform = espressif32@6.9.0
|
||||
|
||||
[env:arduino-3]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.05/platform-espressif32.zip
|
||||
; board = esp32-s3-devkitc-1
|
||||
; board = esp32-c6-devkitc-1
|
||||
|
||||
[env:arduino-3-no-json]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.05/platform-espressif32.zip
|
||||
; board = esp32-s3-devkitc-1
|
||||
; board = esp32-c6-devkitc-1
|
||||
lib_deps =
|
||||
ESP32Async/AsyncTCP @ 3.3.2
|
||||
|
||||
[env:arduino-311]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.11/platform-espressif32.zip
|
||||
; board = esp32-s3-devkitc-1
|
||||
; board = esp32-c6-devkitc-1
|
||||
; board = esp32-h2-devkitm-1
|
||||
|
||||
[env:perf-test-AsyncTCP]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.11/platform-espressif32.zip
|
||||
build_flags = ${env.build_flags}
|
||||
-D PERF_TEST=1
|
||||
|
||||
[env:perf-test-AsyncTCPSock]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.11/platform-espressif32.zip
|
||||
lib_deps =
|
||||
https://github.com/ESP32Async/AsyncTCPSock/archive/refs/tags/v1.0.3-dev.zip
|
||||
build_flags = ${env.build_flags}
|
||||
-D PERF_TEST=1
|
||||
|
||||
[env:esp8266]
|
||||
platform = espressif8266
|
||||
; board = huzzah
|
||||
board = d1_mini
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson @ 7.3.0
|
||||
ESP32Async/ESPAsyncTCP @ 2.0.0
|
||||
|
||||
[env:raspberrypi]
|
||||
platform = https://github.com/maxgerhardt/platform-raspberrypi.git
|
||||
board = rpipicow
|
||||
board_build.core = earlephilhower
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson @ 7.3.0
|
||||
khoih-prog/AsyncTCP_RP2040W @ 1.2.0
|
||||
lib_ignore =
|
||||
lwIP_ESPHost
|
||||
build_flags = ${env.build_flags}
|
||||
-Wno-missing-field-initializers
|
||||
|
||||
; CI
|
||||
|
||||
[env:ci-arduino-2]
|
||||
platform = espressif32@6.9.0
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
|
||||
[env:ci-arduino-3]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.05/platform-espressif32.zip
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
|
||||
[env:ci-arduino-3-no-json]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.05/platform-espressif32.zip
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
lib_deps =
|
||||
ESP32Async/AsyncTCP @ 3.3.2
|
||||
|
||||
[env:ci-arduino-311]
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/53.03.11/platform-espressif32.zip
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
|
||||
[env:ci-esp8266]
|
||||
platform = espressif8266
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson @ 7.3.0
|
||||
ESP32Async/ESPAsyncTCP @ 2.0.0
|
||||
|
||||
[env:ci-raspberrypi]
|
||||
platform = https://github.com/maxgerhardt/platform-raspberrypi.git
|
||||
board = ${sysenv.PIO_BOARD}
|
||||
board_build.core = earlephilhower
|
||||
lib_deps =
|
||||
bblanchon/ArduinoJson @ 7.3.0
|
||||
khoih-prog/AsyncTCP_RP2040W @ 1.2.0
|
||||
lib_ignore =
|
||||
lwIP_ESPHost
|
||||
build_flags = ${env.build_flags}
|
||||
-Wno-missing-field-initializers
|
@ -18,356 +18,450 @@
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
#include "Arduino.h"
|
||||
#if defined(ESP32)
|
||||
#include <rom/ets_sys.h>
|
||||
#endif
|
||||
#include "AsyncEventSource.h"
|
||||
#ifdef ESP32
|
||||
#if ESP_IDF_VERSION_MAJOR >= 5
|
||||
#include "rom/ets_sys.h"
|
||||
#endif
|
||||
#endif
|
||||
|
||||
static String generateEventMessage(const char *message, const char *event, uint32_t id, uint32_t reconnect){
|
||||
String ev = "";
|
||||
#define ASYNC_SSE_NEW_LINE_CHAR (char)0xa
|
||||
|
||||
if(reconnect){
|
||||
ev += "retry: ";
|
||||
ev += String(reconnect);
|
||||
ev += "\r\n";
|
||||
using namespace asyncsrv;
|
||||
|
||||
static String generateEventMessage(const char* message, const char* event, uint32_t id, uint32_t reconnect) {
|
||||
String str;
|
||||
size_t len{0};
|
||||
if (message)
|
||||
len += strlen(message);
|
||||
|
||||
if (event)
|
||||
len += strlen(event);
|
||||
|
||||
len += 42; // give it some overhead
|
||||
|
||||
str.reserve(len);
|
||||
|
||||
if (reconnect) {
|
||||
str += T_retry_;
|
||||
str += reconnect;
|
||||
str += ASYNC_SSE_NEW_LINE_CHAR; // '\n'
|
||||
}
|
||||
|
||||
if(id){
|
||||
ev += "id: ";
|
||||
ev += String(id);
|
||||
ev += "\r\n";
|
||||
if (id) {
|
||||
str += T_id__;
|
||||
str += id;
|
||||
str += ASYNC_SSE_NEW_LINE_CHAR; // '\n'
|
||||
}
|
||||
|
||||
if(event != NULL){
|
||||
ev += "event: ";
|
||||
ev += String(event);
|
||||
ev += "\r\n";
|
||||
if (event != NULL) {
|
||||
str += T_event_;
|
||||
str += event;
|
||||
str += ASYNC_SSE_NEW_LINE_CHAR; // '\n'
|
||||
}
|
||||
|
||||
if(message != NULL){
|
||||
size_t messageLen = strlen(message);
|
||||
char * lineStart = (char *)message;
|
||||
char * lineEnd;
|
||||
do {
|
||||
char * nextN = strchr(lineStart, '\n');
|
||||
char * nextR = strchr(lineStart, '\r');
|
||||
if(nextN == NULL && nextR == NULL){
|
||||
size_t llen = ((char *)message + messageLen) - lineStart;
|
||||
char * ldata = (char *)malloc(llen+1);
|
||||
if(ldata != NULL){
|
||||
memcpy(ldata, lineStart, llen);
|
||||
ldata[llen] = 0;
|
||||
ev += "data: ";
|
||||
ev += ldata;
|
||||
ev += "\r\n\r\n";
|
||||
free(ldata);
|
||||
}
|
||||
lineStart = (char *)message + messageLen;
|
||||
if (!message)
|
||||
return str;
|
||||
|
||||
size_t messageLen = strlen(message);
|
||||
char* lineStart = (char*)message;
|
||||
char* lineEnd;
|
||||
do {
|
||||
char* nextN = strchr(lineStart, '\n');
|
||||
char* nextR = strchr(lineStart, '\r');
|
||||
if (nextN == NULL && nextR == NULL) {
|
||||
// a message is a single-line string
|
||||
str += T_data_;
|
||||
str += message;
|
||||
str += T_nn;
|
||||
return str;
|
||||
}
|
||||
|
||||
// a message is a multi-line string
|
||||
char* nextLine = NULL;
|
||||
if (nextN != NULL && nextR != NULL) { // windows line-ending \r\n
|
||||
if (nextR + 1 == nextN) {
|
||||
// normal \r\n sequense
|
||||
lineEnd = nextR;
|
||||
nextLine = nextN + 1;
|
||||
} else {
|
||||
char * nextLine = NULL;
|
||||
if(nextN != NULL && nextR != NULL){
|
||||
if(nextR < nextN){
|
||||
lineEnd = nextR;
|
||||
if(nextN == (nextR + 1))
|
||||
nextLine = nextN + 1;
|
||||
else
|
||||
nextLine = nextR + 1;
|
||||
} else {
|
||||
lineEnd = nextN;
|
||||
if(nextR == (nextN + 1))
|
||||
nextLine = nextR + 1;
|
||||
else
|
||||
nextLine = nextN + 1;
|
||||
}
|
||||
} else if(nextN != NULL){
|
||||
lineEnd = nextN;
|
||||
nextLine = nextN + 1;
|
||||
} else {
|
||||
lineEnd = nextR;
|
||||
nextLine = nextR + 1;
|
||||
}
|
||||
|
||||
size_t llen = lineEnd - lineStart;
|
||||
char * ldata = (char *)malloc(llen+1);
|
||||
if(ldata != NULL){
|
||||
memcpy(ldata, lineStart, llen);
|
||||
ldata[llen] = 0;
|
||||
ev += "data: ";
|
||||
ev += ldata;
|
||||
ev += "\r\n";
|
||||
free(ldata);
|
||||
}
|
||||
lineStart = nextLine;
|
||||
if(lineStart == ((char *)message + messageLen))
|
||||
ev += "\r\n";
|
||||
// some abnormal \n \r mixed sequence
|
||||
lineEnd = std::min(nextR, nextN);
|
||||
nextLine = lineEnd + 1;
|
||||
}
|
||||
} while(lineStart < ((char *)message + messageLen));
|
||||
}
|
||||
} else if (nextN != NULL) { // Unix/Mac OS X LF
|
||||
lineEnd = nextN;
|
||||
nextLine = nextN + 1;
|
||||
} else { // some ancient garbage
|
||||
lineEnd = nextR;
|
||||
nextLine = nextR + 1;
|
||||
}
|
||||
|
||||
return ev;
|
||||
str += T_data_;
|
||||
str.concat(lineStart, lineEnd - lineStart);
|
||||
str += ASYNC_SSE_NEW_LINE_CHAR; // \n
|
||||
|
||||
lineStart = nextLine;
|
||||
} while (lineStart < ((char*)message + messageLen));
|
||||
|
||||
// append another \n to terminate message
|
||||
str += ASYNC_SSE_NEW_LINE_CHAR; // '\n'
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
// Message
|
||||
|
||||
AsyncEventSourceMessage::AsyncEventSourceMessage(const char * data, size_t len)
|
||||
: _data(nullptr), _len(len), _sent(0), _acked(0)
|
||||
{
|
||||
_data = (uint8_t*)malloc(_len+1);
|
||||
if(_data == nullptr){
|
||||
_len = 0;
|
||||
} else {
|
||||
memcpy(_data, data, len);
|
||||
_data[_len] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
AsyncEventSourceMessage::~AsyncEventSourceMessage() {
|
||||
if(_data != NULL)
|
||||
free(_data);
|
||||
}
|
||||
|
||||
size_t AsyncEventSourceMessage::ack(size_t len, uint32_t time) {
|
||||
(void)time;
|
||||
size_t AsyncEventSourceMessage::ack(size_t len, __attribute__((unused)) uint32_t time) {
|
||||
// If the whole message is now acked...
|
||||
if(_acked + len > _len){
|
||||
// Return the number of extra bytes acked (they will be carried on to the next message)
|
||||
const size_t extra = _acked + len - _len;
|
||||
_acked = _len;
|
||||
return extra;
|
||||
if (_acked + len > _data->length()) {
|
||||
// Return the number of extra bytes acked (they will be carried on to the next message)
|
||||
const size_t extra = _acked + len - _data->length();
|
||||
_acked = _data->length();
|
||||
return extra;
|
||||
}
|
||||
// Return that no extra bytes left.
|
||||
_acked += len;
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t AsyncEventSourceMessage::send(AsyncClient *client) {
|
||||
const size_t len = _len - _sent;
|
||||
if(client->space() < len){
|
||||
size_t AsyncEventSourceMessage::write(AsyncClient* client) {
|
||||
if (!client)
|
||||
return 0;
|
||||
|
||||
if (_sent >= _data->length() || !client->canSend()) {
|
||||
return 0;
|
||||
}
|
||||
size_t sent = client->add((const char *)_data, len);
|
||||
if(client->canSend())
|
||||
client->send();
|
||||
_sent += sent;
|
||||
return sent;
|
||||
|
||||
size_t len = std::min(_data->length() - _sent, client->space());
|
||||
/*
|
||||
add() would call lwip's tcp_write() under the AsyncTCP hood with apiflags argument.
|
||||
By default apiflags=ASYNC_WRITE_FLAG_COPY
|
||||
we could have used apiflags with this flag unset to pass data by reference and avoid copy to socket buffer,
|
||||
but looks like it does not work for Arduino's lwip in ESP32/IDF
|
||||
it is enforced in https://github.com/espressif/esp-lwip/blob/0606eed9d8b98a797514fdf6eabb4daf1c8c8cd9/src/core/tcp_out.c#L422C5-L422C30
|
||||
if LWIP_NETIF_TX_SINGLE_PBUF is set, and it is set indeed in IDF
|
||||
https://github.com/espressif/esp-idf/blob/a0f798cfc4bbd624aab52b2c194d219e242d80c1/components/lwip/port/include/lwipopts.h#L744
|
||||
|
||||
So let's just keep it enforced ASYNC_WRITE_FLAG_COPY and keep in mind that there is no zero-copy
|
||||
*/
|
||||
size_t written = client->add(_data->c_str() + _sent, len, ASYNC_WRITE_FLAG_COPY); // ASYNC_WRITE_FLAG_MORE
|
||||
_sent += written;
|
||||
return written;
|
||||
}
|
||||
|
||||
size_t AsyncEventSourceMessage::send(AsyncClient* client) {
|
||||
size_t sent = write(client);
|
||||
return sent && client->send() ? sent : 0;
|
||||
}
|
||||
|
||||
// Client
|
||||
|
||||
AsyncEventSourceClient::AsyncEventSourceClient(AsyncWebServerRequest *request, AsyncEventSource *server)
|
||||
: _messageQueue(LinkedList<AsyncEventSourceMessage *>([](AsyncEventSourceMessage *m){ delete m; }))
|
||||
{
|
||||
_client = request->client();
|
||||
_server = server;
|
||||
_lastId = 0;
|
||||
if(request->hasHeader("Last-Event-ID"))
|
||||
_lastId = atoi(request->getHeader("Last-Event-ID")->value().c_str());
|
||||
|
||||
AsyncEventSourceClient::AsyncEventSourceClient(AsyncWebServerRequest* request, AsyncEventSource* server)
|
||||
: _client(request->client()), _server(server) {
|
||||
|
||||
if (request->hasHeader(T_Last_Event_ID))
|
||||
_lastId = atoi(request->getHeader(T_Last_Event_ID)->value().c_str());
|
||||
|
||||
_client->setRxTimeout(0);
|
||||
_client->onError(NULL, NULL);
|
||||
_client->onAck([](void *r, AsyncClient* c, size_t len, uint32_t time){ (void)c; ((AsyncEventSourceClient*)(r))->_onAck(len, time); }, this);
|
||||
_client->onPoll([](void *r, AsyncClient* c){ (void)c; ((AsyncEventSourceClient*)(r))->_onPoll(); }, this);
|
||||
_client->onAck([](void* r, AsyncClient* c, size_t len, uint32_t time) { (void)c; static_cast<AsyncEventSourceClient*>(r)->_onAck(len, time); }, this);
|
||||
_client->onPoll([](void* r, AsyncClient* c) { (void)c; static_cast<AsyncEventSourceClient*>(r)->_onPoll(); }, this);
|
||||
_client->onData(NULL, NULL);
|
||||
_client->onTimeout([this](void *r, AsyncClient* c __attribute__((unused)), uint32_t time){ ((AsyncEventSourceClient*)(r))->_onTimeout(time); }, this);
|
||||
_client->onDisconnect([this](void *r, AsyncClient* c){ ((AsyncEventSourceClient*)(r))->_onDisconnect(); delete c; }, this);
|
||||
_client->onTimeout([this](void* r, AsyncClient* c __attribute__((unused)), uint32_t time) { static_cast<AsyncEventSourceClient*>(r)->_onTimeout(time); }, this);
|
||||
_client->onDisconnect([this](void* r, AsyncClient* c) { static_cast<AsyncEventSourceClient*>(r)->_onDisconnect(); delete c; }, this);
|
||||
|
||||
_server->_addClient(this);
|
||||
delete request;
|
||||
|
||||
_client->setNoDelay(true);
|
||||
}
|
||||
|
||||
AsyncEventSourceClient::~AsyncEventSourceClient(){
|
||||
_messageQueue.free();
|
||||
AsyncEventSourceClient::~AsyncEventSourceClient() {
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_lockmq);
|
||||
#endif
|
||||
_messageQueue.clear();
|
||||
close();
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::_queueMessage(AsyncEventSourceMessage *dataMessage){
|
||||
if(dataMessage == NULL)
|
||||
return;
|
||||
if(!connected()){
|
||||
delete dataMessage;
|
||||
return;
|
||||
bool AsyncEventSourceClient::_queueMessage(const char* message, size_t len) {
|
||||
if (_messageQueue.size() >= SSE_MAX_QUEUED_MESSAGES) {
|
||||
#ifdef ESP8266
|
||||
ets_printf(String(F("ERROR: Too many messages queued\n")).c_str());
|
||||
#elif defined(ESP32)
|
||||
log_e("Event message queue overflow: discard message");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
if(_messageQueue.length() >= SSE_MAX_QUEUED_MESSAGES){
|
||||
ets_printf("ERROR: Too many messages queued\n");
|
||||
delete dataMessage;
|
||||
} else {
|
||||
_messageQueue.add(dataMessage);
|
||||
|
||||
#ifdef ESP32
|
||||
// length() is not thread-safe, thus acquiring the lock before this call..
|
||||
std::lock_guard<std::mutex> lock(_lockmq);
|
||||
#endif
|
||||
|
||||
_messageQueue.emplace_back(message, len);
|
||||
|
||||
/*
|
||||
throttle queue run
|
||||
if Q is filled for >25% then network/CPU is congested, since there is no zero-copy mode for socket buff
|
||||
forcing Q run will only eat more heap ram and blow the buffer, let's just keep data in our own queue
|
||||
the queue will be processed at least on each onAck()/onPoll() call from AsyncTCP
|
||||
*/
|
||||
if (_messageQueue.size() < SSE_MAX_QUEUED_MESSAGES >> 2 && _client->canSend()) {
|
||||
_runQueue();
|
||||
}
|
||||
if(_client->canSend())
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool AsyncEventSourceClient::_queueMessage(AsyncEvent_SharedData_t&& msg) {
|
||||
if (_messageQueue.size() >= SSE_MAX_QUEUED_MESSAGES) {
|
||||
#ifdef ESP8266
|
||||
ets_printf(String(F("ERROR: Too many messages queued\n")).c_str());
|
||||
#elif defined(ESP32)
|
||||
log_e("Event message queue overflow: discard message");
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef ESP32
|
||||
// length() is not thread-safe, thus acquiring the lock before this call..
|
||||
std::lock_guard<std::mutex> lock(_lockmq);
|
||||
#endif
|
||||
|
||||
_messageQueue.emplace_back(std::move(msg));
|
||||
|
||||
/*
|
||||
throttle queue run
|
||||
if Q is filled for >25% then network/CPU is congested, since there is no zero-copy mode for socket buff
|
||||
forcing Q run will only eat more heap ram and blow the buffer, let's just keep data in our own queue
|
||||
the queue will be processed at least on each onAck()/onPoll() call from AsyncTCP
|
||||
*/
|
||||
if (_messageQueue.size() < SSE_MAX_QUEUED_MESSAGES >> 2 && _client->canSend()) {
|
||||
_runQueue();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::_onAck(size_t len __attribute__((unused)), uint32_t time __attribute__((unused))) {
|
||||
#ifdef ESP32
|
||||
// Same here, acquiring the lock early
|
||||
std::lock_guard<std::mutex> lock(_lockmq);
|
||||
#endif
|
||||
|
||||
// adjust in-flight len
|
||||
if (len < _inflight)
|
||||
_inflight -= len;
|
||||
else
|
||||
_inflight = 0;
|
||||
|
||||
// acknowledge as much messages's data as we got confirmed len from a AsyncTCP
|
||||
while (len && _messageQueue.size()) {
|
||||
len = _messageQueue.front().ack(len);
|
||||
if (_messageQueue.front().finished()) {
|
||||
// now we could release full ack'ed messages, we were keeping it unless send confirmed from AsyncTCP
|
||||
_messageQueue.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
// try to send another batch of data
|
||||
if (_messageQueue.size())
|
||||
_runQueue();
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::_onAck(size_t len, uint32_t time){
|
||||
while(len && !_messageQueue.isEmpty()){
|
||||
len = _messageQueue.front()->ack(len, time);
|
||||
if(_messageQueue.front()->finished())
|
||||
_messageQueue.remove(_messageQueue.front());
|
||||
}
|
||||
|
||||
_runQueue();
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::_onPoll(){
|
||||
if(!_messageQueue.isEmpty()){
|
||||
void AsyncEventSourceClient::_onPoll() {
|
||||
if (_messageQueue.size()) {
|
||||
#ifdef ESP32
|
||||
// Same here, acquiring the lock early
|
||||
std::lock_guard<std::mutex> lock(_lockmq);
|
||||
#endif
|
||||
_runQueue();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void AsyncEventSourceClient::_onTimeout(uint32_t time __attribute__((unused))){
|
||||
_client->close(true);
|
||||
void AsyncEventSourceClient::_onTimeout(uint32_t time __attribute__((unused))) {
|
||||
if (_client)
|
||||
_client->close(true);
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::_onDisconnect(){
|
||||
_client = NULL;
|
||||
void AsyncEventSourceClient::_onDisconnect() {
|
||||
if (!_client)
|
||||
return;
|
||||
_client = nullptr;
|
||||
_server->_handleDisconnect(this);
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::close(){
|
||||
if(_client != NULL)
|
||||
void AsyncEventSourceClient::close() {
|
||||
if (_client)
|
||||
_client->close();
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::write(const char * message, size_t len){
|
||||
_queueMessage(new AsyncEventSourceMessage(message, len));
|
||||
bool AsyncEventSourceClient::send(const char* message, const char* event, uint32_t id, uint32_t reconnect) {
|
||||
if (!connected())
|
||||
return false;
|
||||
return _queueMessage(std::make_shared<String>(generateEventMessage(message, event, id, reconnect)));
|
||||
}
|
||||
|
||||
void AsyncEventSourceClient::send(const char *message, const char *event, uint32_t id, uint32_t reconnect){
|
||||
String ev = generateEventMessage(message, event, id, reconnect);
|
||||
_queueMessage(new AsyncEventSourceMessage(ev.c_str(), ev.length()));
|
||||
}
|
||||
void AsyncEventSourceClient::_runQueue() {
|
||||
if (!_client)
|
||||
return;
|
||||
|
||||
void AsyncEventSourceClient::_runQueue(){
|
||||
while(!_messageQueue.isEmpty() && _messageQueue.front()->finished()){
|
||||
_messageQueue.remove(_messageQueue.front());
|
||||
// there is no need to lock the mutex here, 'cause all the calls to this method must be already lock'ed
|
||||
size_t total_bytes_written = 0;
|
||||
for (auto i = _messageQueue.begin(); i != _messageQueue.end(); ++i) {
|
||||
if (!i->sent()) {
|
||||
const size_t bytes_written = i->write(_client);
|
||||
total_bytes_written += bytes_written;
|
||||
_inflight += bytes_written;
|
||||
if (bytes_written == 0 || _inflight > _max_inflight) {
|
||||
// Serial.print("_");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for(auto i = _messageQueue.begin(); i != _messageQueue.end(); ++i)
|
||||
{
|
||||
if(!(*i)->sent())
|
||||
(*i)->send(_client);
|
||||
}
|
||||
// flush socket
|
||||
if (total_bytes_written)
|
||||
_client->send();
|
||||
}
|
||||
|
||||
|
||||
// Handler
|
||||
|
||||
AsyncEventSource::AsyncEventSource(const String& url)
|
||||
: _url(url)
|
||||
, _clients(LinkedList<AsyncEventSourceClient *>([](AsyncEventSourceClient *c){ delete c; }))
|
||||
, _connectcb(NULL)
|
||||
{}
|
||||
|
||||
AsyncEventSource::~AsyncEventSource(){
|
||||
close();
|
||||
void AsyncEventSourceClient::set_max_inflight_bytes(size_t value) {
|
||||
if (value >= SSE_MIN_INFLIGH && value <= SSE_MAX_INFLIGH)
|
||||
_max_inflight = value;
|
||||
}
|
||||
|
||||
void AsyncEventSource::onConnect(ArEventHandlerFunction cb){
|
||||
_connectcb = cb;
|
||||
/* AsyncEventSource */
|
||||
|
||||
void AsyncEventSource::authorizeConnect(ArAuthorizeConnectHandler cb) {
|
||||
AsyncAuthorizationMiddleware* m = new AsyncAuthorizationMiddleware(401, cb);
|
||||
m->_freeOnRemoval = true;
|
||||
addMiddleware(m);
|
||||
}
|
||||
|
||||
void AsyncEventSource::_addClient(AsyncEventSourceClient * client){
|
||||
/*char * temp = (char *)malloc(2054);
|
||||
if(temp != NULL){
|
||||
memset(temp+1,' ',2048);
|
||||
temp[0] = ':';
|
||||
temp[2049] = '\r';
|
||||
temp[2050] = '\n';
|
||||
temp[2051] = '\r';
|
||||
temp[2052] = '\n';
|
||||
temp[2053] = 0;
|
||||
client->write((const char *)temp, 2053);
|
||||
free(temp);
|
||||
}*/
|
||||
|
||||
_clients.add(client);
|
||||
if(_connectcb)
|
||||
void AsyncEventSource::_addClient(AsyncEventSourceClient* client) {
|
||||
if (!client)
|
||||
return;
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
_clients.emplace_back(client);
|
||||
if (_connectcb)
|
||||
_connectcb(client);
|
||||
|
||||
_adjust_inflight_window();
|
||||
}
|
||||
|
||||
void AsyncEventSource::_handleDisconnect(AsyncEventSourceClient * client){
|
||||
_clients.remove(client);
|
||||
void AsyncEventSource::_handleDisconnect(AsyncEventSourceClient* client) {
|
||||
if (_disconnectcb)
|
||||
_disconnectcb(client);
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
for (auto i = _clients.begin(); i != _clients.end(); ++i) {
|
||||
if (i->get() == client)
|
||||
_clients.erase(i);
|
||||
}
|
||||
_adjust_inflight_window();
|
||||
}
|
||||
|
||||
void AsyncEventSource::close(){
|
||||
for(const auto &c: _clients){
|
||||
if(c->connected())
|
||||
void AsyncEventSource::close() {
|
||||
// While the whole loop is not done, the linked list is locked and so the
|
||||
// iterator should remain valid even when AsyncEventSource::_handleDisconnect()
|
||||
// is called very early
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
for (const auto& c : _clients) {
|
||||
if (c->connected())
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
|
||||
// pmb fix
|
||||
size_t AsyncEventSource::avgPacketsWaiting() const {
|
||||
if(_clients.isEmpty())
|
||||
size_t aql = 0;
|
||||
uint32_t nConnectedClients = 0;
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
if (!_clients.size())
|
||||
return 0;
|
||||
|
||||
size_t aql=0;
|
||||
uint32_t nConnectedClients=0;
|
||||
|
||||
for(const auto &c: _clients){
|
||||
if(c->connected()) {
|
||||
aql+=c->packetsWaiting();
|
||||
|
||||
for (const auto& c : _clients) {
|
||||
if (c->connected()) {
|
||||
aql += c->packetsWaiting();
|
||||
++nConnectedClients;
|
||||
}
|
||||
}
|
||||
// return aql / nConnectedClients;
|
||||
return ((aql) + (nConnectedClients/2))/(nConnectedClients); // round up
|
||||
return ((aql) + (nConnectedClients / 2)) / (nConnectedClients); // round up
|
||||
}
|
||||
|
||||
void AsyncEventSource::send(const char *message, const char *event, uint32_t id, uint32_t reconnect){
|
||||
|
||||
|
||||
String ev = generateEventMessage(message, event, id, reconnect);
|
||||
for(const auto &c: _clients){
|
||||
if(c->connected()) {
|
||||
c->write(ev.c_str(), ev.length());
|
||||
}
|
||||
AsyncEventSource::SendStatus AsyncEventSource::send(
|
||||
const char* message, const char* event, uint32_t id, uint32_t reconnect) {
|
||||
AsyncEvent_SharedData_t shared_msg = std::make_shared<String>(generateEventMessage(message, event, id, reconnect));
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
size_t hits = 0;
|
||||
size_t miss = 0;
|
||||
for (const auto& c : _clients) {
|
||||
if (c->write(shared_msg))
|
||||
++hits;
|
||||
else
|
||||
++miss;
|
||||
}
|
||||
return hits == 0 ? DISCARDED : (miss == 0 ? ENQUEUED : PARTIALLY_ENQUEUED);
|
||||
}
|
||||
|
||||
size_t AsyncEventSource::count() const {
|
||||
return _clients.count_if([](AsyncEventSourceClient *c){
|
||||
return c->connected();
|
||||
});
|
||||
#ifdef ESP32
|
||||
std::lock_guard<std::mutex> lock(_client_queue_lock);
|
||||
#endif
|
||||
size_t n_clients{0};
|
||||
for (const auto& i : _clients)
|
||||
if (i->connected())
|
||||
++n_clients;
|
||||
|
||||
return n_clients;
|
||||
}
|
||||
|
||||
bool AsyncEventSource::canHandle(AsyncWebServerRequest *request){
|
||||
if(request->method() != HTTP_GET || !request->url().equals(_url)) {
|
||||
return false;
|
||||
}
|
||||
request->addInterestingHeader("Last-Event-ID");
|
||||
return true;
|
||||
bool AsyncEventSource::canHandle(AsyncWebServerRequest* request) const {
|
||||
return request->isSSE() && request->url().equals(_url);
|
||||
}
|
||||
|
||||
void AsyncEventSource::handleRequest(AsyncWebServerRequest *request){
|
||||
if((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
void AsyncEventSource::handleRequest(AsyncWebServerRequest* request) {
|
||||
request->send(new AsyncEventSourceResponse(this));
|
||||
}
|
||||
|
||||
// Response
|
||||
|
||||
AsyncEventSourceResponse::AsyncEventSourceResponse(AsyncEventSource *server){
|
||||
_server = server;
|
||||
_code = 200;
|
||||
_contentType = "text/event-stream";
|
||||
_sendContentLength = false;
|
||||
addHeader("Cache-Control", "no-cache");
|
||||
addHeader("Connection","keep-alive");
|
||||
void AsyncEventSource::_adjust_inflight_window() {
|
||||
if (_clients.size()) {
|
||||
size_t inflight = SSE_MAX_INFLIGH / _clients.size();
|
||||
for (const auto& c : _clients)
|
||||
c->set_max_inflight_bytes(inflight);
|
||||
// Serial.printf("adjusted inflight to: %u\n", inflight);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncEventSourceResponse::_respond(AsyncWebServerRequest *request){
|
||||
String out = _assembleHead(request->version());
|
||||
/* Response */
|
||||
|
||||
AsyncEventSourceResponse::AsyncEventSourceResponse(AsyncEventSource* server) {
|
||||
_server = server;
|
||||
_code = 200;
|
||||
_contentType = T_text_event_stream;
|
||||
_sendContentLength = false;
|
||||
addHeader(T_Cache_Control, T_no_cache);
|
||||
addHeader(T_Connection, T_keep_alive);
|
||||
}
|
||||
|
||||
void AsyncEventSourceResponse::_respond(AsyncWebServerRequest* request) {
|
||||
String out;
|
||||
_assembleHead(out, request->version());
|
||||
request->client()->write(out.c_str(), _headLength);
|
||||
_state = RESPONSE_WAIT_ACK;
|
||||
}
|
||||
|
||||
size_t AsyncEventSourceResponse::_ack(AsyncWebServerRequest *request, size_t len, uint32_t time __attribute__((unused))){
|
||||
if(len){
|
||||
size_t AsyncEventSourceResponse::_ack(AsyncWebServerRequest* request, size_t len, uint32_t time __attribute__((unused))) {
|
||||
if (len) {
|
||||
new AsyncEventSourceClient(request, _server);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
@ -21,113 +21,272 @@
|
||||
#define ASYNCEVENTSOURCE_H_
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#define SSE_MAX_QUEUED_MESSAGES 32
|
||||
#else
|
||||
#include <ESPAsyncTCP.h>
|
||||
#define SSE_MAX_QUEUED_MESSAGES 8
|
||||
#include <AsyncTCP.h>
|
||||
#include <mutex>
|
||||
#ifndef SSE_MAX_QUEUED_MESSAGES
|
||||
#define SSE_MAX_QUEUED_MESSAGES 32
|
||||
#endif
|
||||
#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets
|
||||
#define SSE_MAX_INFLIGH 16 * 1024 // but no more than 16k, no need to blow it, since same data is kept in local Q
|
||||
#elif defined(ESP8266)
|
||||
#include <ESPAsyncTCP.h>
|
||||
#ifndef SSE_MAX_QUEUED_MESSAGES
|
||||
#define SSE_MAX_QUEUED_MESSAGES 8
|
||||
#endif
|
||||
#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets
|
||||
#define SSE_MAX_INFLIGH 8 * 1024 // but no more than 8k, no need to blow it, since same data is kept in local Q
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <AsyncTCP_RP2040W.h>
|
||||
#ifndef SSE_MAX_QUEUED_MESSAGES
|
||||
#define SSE_MAX_QUEUED_MESSAGES 32
|
||||
#endif
|
||||
#define SSE_MIN_INFLIGH 2 * 1460 // allow 2 MSS packets
|
||||
#define SSE_MAX_INFLIGH 16 * 1024 // but no more than 16k, no need to blow it, since same data is kept in local Q
|
||||
#endif
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include "AsyncWebSynchronization.h"
|
||||
|
||||
#ifdef ESP8266
|
||||
#include <Hash.h>
|
||||
#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library
|
||||
#include <../src/Hash.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef ESP32
|
||||
#define DEFAULT_MAX_SSE_CLIENTS 8
|
||||
#else
|
||||
#define DEFAULT_MAX_SSE_CLIENTS 4
|
||||
#include <Hash.h>
|
||||
#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library
|
||||
#include <../src/Hash.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
class AsyncEventSource;
|
||||
class AsyncEventSourceResponse;
|
||||
class AsyncEventSourceClient;
|
||||
typedef std::function<void(AsyncEventSourceClient *client)> ArEventHandlerFunction;
|
||||
using ArEventHandlerFunction = std::function<void(AsyncEventSourceClient* client)>;
|
||||
using ArAuthorizeConnectHandler = ArAuthorizeFunction;
|
||||
// shared message object container
|
||||
using AsyncEvent_SharedData_t = std::shared_ptr<String>;
|
||||
|
||||
/**
|
||||
* @brief Async Event Message container with shared message content data
|
||||
*
|
||||
*/
|
||||
class AsyncEventSourceMessage {
|
||||
|
||||
private:
|
||||
uint8_t * _data;
|
||||
size_t _len;
|
||||
size_t _sent;
|
||||
//size_t _ack;
|
||||
size_t _acked;
|
||||
const AsyncEvent_SharedData_t _data;
|
||||
size_t _sent{0}; // num of bytes already sent
|
||||
size_t _acked{0}; // num of bytes acked
|
||||
|
||||
public:
|
||||
AsyncEventSourceMessage(const char * data, size_t len);
|
||||
~AsyncEventSourceMessage();
|
||||
size_t ack(size_t len, uint32_t time __attribute__((unused)));
|
||||
size_t send(AsyncClient *client);
|
||||
bool finished(){ return _acked == _len; }
|
||||
bool sent() { return _sent == _len; }
|
||||
AsyncEventSourceMessage(AsyncEvent_SharedData_t data) : _data(data) {};
|
||||
#ifdef ESP32
|
||||
AsyncEventSourceMessage(const char* data, size_t len) : _data(std::make_shared<String>(data, len)) {};
|
||||
#else
|
||||
// esp8266's String does not have constructor with data/length arguments. Use a concat method here
|
||||
AsyncEventSourceMessage(const char* data, size_t len) { _data->concat(data, len); };
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief acknowledge sending len bytes of data
|
||||
* @note if num of bytes to ack is larger then the unacknowledged message length the number of carried over bytes are returned
|
||||
*
|
||||
* @param len bytes to acknowlegde
|
||||
* @param time
|
||||
* @return size_t number of extra bytes carried over
|
||||
*/
|
||||
size_t ack(size_t len, uint32_t time = 0);
|
||||
|
||||
/**
|
||||
* @brief write message data to client's buffer
|
||||
* @note this method does NOT call client's send
|
||||
*
|
||||
* @param client
|
||||
* @return size_t number of bytes written
|
||||
*/
|
||||
size_t write(AsyncClient* client);
|
||||
|
||||
/**
|
||||
* @brief writes message data to client's buffer and calls client's send method
|
||||
*
|
||||
* @param client
|
||||
* @return size_t returns num of bytes the clien was able to send()
|
||||
*/
|
||||
size_t send(AsyncClient* client);
|
||||
|
||||
// returns true if full message's length were acked
|
||||
bool finished() { return _acked == _data->length(); }
|
||||
|
||||
/**
|
||||
* @brief returns true if all data has been sent already
|
||||
*
|
||||
*/
|
||||
bool sent() { return _sent == _data->length(); }
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief class holds a sse messages queue for a particular client's connection
|
||||
*
|
||||
*/
|
||||
class AsyncEventSourceClient {
|
||||
private:
|
||||
AsyncClient *_client;
|
||||
AsyncEventSource *_server;
|
||||
uint32_t _lastId;
|
||||
LinkedList<AsyncEventSourceMessage *> _messageQueue;
|
||||
void _queueMessage(AsyncEventSourceMessage *dataMessage);
|
||||
AsyncClient* _client;
|
||||
AsyncEventSource* _server;
|
||||
uint32_t _lastId{0};
|
||||
size_t _inflight{0}; // num of unacknowledged bytes that has been written to socket buffer
|
||||
size_t _max_inflight{SSE_MAX_INFLIGH}; // max num of unacknowledged bytes that could be written to socket buffer
|
||||
std::list<AsyncEventSourceMessage> _messageQueue;
|
||||
#ifdef ESP32
|
||||
mutable std::mutex _lockmq;
|
||||
#endif
|
||||
bool _queueMessage(const char* message, size_t len);
|
||||
bool _queueMessage(AsyncEvent_SharedData_t&& msg);
|
||||
void _runQueue();
|
||||
|
||||
public:
|
||||
|
||||
AsyncEventSourceClient(AsyncWebServerRequest *request, AsyncEventSource *server);
|
||||
AsyncEventSourceClient(AsyncWebServerRequest* request, AsyncEventSource* server);
|
||||
~AsyncEventSourceClient();
|
||||
|
||||
AsyncClient* client(){ return _client; }
|
||||
void close();
|
||||
void write(const char * message, size_t len);
|
||||
void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0);
|
||||
bool connected() const { return (_client != NULL) && _client->connected(); }
|
||||
uint32_t lastId() const { return _lastId; }
|
||||
size_t packetsWaiting() const { return _messageQueue.length(); }
|
||||
/**
|
||||
* @brief Send an SSE message to client
|
||||
* it will craft an SSE message and place it to client's message queue
|
||||
*
|
||||
* @param message body string, could be single or multi-line string sepprated by \n, \r, \r\n
|
||||
* @param event body string, a sinle line string
|
||||
* @param id sequence id
|
||||
* @param reconnect client's reconnect timeout
|
||||
* @return true if message was placed in a queue
|
||||
* @return false if queue is full
|
||||
*/
|
||||
bool send(const char* message, const char* event = NULL, uint32_t id = 0, uint32_t reconnect = 0);
|
||||
bool send(const String& message, const String& event, uint32_t id = 0, uint32_t reconnect = 0) { return send(message.c_str(), event.c_str(), id, reconnect); }
|
||||
bool send(const String& message, const char* event, uint32_t id = 0, uint32_t reconnect = 0) { return send(message.c_str(), event, id, reconnect); }
|
||||
|
||||
//system callbacks (do not call)
|
||||
/**
|
||||
* @brief place supplied preformatted SSE message to the message queue
|
||||
* @note message must a properly formatted SSE string according to https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
|
||||
*
|
||||
* @param message data
|
||||
* @return true on success
|
||||
* @return false on queue overflow or no client connected
|
||||
*/
|
||||
bool write(AsyncEvent_SharedData_t message) { return connected() && _queueMessage(std::move(message)); };
|
||||
|
||||
[[deprecated("Use _write(AsyncEvent_SharedData_t message) instead to share same data with multiple SSE clients")]]
|
||||
bool write(const char* message, size_t len) { return connected() && _queueMessage(message, len); };
|
||||
|
||||
// close client's connection
|
||||
void close();
|
||||
|
||||
// getters
|
||||
|
||||
AsyncClient* client() { return _client; }
|
||||
bool connected() const { return _client && _client->connected(); }
|
||||
uint32_t lastId() const { return _lastId; }
|
||||
size_t packetsWaiting() const { return _messageQueue.size(); };
|
||||
|
||||
/**
|
||||
* @brief Sets max amount of bytes that could be written to client's socket while awaiting delivery acknowledge
|
||||
* used to throttle message delivery length to tradeoff memory consumption
|
||||
* @note actual amount of data written could possible be a bit larger but no more than available socket buff space
|
||||
*
|
||||
* @param value
|
||||
*/
|
||||
void set_max_inflight_bytes(size_t value);
|
||||
|
||||
/**
|
||||
* @brief Get current max inflight bytes value
|
||||
*
|
||||
* @return size_t
|
||||
*/
|
||||
size_t get_max_inflight_bytes() const { return _max_inflight; }
|
||||
|
||||
// system callbacks (do not call if from user code!)
|
||||
void _onAck(size_t len, uint32_t time);
|
||||
void _onPoll();
|
||||
void _onPoll();
|
||||
void _onTimeout(uint32_t time);
|
||||
void _onDisconnect();
|
||||
};
|
||||
|
||||
class AsyncEventSource: public AsyncWebHandler {
|
||||
/**
|
||||
* @brief a class that maintains all connected HTTP clients subscribed to SSE delivery
|
||||
* dispatches supplied messages to the client's queues
|
||||
*
|
||||
*/
|
||||
class AsyncEventSource : public AsyncWebHandler {
|
||||
private:
|
||||
String _url;
|
||||
LinkedList<AsyncEventSourceClient *> _clients;
|
||||
ArEventHandlerFunction _connectcb;
|
||||
std::list<std::unique_ptr<AsyncEventSourceClient>> _clients;
|
||||
#ifdef ESP32
|
||||
// Same as for individual messages, protect mutations of _clients list
|
||||
// since simultaneous access from different tasks is possible
|
||||
mutable std::mutex _client_queue_lock;
|
||||
#endif
|
||||
ArEventHandlerFunction _connectcb = nullptr;
|
||||
ArEventHandlerFunction _disconnectcb = nullptr;
|
||||
|
||||
// this method manipulates in-fligh data size for connected client depending on number of active connections
|
||||
void _adjust_inflight_window();
|
||||
|
||||
public:
|
||||
AsyncEventSource(const String& url);
|
||||
~AsyncEventSource();
|
||||
typedef enum {
|
||||
DISCARDED = 0,
|
||||
ENQUEUED = 1,
|
||||
PARTIALLY_ENQUEUED = 2,
|
||||
} SendStatus;
|
||||
|
||||
const char * url() const { return _url.c_str(); }
|
||||
AsyncEventSource(const char* url) : _url(url) {};
|
||||
AsyncEventSource(const String& url) : _url(url) {};
|
||||
~AsyncEventSource() { close(); };
|
||||
|
||||
const char* url() const { return _url.c_str(); }
|
||||
// close all connected clients
|
||||
void close();
|
||||
void onConnect(ArEventHandlerFunction cb);
|
||||
void send(const char *message, const char *event=NULL, uint32_t id=0, uint32_t reconnect=0);
|
||||
size_t count() const; //number clinets connected
|
||||
size_t avgPacketsWaiting() const;
|
||||
|
||||
//system callbacks (do not call)
|
||||
void _addClient(AsyncEventSourceClient * client);
|
||||
void _handleDisconnect(AsyncEventSourceClient * client);
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final;
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final;
|
||||
/**
|
||||
* @brief set on-connect callback for the client
|
||||
* used to deliver messages to client on first connect
|
||||
*
|
||||
* @param cb
|
||||
*/
|
||||
void onConnect(ArEventHandlerFunction cb) { _connectcb = cb; }
|
||||
|
||||
/**
|
||||
* @brief Send an SSE message to client
|
||||
* it will craft an SSE message and place it to all connected client's message queues
|
||||
*
|
||||
* @param message body string, could be single or multi-line string sepprated by \n, \r, \r\n
|
||||
* @param event body string, a sinle line string
|
||||
* @param id sequence id
|
||||
* @param reconnect client's reconnect timeout
|
||||
* @return SendStatus if message was placed in any/all/part of the client's queues
|
||||
*/
|
||||
SendStatus send(const char* message, const char* event = NULL, uint32_t id = 0, uint32_t reconnect = 0);
|
||||
SendStatus send(const String& message, const String& event, uint32_t id = 0, uint32_t reconnect = 0) { return send(message.c_str(), event.c_str(), id, reconnect); }
|
||||
SendStatus send(const String& message, const char* event, uint32_t id = 0, uint32_t reconnect = 0) { return send(message.c_str(), event, id, reconnect); }
|
||||
|
||||
// The client pointer sent to the callback is only for reference purposes. DO NOT CALL ANY METHOD ON IT !
|
||||
void onDisconnect(ArEventHandlerFunction cb) { _disconnectcb = cb; }
|
||||
void authorizeConnect(ArAuthorizeConnectHandler cb);
|
||||
|
||||
// returns number of connected clients
|
||||
size_t count() const;
|
||||
|
||||
// returns average number of messages pending in all client's queues
|
||||
size_t avgPacketsWaiting() const;
|
||||
|
||||
// system callbacks (do not call from user code!)
|
||||
void _addClient(AsyncEventSourceClient* client);
|
||||
void _handleDisconnect(AsyncEventSourceClient* client);
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
};
|
||||
|
||||
class AsyncEventSourceResponse: public AsyncWebServerResponse {
|
||||
class AsyncEventSourceResponse : public AsyncWebServerResponse {
|
||||
private:
|
||||
String _content;
|
||||
AsyncEventSource *_server;
|
||||
AsyncEventSource* _server;
|
||||
|
||||
public:
|
||||
AsyncEventSourceResponse(AsyncEventSource *server);
|
||||
void _respond(AsyncWebServerRequest *request);
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time);
|
||||
AsyncEventSourceResponse(AsyncEventSource* server);
|
||||
void _respond(AsyncWebServerRequest* request);
|
||||
size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time);
|
||||
bool _sourceValid() const { return true; }
|
||||
};
|
||||
|
||||
|
||||
#endif /* ASYNCEVENTSOURCE_H_ */
|
||||
|
151
src/AsyncJson.cpp
Normal file
151
src/AsyncJson.cpp
Normal file
@ -0,0 +1,151 @@
|
||||
#include "AsyncJson.h"
|
||||
|
||||
#if ASYNC_JSON_SUPPORT == 1
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
AsyncJsonResponse::AsyncJsonResponse(bool isArray) : _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = asyncsrv::T_application_json;
|
||||
if (isArray)
|
||||
_root = _jsonBuffer.createArray();
|
||||
else
|
||||
_root = _jsonBuffer.createObject();
|
||||
}
|
||||
#elif ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncJsonResponse::AsyncJsonResponse(bool isArray, size_t maxJsonBufferSize) : _jsonBuffer(maxJsonBufferSize), _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = asyncsrv::T_application_json;
|
||||
if (isArray)
|
||||
_root = _jsonBuffer.createNestedArray();
|
||||
else
|
||||
_root = _jsonBuffer.createNestedObject();
|
||||
}
|
||||
#else
|
||||
AsyncJsonResponse::AsyncJsonResponse(bool isArray) : _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = asyncsrv::T_application_json;
|
||||
if (isArray)
|
||||
_root = _jsonBuffer.add<JsonArray>();
|
||||
else
|
||||
_root = _jsonBuffer.add<JsonObject>();
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t AsyncJsonResponse::setLength() {
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
_contentLength = _root.measureLength();
|
||||
#else
|
||||
_contentLength = measureJson(_root);
|
||||
#endif
|
||||
if (_contentLength) {
|
||||
_isValid = true;
|
||||
}
|
||||
return _contentLength;
|
||||
}
|
||||
|
||||
size_t AsyncJsonResponse::_fillBuffer(uint8_t* data, size_t len) {
|
||||
ChunkPrint dest(data, _sentLength, len);
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
_root.printTo(dest);
|
||||
#else
|
||||
serializeJson(_root, dest);
|
||||
#endif
|
||||
return len;
|
||||
}
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
PrettyAsyncJsonResponse::PrettyAsyncJsonResponse(bool isArray, size_t maxJsonBufferSize) : AsyncJsonResponse{isArray, maxJsonBufferSize} {}
|
||||
#else
|
||||
PrettyAsyncJsonResponse::PrettyAsyncJsonResponse(bool isArray) : AsyncJsonResponse{isArray} {}
|
||||
#endif
|
||||
|
||||
size_t PrettyAsyncJsonResponse::setLength() {
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
_contentLength = _root.measurePrettyLength();
|
||||
#else
|
||||
_contentLength = measureJsonPretty(_root);
|
||||
#endif
|
||||
if (_contentLength) {
|
||||
_isValid = true;
|
||||
}
|
||||
return _contentLength;
|
||||
}
|
||||
|
||||
size_t PrettyAsyncJsonResponse::_fillBuffer(uint8_t* data, size_t len) {
|
||||
ChunkPrint dest(data, _sentLength, len);
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
_root.prettyPrintTo(dest);
|
||||
#else
|
||||
serializeJsonPretty(_root, dest);
|
||||
#endif
|
||||
return len;
|
||||
}
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest, size_t maxJsonBufferSize)
|
||||
: _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {}
|
||||
#else
|
||||
AsyncCallbackJsonWebHandler::AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest)
|
||||
: _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {}
|
||||
#endif
|
||||
|
||||
bool AsyncCallbackJsonWebHandler::canHandle(AsyncWebServerRequest* request) const {
|
||||
if (!_onRequest || !request->isHTTP() || !(_method & request->method()))
|
||||
return false;
|
||||
|
||||
if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/")))
|
||||
return false;
|
||||
|
||||
if (request->method() != HTTP_GET && !request->contentType().equalsIgnoreCase(asyncsrv::T_application_json))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AsyncCallbackJsonWebHandler::handleRequest(AsyncWebServerRequest* request) {
|
||||
if (_onRequest) {
|
||||
if (request->method() == HTTP_GET) {
|
||||
JsonVariant json;
|
||||
_onRequest(request, json);
|
||||
return;
|
||||
} else if (request->_tempObject != NULL) {
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonVariant json = jsonBuffer.parse((uint8_t*)(request->_tempObject));
|
||||
if (json.success()) {
|
||||
#elif ARDUINOJSON_VERSION_MAJOR == 6
|
||||
DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize);
|
||||
DeserializationError error = deserializeJson(jsonBuffer, (uint8_t*)(request->_tempObject));
|
||||
if (!error) {
|
||||
JsonVariant json = jsonBuffer.as<JsonVariant>();
|
||||
#else
|
||||
JsonDocument jsonBuffer;
|
||||
DeserializationError error = deserializeJson(jsonBuffer, (uint8_t*)(request->_tempObject));
|
||||
if (!error) {
|
||||
JsonVariant json = jsonBuffer.as<JsonVariant>();
|
||||
#endif
|
||||
|
||||
_onRequest(request, json);
|
||||
return;
|
||||
}
|
||||
}
|
||||
request->send(_contentLength > _maxContentLength ? 413 : 400);
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncCallbackJsonWebHandler::handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) {
|
||||
if (_onRequest) {
|
||||
_contentLength = total;
|
||||
if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) {
|
||||
request->_tempObject = malloc(total);
|
||||
}
|
||||
if (request->_tempObject != NULL) {
|
||||
memcpy((uint8_t*)(request->_tempObject) + index, data, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ASYNC_JSON_SUPPORT
|
277
src/AsyncJson.h
277
src/AsyncJson.h
@ -26,229 +26,106 @@
|
||||
|
||||
AsyncCallbackJsonWebHandler* handler = new AsyncCallbackJsonWebHandler("/rest/endpoint");
|
||||
handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
JsonObject& jsonObj = json.as<JsonObject>();
|
||||
JsonObject jsonObj = json.as<JsonObject>();
|
||||
// ...
|
||||
});
|
||||
server.addHandler(handler);
|
||||
|
||||
|
||||
*/
|
||||
#ifndef ASYNC_JSON_H_
|
||||
#define ASYNC_JSON_H_
|
||||
#include <ArduinoJson.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <Print.h>
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
#define ARDUINOJSON_5_COMPATIBILITY
|
||||
#else
|
||||
#ifndef DYNAMIC_JSON_DOCUMENT_SIZE
|
||||
#define DYNAMIC_JSON_DOCUMENT_SIZE 1024
|
||||
#if __has_include("ArduinoJson.h")
|
||||
#include <ArduinoJson.h>
|
||||
#if ARDUINOJSON_VERSION_MAJOR >= 5
|
||||
#define ASYNC_JSON_SUPPORT 1
|
||||
#else
|
||||
#define ASYNC_JSON_SUPPORT 0
|
||||
#endif // ARDUINOJSON_VERSION_MAJOR >= 5
|
||||
#endif // __has_include("ArduinoJson.h")
|
||||
|
||||
#if ASYNC_JSON_SUPPORT == 1
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include "ChunkPrint.h"
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
#ifndef DYNAMIC_JSON_DOCUMENT_SIZE
|
||||
#define DYNAMIC_JSON_DOCUMENT_SIZE 1024
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
constexpr const char* JSON_MIMETYPE = "application/json";
|
||||
|
||||
/*
|
||||
* Json Response
|
||||
* */
|
||||
|
||||
class ChunkPrint : public Print {
|
||||
private:
|
||||
uint8_t* _destination;
|
||||
size_t _to_skip;
|
||||
size_t _to_write;
|
||||
size_t _pos;
|
||||
public:
|
||||
ChunkPrint(uint8_t* destination, size_t from, size_t len)
|
||||
: _destination(destination), _to_skip(from), _to_write(len), _pos{0} {}
|
||||
virtual ~ChunkPrint(){}
|
||||
size_t write(uint8_t c){
|
||||
if (_to_skip > 0) {
|
||||
_to_skip--;
|
||||
return 1;
|
||||
} else if (_to_write > 0) {
|
||||
_to_write--;
|
||||
_destination[_pos++] = c;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
size_t write(const uint8_t *buffer, size_t size)
|
||||
{
|
||||
return this->Print::write(buffer, size);
|
||||
}
|
||||
};
|
||||
|
||||
class AsyncJsonResponse: public AsyncAbstractResponse {
|
||||
class AsyncJsonResponse : public AsyncAbstractResponse {
|
||||
protected:
|
||||
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 5
|
||||
DynamicJsonBuffer _jsonBuffer;
|
||||
#else
|
||||
#elif ARDUINOJSON_VERSION_MAJOR == 6
|
||||
DynamicJsonDocument _jsonBuffer;
|
||||
#endif
|
||||
#else
|
||||
JsonDocument _jsonBuffer;
|
||||
#endif
|
||||
|
||||
JsonVariant _root;
|
||||
bool _isValid;
|
||||
|
||||
public:
|
||||
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
AsyncJsonResponse(bool isArray=false): _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = JSON_MIMETYPE;
|
||||
if(isArray)
|
||||
_root = _jsonBuffer.createArray();
|
||||
else
|
||||
_root = _jsonBuffer.createObject();
|
||||
}
|
||||
#else
|
||||
AsyncJsonResponse(bool isArray=false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE) : _jsonBuffer(maxJsonBufferSize), _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = JSON_MIMETYPE;
|
||||
if(isArray)
|
||||
_root = _jsonBuffer.createNestedArray();
|
||||
else
|
||||
_root = _jsonBuffer.createNestedObject();
|
||||
}
|
||||
#endif
|
||||
|
||||
~AsyncJsonResponse() {}
|
||||
JsonVariant & getRoot() { return _root; }
|
||||
public:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE);
|
||||
#else
|
||||
AsyncJsonResponse(bool isArray = false);
|
||||
#endif
|
||||
JsonVariant& getRoot() { return _root; }
|
||||
bool _sourceValid() const { return _isValid; }
|
||||
size_t setLength() {
|
||||
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
_contentLength = _root.measureLength();
|
||||
#else
|
||||
_contentLength = measureJson(_root);
|
||||
#endif
|
||||
|
||||
if (_contentLength) { _isValid = true; }
|
||||
return _contentLength;
|
||||
}
|
||||
|
||||
size_t getSize() { return _jsonBuffer.size(); }
|
||||
|
||||
size_t _fillBuffer(uint8_t *data, size_t len){
|
||||
ChunkPrint dest(data, _sentLength, len);
|
||||
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
_root.printTo( dest ) ;
|
||||
#else
|
||||
serializeJson(_root, dest);
|
||||
#endif
|
||||
return len;
|
||||
}
|
||||
size_t setLength();
|
||||
size_t getSize() const { return _jsonBuffer.size(); }
|
||||
size_t _fillBuffer(uint8_t* data, size_t len);
|
||||
#if ARDUINOJSON_VERSION_MAJOR >= 6
|
||||
bool overflowed() const { return _jsonBuffer.overflowed(); }
|
||||
#endif
|
||||
};
|
||||
|
||||
class PrettyAsyncJsonResponse: public AsyncJsonResponse {
|
||||
public:
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
PrettyAsyncJsonResponse (bool isArray=false) : AsyncJsonResponse{isArray} {}
|
||||
#else
|
||||
PrettyAsyncJsonResponse (bool isArray=false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE) : AsyncJsonResponse{isArray, maxJsonBufferSize} {}
|
||||
#endif
|
||||
size_t setLength () {
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
_contentLength = _root.measurePrettyLength ();
|
||||
#else
|
||||
_contentLength = measureJsonPretty(_root);
|
||||
#endif
|
||||
if (_contentLength) {_isValid = true;}
|
||||
return _contentLength;
|
||||
}
|
||||
size_t _fillBuffer (uint8_t *data, size_t len) {
|
||||
ChunkPrint dest (data, _sentLength, len);
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
_root.prettyPrintTo (dest);
|
||||
#else
|
||||
serializeJsonPretty(_root, dest);
|
||||
#endif
|
||||
return len;
|
||||
}
|
||||
class PrettyAsyncJsonResponse : public AsyncJsonResponse {
|
||||
public:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
PrettyAsyncJsonResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE);
|
||||
#else
|
||||
PrettyAsyncJsonResponse(bool isArray = false);
|
||||
#endif
|
||||
size_t setLength();
|
||||
size_t _fillBuffer(uint8_t* data, size_t len);
|
||||
};
|
||||
|
||||
typedef std::function<void(AsyncWebServerRequest *request, JsonVariant &json)> ArJsonRequestHandlerFunction;
|
||||
typedef std::function<void(AsyncWebServerRequest* request, JsonVariant& json)> ArJsonRequestHandlerFunction;
|
||||
|
||||
class AsyncCallbackJsonWebHandler: public AsyncWebHandler {
|
||||
private:
|
||||
protected:
|
||||
const String _uri;
|
||||
WebRequestMethodComposite _method;
|
||||
ArJsonRequestHandlerFunction _onRequest;
|
||||
size_t _contentLength;
|
||||
#ifndef ARDUINOJSON_5_COMPATIBILITY
|
||||
const size_t maxJsonBufferSize;
|
||||
#endif
|
||||
size_t _maxContentLength;
|
||||
public:
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest)
|
||||
: _uri(uri), _method(HTTP_POST|HTTP_PUT|HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {}
|
||||
#else
|
||||
AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest, size_t maxJsonBufferSize=DYNAMIC_JSON_DOCUMENT_SIZE)
|
||||
: _uri(uri), _method(HTTP_POST|HTTP_PUT|HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {}
|
||||
#endif
|
||||
|
||||
void setMethod(WebRequestMethodComposite method){ _method = method; }
|
||||
void setMaxContentLength(int maxContentLength){ _maxContentLength = maxContentLength; }
|
||||
void onRequest(ArJsonRequestHandlerFunction fn){ _onRequest = fn; }
|
||||
class AsyncCallbackJsonWebHandler : public AsyncWebHandler {
|
||||
protected:
|
||||
String _uri;
|
||||
WebRequestMethodComposite _method;
|
||||
ArJsonRequestHandlerFunction _onRequest;
|
||||
size_t _contentLength;
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
size_t maxJsonBufferSize;
|
||||
#endif
|
||||
size_t _maxContentLength;
|
||||
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final{
|
||||
if(!_onRequest)
|
||||
return false;
|
||||
public:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest = nullptr, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE);
|
||||
#else
|
||||
AsyncCallbackJsonWebHandler(const String& uri, ArJsonRequestHandlerFunction onRequest = nullptr);
|
||||
#endif
|
||||
|
||||
if(!(_method & request->method()))
|
||||
return false;
|
||||
void setMethod(WebRequestMethodComposite method) { _method = method; }
|
||||
void setMaxContentLength(int maxContentLength) { _maxContentLength = maxContentLength; }
|
||||
void onRequest(ArJsonRequestHandlerFunction fn) { _onRequest = fn; }
|
||||
|
||||
if(_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri+"/")))
|
||||
return false;
|
||||
|
||||
if ( !request->contentType().equalsIgnoreCase(JSON_MIMETYPE) )
|
||||
return false;
|
||||
|
||||
request->addInterestingHeader("ANY");
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final {
|
||||
if(_onRequest) {
|
||||
if (request->_tempObject != NULL) {
|
||||
|
||||
#ifdef ARDUINOJSON_5_COMPATIBILITY
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonVariant json = jsonBuffer.parse((uint8_t*)(request->_tempObject));
|
||||
if (json.success()) {
|
||||
#else
|
||||
DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize);
|
||||
DeserializationError error = deserializeJson(jsonBuffer, (uint8_t*)(request->_tempObject));
|
||||
if(!error) {
|
||||
JsonVariant json = jsonBuffer.as<JsonVariant>();
|
||||
#endif
|
||||
|
||||
_onRequest(request, json);
|
||||
return;
|
||||
}
|
||||
}
|
||||
request->send(_contentLength > _maxContentLength ? 413 : 400);
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
}
|
||||
virtual void handleUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) override final {
|
||||
}
|
||||
virtual void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) override final {
|
||||
if (_onRequest) {
|
||||
_contentLength = total;
|
||||
if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) {
|
||||
request->_tempObject = malloc(total);
|
||||
}
|
||||
if (request->_tempObject != NULL) {
|
||||
memcpy((uint8_t*)(request->_tempObject) + index, data, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
virtual bool isRequestHandlerTrivial() override final {return _onRequest ? false : true;}
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
void handleUpload(__unused AsyncWebServerRequest* request, __unused const String& filename, __unused size_t index, __unused uint8_t* data, __unused size_t len, __unused bool final) override final {}
|
||||
void handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) override final;
|
||||
bool isRequestHandlerTrivial() const override final { return !_onRequest; }
|
||||
};
|
||||
#endif
|
||||
|
||||
#endif // ASYNC_JSON_SUPPORT == 1
|
||||
|
||||
#endif // ASYNC_JSON_H_
|
||||
|
102
src/AsyncMessagePack.cpp
Normal file
102
src/AsyncMessagePack.cpp
Normal file
@ -0,0 +1,102 @@
|
||||
#include "AsyncMessagePack.h"
|
||||
|
||||
#if ASYNC_MSG_PACK_SUPPORT == 1
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncMessagePackResponse::AsyncMessagePackResponse(bool isArray, size_t maxJsonBufferSize) : _jsonBuffer(maxJsonBufferSize), _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = asyncsrv::T_application_msgpack;
|
||||
if (isArray)
|
||||
_root = _jsonBuffer.createNestedArray();
|
||||
else
|
||||
_root = _jsonBuffer.createNestedObject();
|
||||
}
|
||||
#else
|
||||
AsyncMessagePackResponse::AsyncMessagePackResponse(bool isArray) : _isValid{false} {
|
||||
_code = 200;
|
||||
_contentType = asyncsrv::T_application_msgpack;
|
||||
if (isArray)
|
||||
_root = _jsonBuffer.add<JsonArray>();
|
||||
else
|
||||
_root = _jsonBuffer.add<JsonObject>();
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t AsyncMessagePackResponse::setLength() {
|
||||
_contentLength = measureMsgPack(_root);
|
||||
if (_contentLength) {
|
||||
_isValid = true;
|
||||
}
|
||||
return _contentLength;
|
||||
}
|
||||
|
||||
size_t AsyncMessagePackResponse::_fillBuffer(uint8_t* data, size_t len) {
|
||||
ChunkPrint dest(data, _sentLength, len);
|
||||
serializeMsgPack(_root, dest);
|
||||
return len;
|
||||
}
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncCallbackMessagePackWebHandler::AsyncCallbackMessagePackWebHandler(const String& uri, ArMessagePackRequestHandlerFunction onRequest, size_t maxJsonBufferSize)
|
||||
: _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), maxJsonBufferSize(maxJsonBufferSize), _maxContentLength(16384) {}
|
||||
#else
|
||||
AsyncCallbackMessagePackWebHandler::AsyncCallbackMessagePackWebHandler(const String& uri, ArMessagePackRequestHandlerFunction onRequest)
|
||||
: _uri(uri), _method(HTTP_GET | HTTP_POST | HTTP_PUT | HTTP_PATCH), _onRequest(onRequest), _maxContentLength(16384) {}
|
||||
#endif
|
||||
|
||||
bool AsyncCallbackMessagePackWebHandler::canHandle(AsyncWebServerRequest* request) const {
|
||||
if (!_onRequest || !request->isHTTP() || !(_method & request->method()))
|
||||
return false;
|
||||
|
||||
if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/")))
|
||||
return false;
|
||||
|
||||
if (request->method() != HTTP_GET && !request->contentType().equalsIgnoreCase(asyncsrv::T_application_msgpack))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AsyncCallbackMessagePackWebHandler::handleRequest(AsyncWebServerRequest* request) {
|
||||
if (_onRequest) {
|
||||
if (request->method() == HTTP_GET) {
|
||||
JsonVariant json;
|
||||
_onRequest(request, json);
|
||||
return;
|
||||
} else if (request->_tempObject != NULL) {
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
DynamicJsonDocument jsonBuffer(this->maxJsonBufferSize);
|
||||
DeserializationError error = deserializeMsgPack(jsonBuffer, (uint8_t*)(request->_tempObject));
|
||||
if (!error) {
|
||||
JsonVariant json = jsonBuffer.as<JsonVariant>();
|
||||
#else
|
||||
JsonDocument jsonBuffer;
|
||||
DeserializationError error = deserializeMsgPack(jsonBuffer, (uint8_t*)(request->_tempObject));
|
||||
if (!error) {
|
||||
JsonVariant json = jsonBuffer.as<JsonVariant>();
|
||||
#endif
|
||||
|
||||
_onRequest(request, json);
|
||||
return;
|
||||
}
|
||||
}
|
||||
request->send(_contentLength > _maxContentLength ? 413 : 400);
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncCallbackMessagePackWebHandler::handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) {
|
||||
if (_onRequest) {
|
||||
_contentLength = total;
|
||||
if (total > 0 && request->_tempObject == NULL && total < _maxContentLength) {
|
||||
request->_tempObject = malloc(total);
|
||||
}
|
||||
if (request->_tempObject != NULL) {
|
||||
memcpy((uint8_t*)(request->_tempObject) + index, data, len);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ASYNC_MSG_PACK_SUPPORT
|
102
src/AsyncMessagePack.h
Normal file
102
src/AsyncMessagePack.h
Normal file
@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
server.on("/msg_pack", HTTP_ANY, [](AsyncWebServerRequest * request) {
|
||||
AsyncMessagePackResponse * response = new AsyncMessagePackResponse();
|
||||
JsonObject& root = response->getRoot();
|
||||
root["key1"] = "key number one";
|
||||
JsonObject& nested = root.createNestedObject("nested");
|
||||
nested["key1"] = "key number one";
|
||||
response->setLength();
|
||||
request->send(response);
|
||||
});
|
||||
|
||||
--------------------
|
||||
|
||||
AsyncCallbackMessagePackWebHandler* handler = new AsyncCallbackMessagePackWebHandler("/msg_pack/endpoint");
|
||||
handler->onRequest([](AsyncWebServerRequest *request, JsonVariant &json) {
|
||||
JsonObject jsonObj = json.as<JsonObject>();
|
||||
// ...
|
||||
});
|
||||
server.addHandler(handler);
|
||||
*/
|
||||
|
||||
#if __has_include("ArduinoJson.h")
|
||||
#include <ArduinoJson.h>
|
||||
#if ARDUINOJSON_VERSION_MAJOR >= 6
|
||||
#define ASYNC_MSG_PACK_SUPPORT 1
|
||||
#else
|
||||
#define ASYNC_MSG_PACK_SUPPORT 0
|
||||
#endif // ARDUINOJSON_VERSION_MAJOR >= 6
|
||||
#endif // __has_include("ArduinoJson.h")
|
||||
|
||||
#if ASYNC_MSG_PACK_SUPPORT == 1
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include "ChunkPrint.h"
|
||||
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
#ifndef DYNAMIC_JSON_DOCUMENT_SIZE
|
||||
#define DYNAMIC_JSON_DOCUMENT_SIZE 1024
|
||||
#endif
|
||||
#endif
|
||||
|
||||
class AsyncMessagePackResponse : public AsyncAbstractResponse {
|
||||
protected:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
DynamicJsonDocument _jsonBuffer;
|
||||
#else
|
||||
JsonDocument _jsonBuffer;
|
||||
#endif
|
||||
|
||||
JsonVariant _root;
|
||||
bool _isValid;
|
||||
|
||||
public:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncMessagePackResponse(bool isArray = false, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE);
|
||||
#else
|
||||
AsyncMessagePackResponse(bool isArray = false);
|
||||
#endif
|
||||
JsonVariant& getRoot() { return _root; }
|
||||
bool _sourceValid() const { return _isValid; }
|
||||
size_t setLength();
|
||||
size_t getSize() const { return _jsonBuffer.size(); }
|
||||
size_t _fillBuffer(uint8_t* data, size_t len);
|
||||
#if ARDUINOJSON_VERSION_MAJOR >= 6
|
||||
bool overflowed() const { return _jsonBuffer.overflowed(); }
|
||||
#endif
|
||||
};
|
||||
|
||||
typedef std::function<void(AsyncWebServerRequest* request, JsonVariant& json)> ArMessagePackRequestHandlerFunction;
|
||||
|
||||
class AsyncCallbackMessagePackWebHandler : public AsyncWebHandler {
|
||||
protected:
|
||||
String _uri;
|
||||
WebRequestMethodComposite _method;
|
||||
ArMessagePackRequestHandlerFunction _onRequest;
|
||||
size_t _contentLength;
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
size_t maxJsonBufferSize;
|
||||
#endif
|
||||
size_t _maxContentLength;
|
||||
|
||||
public:
|
||||
#if ARDUINOJSON_VERSION_MAJOR == 6
|
||||
AsyncCallbackMessagePackWebHandler(const String& uri, ArMessagePackRequestHandlerFunction onRequest = nullptr, size_t maxJsonBufferSize = DYNAMIC_JSON_DOCUMENT_SIZE);
|
||||
#else
|
||||
AsyncCallbackMessagePackWebHandler(const String& uri, ArMessagePackRequestHandlerFunction onRequest = nullptr);
|
||||
#endif
|
||||
|
||||
void setMethod(WebRequestMethodComposite method) { _method = method; }
|
||||
void setMaxContentLength(int maxContentLength) { _maxContentLength = maxContentLength; }
|
||||
void onRequest(ArMessagePackRequestHandlerFunction fn) { _onRequest = fn; }
|
||||
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
void handleUpload(__unused AsyncWebServerRequest* request, __unused const String& filename, __unused size_t index, __unused uint8_t* data, __unused size_t len, __unused bool final) override final {}
|
||||
void handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) override final;
|
||||
bool isRequestHandlerTrivial() const override final { return !_onRequest; }
|
||||
};
|
||||
|
||||
#endif // ASYNC_MSG_PACK_SUPPORT == 1
|
22
src/AsyncWebHeader.cpp
Normal file
22
src/AsyncWebHeader.cpp
Normal file
@ -0,0 +1,22 @@
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
AsyncWebHeader::AsyncWebHeader(const String& data) {
|
||||
if (!data)
|
||||
return;
|
||||
int index = data.indexOf(':');
|
||||
if (index < 0)
|
||||
return;
|
||||
_name = data.substring(0, index);
|
||||
_value = data.substring(index + 2);
|
||||
}
|
||||
|
||||
String AsyncWebHeader::toString() const {
|
||||
String str;
|
||||
str.reserve(_name.length() + _value.length() + 2);
|
||||
str.concat(_name);
|
||||
str.concat((char)0x3a);
|
||||
str.concat((char)0x20);
|
||||
str.concat(_value);
|
||||
str.concat(asyncsrv::T_rn);
|
||||
return str;
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -23,29 +23,44 @@
|
||||
|
||||
#include <Arduino.h>
|
||||
#ifdef ESP32
|
||||
#include <AsyncTCP.h>
|
||||
#define WS_MAX_QUEUED_MESSAGES 32
|
||||
#else
|
||||
#include <ESPAsyncTCP.h>
|
||||
#define WS_MAX_QUEUED_MESSAGES 8
|
||||
#include <AsyncTCP.h>
|
||||
#include <mutex>
|
||||
#ifndef WS_MAX_QUEUED_MESSAGES
|
||||
#define WS_MAX_QUEUED_MESSAGES 32
|
||||
#endif
|
||||
#elif defined(ESP8266)
|
||||
#include <ESPAsyncTCP.h>
|
||||
#ifndef WS_MAX_QUEUED_MESSAGES
|
||||
#define WS_MAX_QUEUED_MESSAGES 8
|
||||
#endif
|
||||
#elif defined(TARGET_RP2040)
|
||||
#include <AsyncTCP_RP2040W.h>
|
||||
#ifndef WS_MAX_QUEUED_MESSAGES
|
||||
#define WS_MAX_QUEUED_MESSAGES 32
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#include "AsyncWebSynchronization.h"
|
||||
#include <memory>
|
||||
|
||||
#ifdef ESP8266
|
||||
#include <Hash.h>
|
||||
#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library
|
||||
#include <../src/Hash.h>
|
||||
#endif
|
||||
#include <Hash.h>
|
||||
#ifdef CRYPTO_HASH_h // include Hash.h from espressif framework if the first include was from the crypto library
|
||||
#include <../src/Hash.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef ESP32
|
||||
#define DEFAULT_MAX_WS_CLIENTS 8
|
||||
#else
|
||||
#define DEFAULT_MAX_WS_CLIENTS 4
|
||||
#ifndef DEFAULT_MAX_WS_CLIENTS
|
||||
#ifdef ESP32
|
||||
#define DEFAULT_MAX_WS_CLIENTS 8
|
||||
#else
|
||||
#define DEFAULT_MAX_WS_CLIENTS 4
|
||||
#endif
|
||||
#endif
|
||||
|
||||
using AsyncWebSocketSharedBuffer = std::shared_ptr<std::vector<uint8_t>>;
|
||||
|
||||
class AsyncWebSocket;
|
||||
class AsyncWebSocketResponse;
|
||||
class AsyncWebSocketClient;
|
||||
@ -75,94 +90,74 @@ typedef struct {
|
||||
uint64_t index;
|
||||
} AwsFrameInfo;
|
||||
|
||||
typedef enum { WS_DISCONNECTED, WS_CONNECTED, WS_DISCONNECTING } AwsClientStatus;
|
||||
typedef enum { WS_CONTINUATION, WS_TEXT, WS_BINARY, WS_DISCONNECT = 0x08, WS_PING, WS_PONG } AwsFrameType;
|
||||
typedef enum { WS_MSG_SENDING, WS_MSG_SENT, WS_MSG_ERROR } AwsMessageStatus;
|
||||
typedef enum { WS_EVT_CONNECT, WS_EVT_DISCONNECT, WS_EVT_PONG, WS_EVT_ERROR, WS_EVT_DATA } AwsEventType;
|
||||
typedef enum { WS_DISCONNECTED,
|
||||
WS_CONNECTED,
|
||||
WS_DISCONNECTING } AwsClientStatus;
|
||||
typedef enum { WS_CONTINUATION,
|
||||
WS_TEXT,
|
||||
WS_BINARY,
|
||||
WS_DISCONNECT = 0x08,
|
||||
WS_PING,
|
||||
WS_PONG } AwsFrameType;
|
||||
typedef enum { WS_MSG_SENDING,
|
||||
WS_MSG_SENT,
|
||||
WS_MSG_ERROR } AwsMessageStatus;
|
||||
typedef enum { WS_EVT_CONNECT,
|
||||
WS_EVT_DISCONNECT,
|
||||
WS_EVT_PING,
|
||||
WS_EVT_PONG,
|
||||
WS_EVT_ERROR,
|
||||
WS_EVT_DATA } AwsEventType;
|
||||
|
||||
class AsyncWebSocketMessageBuffer {
|
||||
friend AsyncWebSocket;
|
||||
friend AsyncWebSocketClient;
|
||||
|
||||
private:
|
||||
uint8_t * _data;
|
||||
size_t _len;
|
||||
bool _lock;
|
||||
uint32_t _count;
|
||||
AsyncWebSocketSharedBuffer _buffer;
|
||||
|
||||
public:
|
||||
AsyncWebSocketMessageBuffer();
|
||||
AsyncWebSocketMessageBuffer(size_t size);
|
||||
AsyncWebSocketMessageBuffer(uint8_t * data, size_t size);
|
||||
AsyncWebSocketMessageBuffer(const AsyncWebSocketMessageBuffer &);
|
||||
AsyncWebSocketMessageBuffer(AsyncWebSocketMessageBuffer &&);
|
||||
~AsyncWebSocketMessageBuffer();
|
||||
void operator ++(int i) { (void)i; _count++; }
|
||||
void operator --(int i) { (void)i; if (_count > 0) { _count--; } ; }
|
||||
AsyncWebSocketMessageBuffer() {}
|
||||
explicit AsyncWebSocketMessageBuffer(size_t size);
|
||||
AsyncWebSocketMessageBuffer(const uint8_t* data, size_t size);
|
||||
//~AsyncWebSocketMessageBuffer();
|
||||
bool reserve(size_t size);
|
||||
void lock() { _lock = true; }
|
||||
void unlock() { _lock = false; }
|
||||
uint8_t * get() { return _data; }
|
||||
size_t length() { return _len; }
|
||||
uint32_t count() { return _count; }
|
||||
bool canDelete() { return (!_count && !_lock); }
|
||||
|
||||
friend AsyncWebSocket;
|
||||
|
||||
uint8_t* get() { return _buffer->data(); }
|
||||
size_t length() const { return _buffer->size(); }
|
||||
};
|
||||
|
||||
class AsyncWebSocketMessage {
|
||||
protected:
|
||||
uint8_t _opcode;
|
||||
bool _mask;
|
||||
AwsMessageStatus _status;
|
||||
private:
|
||||
AsyncWebSocketSharedBuffer _WSbuffer;
|
||||
uint8_t _opcode{WS_TEXT};
|
||||
bool _mask{false};
|
||||
AwsMessageStatus _status{WS_MSG_ERROR};
|
||||
size_t _sent{};
|
||||
size_t _ack{};
|
||||
size_t _acked{};
|
||||
|
||||
public:
|
||||
AsyncWebSocketMessage():_opcode(WS_TEXT),_mask(false),_status(WS_MSG_ERROR){}
|
||||
virtual ~AsyncWebSocketMessage(){}
|
||||
virtual void ack(size_t len __attribute__((unused)), uint32_t time __attribute__((unused))){}
|
||||
virtual size_t send(AsyncClient *client __attribute__((unused))){ return 0; }
|
||||
virtual bool finished(){ return _status != WS_MSG_SENDING; }
|
||||
virtual bool betweenFrames() const { return false; }
|
||||
};
|
||||
AsyncWebSocketMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false);
|
||||
|
||||
class AsyncWebSocketBasicMessage: public AsyncWebSocketMessage {
|
||||
private:
|
||||
size_t _len;
|
||||
size_t _sent;
|
||||
size_t _ack;
|
||||
size_t _acked;
|
||||
uint8_t * _data;
|
||||
public:
|
||||
AsyncWebSocketBasicMessage(const char * data, size_t len, uint8_t opcode=WS_TEXT, bool mask=false);
|
||||
AsyncWebSocketBasicMessage(uint8_t opcode=WS_TEXT, bool mask=false);
|
||||
virtual ~AsyncWebSocketBasicMessage() override;
|
||||
virtual bool betweenFrames() const override { return _acked == _ack; }
|
||||
virtual void ack(size_t len, uint32_t time) override ;
|
||||
virtual size_t send(AsyncClient *client) override ;
|
||||
};
|
||||
bool finished() const { return _status != WS_MSG_SENDING; }
|
||||
bool betweenFrames() const { return _acked == _ack; }
|
||||
|
||||
class AsyncWebSocketMultiMessage: public AsyncWebSocketMessage {
|
||||
private:
|
||||
uint8_t * _data;
|
||||
size_t _len;
|
||||
size_t _sent;
|
||||
size_t _ack;
|
||||
size_t _acked;
|
||||
AsyncWebSocketMessageBuffer * _WSbuffer;
|
||||
public:
|
||||
AsyncWebSocketMultiMessage(AsyncWebSocketMessageBuffer * buffer, uint8_t opcode=WS_TEXT, bool mask=false);
|
||||
virtual ~AsyncWebSocketMultiMessage() override;
|
||||
virtual bool betweenFrames() const override { return _acked == _ack; }
|
||||
virtual void ack(size_t len, uint32_t time) override ;
|
||||
virtual size_t send(AsyncClient *client) override ;
|
||||
void ack(size_t len, uint32_t time);
|
||||
size_t send(AsyncClient* client);
|
||||
};
|
||||
|
||||
class AsyncWebSocketClient {
|
||||
private:
|
||||
AsyncClient *_client;
|
||||
AsyncWebSocket *_server;
|
||||
AsyncClient* _client;
|
||||
AsyncWebSocket* _server;
|
||||
uint32_t _clientId;
|
||||
AwsClientStatus _status;
|
||||
|
||||
LinkedList<AsyncWebSocketControl *> _controlQueue;
|
||||
LinkedList<AsyncWebSocketMessage *> _messageQueue;
|
||||
#ifdef ESP32
|
||||
mutable std::mutex _lock;
|
||||
#endif
|
||||
std::deque<AsyncWebSocketControl> _controlQueue;
|
||||
std::deque<AsyncWebSocketMessage> _messageQueue;
|
||||
bool closeWhenFull = true;
|
||||
|
||||
uint8_t _pstate;
|
||||
AwsFrameInfo _pinfo;
|
||||
@ -170,181 +165,213 @@ class AsyncWebSocketClient {
|
||||
uint32_t _lastMessageTime;
|
||||
uint32_t _keepAlivePeriod;
|
||||
|
||||
void _queueMessage(AsyncWebSocketMessage *dataMessage);
|
||||
void _queueControl(AsyncWebSocketControl *controlMessage);
|
||||
bool _queueControl(uint8_t opcode, const uint8_t* data = NULL, size_t len = 0, bool mask = false);
|
||||
bool _queueMessage(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false);
|
||||
void _runQueue();
|
||||
void _clearQueue();
|
||||
|
||||
public:
|
||||
void *_tempObject;
|
||||
void* _tempObject;
|
||||
|
||||
AsyncWebSocketClient(AsyncWebServerRequest *request, AsyncWebSocket *server);
|
||||
AsyncWebSocketClient(AsyncWebServerRequest* request, AsyncWebSocket* server);
|
||||
~AsyncWebSocketClient();
|
||||
|
||||
//client id increments for the given server
|
||||
uint32_t id(){ return _clientId; }
|
||||
AwsClientStatus status(){ return _status; }
|
||||
AsyncClient* client(){ return _client; }
|
||||
AsyncWebSocket *server(){ return _server; }
|
||||
AwsFrameInfo const &pinfo() const { return _pinfo; }
|
||||
// client id increments for the given server
|
||||
uint32_t id() const { return _clientId; }
|
||||
AwsClientStatus status() const { return _status; }
|
||||
AsyncClient* client() { return _client; }
|
||||
const AsyncClient* client() const { return _client; }
|
||||
AsyncWebSocket* server() { return _server; }
|
||||
const AsyncWebSocket* server() const { return _server; }
|
||||
AwsFrameInfo const& pinfo() const { return _pinfo; }
|
||||
|
||||
IPAddress remoteIP();
|
||||
uint16_t remotePort();
|
||||
// - If "true" (default), the connection will be closed if the message queue is full.
|
||||
// This is the default behavior in yubox-node-org, which is not silently discarding messages but instead closes the connection.
|
||||
// The big issue with this behavior is that is can cause the UI to automatically re-create a new WS connection, which can be filled again,
|
||||
// and so on, causing a resource exhaustion.
|
||||
//
|
||||
// - If "false", the incoming message will be discarded if the queue is full.
|
||||
// This is the default behavior in the original ESPAsyncWebServer library from me-no-dev.
|
||||
// This behavior allows the best performance at the expense of unreliable message delivery in case the queue is full (some messages may be lost).
|
||||
//
|
||||
// - In any case, when the queue is full, a message is logged.
|
||||
// - IT is recommended to use the methods queueIsFull(), availableForWriteAll(), availableForWrite(clientId) to check if the queue is full before sending a message.
|
||||
//
|
||||
// Usage:
|
||||
// - can be set in the onEvent listener when connecting (event type is: WS_EVT_CONNECT)
|
||||
//
|
||||
// Use cases:,
|
||||
// - if using websocket to send logging messages, maybe some loss is acceptable.
|
||||
// - But if using websocket to send UI update messages, maybe the connection should be closed and the UI redrawn.
|
||||
void setCloseClientOnQueueFull(bool close) { closeWhenFull = close; }
|
||||
bool willCloseClientOnQueueFull() const { return closeWhenFull; }
|
||||
|
||||
//control frames
|
||||
void close(uint16_t code=0, const char * message=NULL);
|
||||
void ping(uint8_t *data=NULL, size_t len=0);
|
||||
IPAddress remoteIP() const;
|
||||
uint16_t remotePort() const;
|
||||
|
||||
//set auto-ping period in seconds. disabled if zero (default)
|
||||
void keepAlivePeriod(uint16_t seconds){
|
||||
bool shouldBeDeleted() const { return !_client; }
|
||||
|
||||
// control frames
|
||||
void close(uint16_t code = 0, const char* message = NULL);
|
||||
bool ping(const uint8_t* data = NULL, size_t len = 0);
|
||||
|
||||
// set auto-ping period in seconds. disabled if zero (default)
|
||||
void keepAlivePeriod(uint16_t seconds) {
|
||||
_keepAlivePeriod = seconds * 1000;
|
||||
}
|
||||
uint16_t keepAlivePeriod(){
|
||||
uint16_t keepAlivePeriod() {
|
||||
return (uint16_t)(_keepAlivePeriod / 1000);
|
||||
}
|
||||
|
||||
//data packets
|
||||
void message(AsyncWebSocketMessage *message){ _queueMessage(message); }
|
||||
bool queueIsFull();
|
||||
// data packets
|
||||
void message(AsyncWebSocketSharedBuffer buffer, uint8_t opcode = WS_TEXT, bool mask = false) { _queueMessage(buffer, opcode, mask); }
|
||||
bool queueIsFull() const;
|
||||
size_t queueLen() const;
|
||||
|
||||
size_t printf(const char *format, ...) __attribute__ ((format (printf, 2, 3)));
|
||||
#ifndef ESP32
|
||||
size_t printf_P(PGM_P formatP, ...) __attribute__ ((format (printf, 2, 3)));
|
||||
#endif
|
||||
void text(const char * message, size_t len);
|
||||
void text(const char * message);
|
||||
void text(uint8_t * message, size_t len);
|
||||
void text(char * message);
|
||||
void text(const String &message);
|
||||
void text(const __FlashStringHelper *data);
|
||||
void text(AsyncWebSocketMessageBuffer *buffer);
|
||||
size_t printf(const char* format, ...) __attribute__((format(printf, 2, 3)));
|
||||
|
||||
void binary(const char * message, size_t len);
|
||||
void binary(const char * message);
|
||||
void binary(uint8_t * message, size_t len);
|
||||
void binary(char * message);
|
||||
void binary(const String &message);
|
||||
void binary(const __FlashStringHelper *data, size_t len);
|
||||
void binary(AsyncWebSocketMessageBuffer *buffer);
|
||||
bool text(AsyncWebSocketSharedBuffer buffer);
|
||||
bool text(const uint8_t* message, size_t len);
|
||||
bool text(const char* message, size_t len);
|
||||
bool text(const char* message);
|
||||
bool text(const String& message);
|
||||
bool text(AsyncWebSocketMessageBuffer* buffer);
|
||||
|
||||
bool canSend() { return _messageQueue.length() < WS_MAX_QUEUED_MESSAGES; }
|
||||
bool binary(AsyncWebSocketSharedBuffer buffer);
|
||||
bool binary(const uint8_t* message, size_t len);
|
||||
bool binary(const char* message, size_t len);
|
||||
bool binary(const char* message);
|
||||
bool binary(const String& message);
|
||||
bool binary(AsyncWebSocketMessageBuffer* buffer);
|
||||
|
||||
//system callbacks (do not call)
|
||||
bool canSend() const;
|
||||
|
||||
// system callbacks (do not call)
|
||||
void _onAck(size_t len, uint32_t time);
|
||||
void _onError(int8_t);
|
||||
void _onPoll();
|
||||
void _onTimeout(uint32_t time);
|
||||
void _onDisconnect();
|
||||
void _onData(void *pbuf, size_t plen);
|
||||
void _onData(void* pbuf, size_t plen);
|
||||
|
||||
#ifdef ESP8266
|
||||
size_t printf_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3)));
|
||||
bool text(const __FlashStringHelper* message);
|
||||
bool binary(const __FlashStringHelper* message, size_t len);
|
||||
#endif
|
||||
};
|
||||
|
||||
typedef std::function<void(AsyncWebSocket * server, AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len)> AwsEventHandler;
|
||||
using AwsHandshakeHandler = std::function<bool(AsyncWebServerRequest* request)>;
|
||||
using AwsEventHandler = std::function<void(AsyncWebSocket* server, AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len)>;
|
||||
|
||||
//WebServer Handler implementation that plays the role of a socket server
|
||||
class AsyncWebSocket: public AsyncWebHandler {
|
||||
public:
|
||||
typedef LinkedList<AsyncWebSocketClient *> AsyncWebSocketClientLinkedList;
|
||||
// WebServer Handler implementation that plays the role of a socket server
|
||||
class AsyncWebSocket : public AsyncWebHandler {
|
||||
private:
|
||||
String _url;
|
||||
AsyncWebSocketClientLinkedList _clients;
|
||||
std::list<AsyncWebSocketClient> _clients;
|
||||
uint32_t _cNextId;
|
||||
AwsEventHandler _eventHandler;
|
||||
AwsEventHandler _eventHandler{nullptr};
|
||||
AwsHandshakeHandler _handshakeHandler;
|
||||
bool _enabled;
|
||||
AsyncWebLock _lock;
|
||||
#ifdef ESP32
|
||||
mutable std::mutex _lock;
|
||||
#endif
|
||||
|
||||
public:
|
||||
AsyncWebSocket(const String& url);
|
||||
~AsyncWebSocket();
|
||||
const char * url() const { return _url.c_str(); }
|
||||
void enable(bool e){ _enabled = e; }
|
||||
typedef enum {
|
||||
DISCARDED = 0,
|
||||
ENQUEUED = 1,
|
||||
PARTIALLY_ENQUEUED = 2,
|
||||
} SendStatus;
|
||||
|
||||
explicit AsyncWebSocket(const char* url) : _url(url), _cNextId(1), _enabled(true) {}
|
||||
AsyncWebSocket(const String& url) : _url(url), _cNextId(1), _enabled(true) {}
|
||||
~AsyncWebSocket() {};
|
||||
const char* url() const { return _url.c_str(); }
|
||||
void enable(bool e) { _enabled = e; }
|
||||
bool enabled() const { return _enabled; }
|
||||
bool availableForWriteAll();
|
||||
bool availableForWrite(uint32_t id);
|
||||
|
||||
size_t count() const;
|
||||
AsyncWebSocketClient * client(uint32_t id);
|
||||
bool hasClient(uint32_t id){ return client(id) != NULL; }
|
||||
AsyncWebSocketClient* client(uint32_t id);
|
||||
bool hasClient(uint32_t id) { return client(id) != nullptr; }
|
||||
|
||||
void close(uint32_t id, uint16_t code=0, const char * message=NULL);
|
||||
void closeAll(uint16_t code=0, const char * message=NULL);
|
||||
void close(uint32_t id, uint16_t code = 0, const char* message = NULL);
|
||||
void closeAll(uint16_t code = 0, const char* message = NULL);
|
||||
void cleanupClients(uint16_t maxClients = DEFAULT_MAX_WS_CLIENTS);
|
||||
|
||||
void ping(uint32_t id, uint8_t *data=NULL, size_t len=0);
|
||||
void pingAll(uint8_t *data=NULL, size_t len=0); // done
|
||||
bool ping(uint32_t id, const uint8_t* data = NULL, size_t len = 0);
|
||||
SendStatus pingAll(const uint8_t* data = NULL, size_t len = 0); // done
|
||||
|
||||
void text(uint32_t id, const char * message, size_t len);
|
||||
void text(uint32_t id, const char * message);
|
||||
void text(uint32_t id, uint8_t * message, size_t len);
|
||||
void text(uint32_t id, char * message);
|
||||
void text(uint32_t id, const String &message);
|
||||
void text(uint32_t id, const __FlashStringHelper *message);
|
||||
bool text(uint32_t id, const uint8_t* message, size_t len);
|
||||
bool text(uint32_t id, const char* message, size_t len);
|
||||
bool text(uint32_t id, const char* message);
|
||||
bool text(uint32_t id, const String& message);
|
||||
bool text(uint32_t id, AsyncWebSocketMessageBuffer* buffer);
|
||||
bool text(uint32_t id, AsyncWebSocketSharedBuffer buffer);
|
||||
|
||||
void textAll(const char * message, size_t len);
|
||||
void textAll(const char * message);
|
||||
void textAll(uint8_t * message, size_t len);
|
||||
void textAll(char * message);
|
||||
void textAll(const String &message);
|
||||
void textAll(const __FlashStringHelper *message); // need to convert
|
||||
void textAll(AsyncWebSocketMessageBuffer * buffer);
|
||||
SendStatus textAll(const uint8_t* message, size_t len);
|
||||
SendStatus textAll(const char* message, size_t len);
|
||||
SendStatus textAll(const char* message);
|
||||
SendStatus textAll(const String& message);
|
||||
SendStatus textAll(AsyncWebSocketMessageBuffer* buffer);
|
||||
SendStatus textAll(AsyncWebSocketSharedBuffer buffer);
|
||||
|
||||
void binary(uint32_t id, const char * message, size_t len);
|
||||
void binary(uint32_t id, const char * message);
|
||||
void binary(uint32_t id, uint8_t * message, size_t len);
|
||||
void binary(uint32_t id, char * message);
|
||||
void binary(uint32_t id, const String &message);
|
||||
void binary(uint32_t id, const __FlashStringHelper *message, size_t len);
|
||||
bool binary(uint32_t id, const uint8_t* message, size_t len);
|
||||
bool binary(uint32_t id, const char* message, size_t len);
|
||||
bool binary(uint32_t id, const char* message);
|
||||
bool binary(uint32_t id, const String& message);
|
||||
bool binary(uint32_t id, AsyncWebSocketMessageBuffer* buffer);
|
||||
bool binary(uint32_t id, AsyncWebSocketSharedBuffer buffer);
|
||||
|
||||
void binaryAll(const char * message, size_t len);
|
||||
void binaryAll(const char * message);
|
||||
void binaryAll(uint8_t * message, size_t len);
|
||||
void binaryAll(char * message);
|
||||
void binaryAll(const String &message);
|
||||
void binaryAll(const __FlashStringHelper *message, size_t len);
|
||||
void binaryAll(AsyncWebSocketMessageBuffer * buffer);
|
||||
SendStatus binaryAll(const uint8_t* message, size_t len);
|
||||
SendStatus binaryAll(const char* message, size_t len);
|
||||
SendStatus binaryAll(const char* message);
|
||||
SendStatus binaryAll(const String& message);
|
||||
SendStatus binaryAll(AsyncWebSocketMessageBuffer* buffer);
|
||||
SendStatus binaryAll(AsyncWebSocketSharedBuffer buffer);
|
||||
|
||||
void message(uint32_t id, AsyncWebSocketMessage *message);
|
||||
void messageAll(AsyncWebSocketMultiMessage *message);
|
||||
size_t printf(uint32_t id, const char* format, ...) __attribute__((format(printf, 3, 4)));
|
||||
size_t printfAll(const char* format, ...) __attribute__((format(printf, 2, 3)));
|
||||
|
||||
size_t printf(uint32_t id, const char *format, ...) __attribute__ ((format (printf, 3, 4)));
|
||||
size_t printfAll(const char *format, ...) __attribute__ ((format (printf, 2, 3)));
|
||||
#ifndef ESP32
|
||||
size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__ ((format (printf, 3, 4)));
|
||||
#ifdef ESP8266
|
||||
bool text(uint32_t id, const __FlashStringHelper* message);
|
||||
SendStatus textAll(const __FlashStringHelper* message);
|
||||
bool binary(uint32_t id, const __FlashStringHelper* message, size_t len);
|
||||
SendStatus binaryAll(const __FlashStringHelper* message, size_t len);
|
||||
size_t printf_P(uint32_t id, PGM_P formatP, ...) __attribute__((format(printf, 3, 4)));
|
||||
size_t printfAll_P(PGM_P formatP, ...) __attribute__((format(printf, 2, 3)));
|
||||
#endif
|
||||
size_t printfAll_P(PGM_P formatP, ...) __attribute__ ((format (printf, 2, 3)));
|
||||
|
||||
//event listener
|
||||
void onEvent(AwsEventHandler handler){
|
||||
_eventHandler = handler;
|
||||
}
|
||||
void onEvent(AwsEventHandler handler) { _eventHandler = handler; }
|
||||
void handleHandshake(AwsHandshakeHandler handler) { _handshakeHandler = handler; }
|
||||
|
||||
//system callbacks (do not call)
|
||||
uint32_t _getNextId(){ return _cNextId++; }
|
||||
void _addClient(AsyncWebSocketClient * client);
|
||||
void _handleDisconnect(AsyncWebSocketClient * client);
|
||||
void _handleEvent(AsyncWebSocketClient * client, AwsEventType type, void * arg, uint8_t *data, size_t len);
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final;
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final;
|
||||
// system callbacks (do not call)
|
||||
uint32_t _getNextId() { return _cNextId++; }
|
||||
AsyncWebSocketClient* _newClient(AsyncWebServerRequest* request);
|
||||
void _handleEvent(AsyncWebSocketClient* client, AwsEventType type, void* arg, uint8_t* data, size_t len);
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
|
||||
// messagebuffer functions/objects.
|
||||
AsyncWebSocketMessageBuffer* makeBuffer(size_t size = 0);
|
||||
AsyncWebSocketMessageBuffer* makeBuffer(const uint8_t* data, size_t size);
|
||||
|
||||
// messagebuffer functions/objects.
|
||||
AsyncWebSocketMessageBuffer * makeBuffer(size_t size = 0);
|
||||
AsyncWebSocketMessageBuffer * makeBuffer(uint8_t * data, size_t size);
|
||||
LinkedList<AsyncWebSocketMessageBuffer *> _buffers;
|
||||
void _cleanBuffers();
|
||||
|
||||
AsyncWebSocketClientLinkedList getClients() const;
|
||||
std::list<AsyncWebSocketClient>& getClients() { return _clients; }
|
||||
};
|
||||
|
||||
//WebServer response to authenticate the socket and detach the tcp client from the web server request
|
||||
class AsyncWebSocketResponse: public AsyncWebServerResponse {
|
||||
// WebServer response to authenticate the socket and detach the tcp client from the web server request
|
||||
class AsyncWebSocketResponse : public AsyncWebServerResponse {
|
||||
private:
|
||||
String _content;
|
||||
AsyncWebSocket *_server;
|
||||
AsyncWebSocket* _server;
|
||||
|
||||
public:
|
||||
AsyncWebSocketResponse(const String& key, AsyncWebSocket *server);
|
||||
void _respond(AsyncWebServerRequest *request);
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time);
|
||||
AsyncWebSocketResponse(const String& key, AsyncWebSocket* server);
|
||||
void _respond(AsyncWebServerRequest* request);
|
||||
size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time);
|
||||
bool _sourceValid() const { return true; }
|
||||
};
|
||||
|
||||
|
||||
#endif /* ASYNCWEBSOCKET_H_ */
|
||||
|
@ -1,87 +0,0 @@
|
||||
#ifndef ASYNCWEBSYNCHRONIZATION_H_
|
||||
#define ASYNCWEBSYNCHRONIZATION_H_
|
||||
|
||||
// Synchronisation is only available on ESP32, as the ESP8266 isn't using FreeRTOS by default
|
||||
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
#ifdef ESP32
|
||||
|
||||
// This is the ESP32 version of the Sync Lock, using the FreeRTOS Semaphore
|
||||
class AsyncWebLock
|
||||
{
|
||||
private:
|
||||
SemaphoreHandle_t _lock;
|
||||
mutable void *_lockedBy;
|
||||
|
||||
public:
|
||||
AsyncWebLock() {
|
||||
_lock = xSemaphoreCreateBinary();
|
||||
_lockedBy = NULL;
|
||||
xSemaphoreGive(_lock);
|
||||
}
|
||||
|
||||
~AsyncWebLock() {
|
||||
vSemaphoreDelete(_lock);
|
||||
}
|
||||
|
||||
bool lock() const {
|
||||
extern void *pxCurrentTCB;
|
||||
if (_lockedBy != pxCurrentTCB) {
|
||||
xSemaphoreTake(_lock, portMAX_DELAY);
|
||||
_lockedBy = pxCurrentTCB;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void unlock() const {
|
||||
_lockedBy = NULL;
|
||||
xSemaphoreGive(_lock);
|
||||
}
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
// This is the 8266 version of the Sync Lock which is currently unimplemented
|
||||
class AsyncWebLock
|
||||
{
|
||||
|
||||
public:
|
||||
AsyncWebLock() {
|
||||
}
|
||||
|
||||
~AsyncWebLock() {
|
||||
}
|
||||
|
||||
bool lock() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
void unlock() const {
|
||||
}
|
||||
};
|
||||
#endif
|
||||
|
||||
class AsyncWebLockGuard
|
||||
{
|
||||
private:
|
||||
const AsyncWebLock *_lock;
|
||||
|
||||
public:
|
||||
AsyncWebLockGuard(const AsyncWebLock &l) {
|
||||
if (l.lock()) {
|
||||
_lock = &l;
|
||||
} else {
|
||||
_lock = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
~AsyncWebLockGuard() {
|
||||
if (_lock) {
|
||||
_lock->unlock();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
#endif // ASYNCWEBSYNCHRONIZATION_H_
|
284
src/BackPort_SHA1Builder.cpp
Normal file
284
src/BackPort_SHA1Builder.cpp
Normal file
@ -0,0 +1,284 @@
|
||||
/*
|
||||
* FIPS-180-1 compliant SHA-1 implementation
|
||||
*
|
||||
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||
* not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* This file is part of mbed TLS (https://tls.mbed.org)
|
||||
* Modified for esp32 by Lucas Saavedra Vaz on 11 Jan 2024
|
||||
*/
|
||||
|
||||
#include <Arduino.h>
|
||||
#if ESP_IDF_VERSION_MAJOR < 5
|
||||
|
||||
#include "BackPort_SHA1Builder.h"
|
||||
|
||||
// 32-bit integer manipulation macros (big endian)
|
||||
|
||||
#ifndef GET_UINT32_BE
|
||||
#define GET_UINT32_BE(n, b, i) \
|
||||
{ (n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | ((uint32_t)(b)[(i) + 2] << 8) | ((uint32_t)(b)[(i) + 3]); }
|
||||
#endif
|
||||
|
||||
#ifndef PUT_UINT32_BE
|
||||
#define PUT_UINT32_BE(n, b, i) \
|
||||
{ \
|
||||
(b)[(i)] = (uint8_t)((n) >> 24); \
|
||||
(b)[(i) + 1] = (uint8_t)((n) >> 16); \
|
||||
(b)[(i) + 2] = (uint8_t)((n) >> 8); \
|
||||
(b)[(i) + 3] = (uint8_t)((n)); \
|
||||
}
|
||||
#endif
|
||||
|
||||
// Constants
|
||||
|
||||
static const uint8_t sha1_padding[64] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
|
||||
|
||||
// Private methods
|
||||
|
||||
void SHA1Builder::process(const uint8_t *data) {
|
||||
uint32_t temp, W[16], A, B, C, D, E;
|
||||
|
||||
GET_UINT32_BE(W[0], data, 0);
|
||||
GET_UINT32_BE(W[1], data, 4);
|
||||
GET_UINT32_BE(W[2], data, 8);
|
||||
GET_UINT32_BE(W[3], data, 12);
|
||||
GET_UINT32_BE(W[4], data, 16);
|
||||
GET_UINT32_BE(W[5], data, 20);
|
||||
GET_UINT32_BE(W[6], data, 24);
|
||||
GET_UINT32_BE(W[7], data, 28);
|
||||
GET_UINT32_BE(W[8], data, 32);
|
||||
GET_UINT32_BE(W[9], data, 36);
|
||||
GET_UINT32_BE(W[10], data, 40);
|
||||
GET_UINT32_BE(W[11], data, 44);
|
||||
GET_UINT32_BE(W[12], data, 48);
|
||||
GET_UINT32_BE(W[13], data, 52);
|
||||
GET_UINT32_BE(W[14], data, 56);
|
||||
GET_UINT32_BE(W[15], data, 60);
|
||||
|
||||
#define sha1_S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
|
||||
|
||||
#define sha1_R(t) (temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ W[t & 0x0F], (W[t & 0x0F] = sha1_S(temp, 1)))
|
||||
|
||||
#define sha1_P(a, b, c, d, e, x) \
|
||||
{ \
|
||||
e += sha1_S(a, 5) + sha1_F(b, c, d) + sha1_K + x; \
|
||||
b = sha1_S(b, 30); \
|
||||
}
|
||||
|
||||
A = state[0];
|
||||
B = state[1];
|
||||
C = state[2];
|
||||
D = state[3];
|
||||
E = state[4];
|
||||
|
||||
#define sha1_F(x, y, z) (z ^ (x & (y ^ z)))
|
||||
#define sha1_K 0x5A827999
|
||||
|
||||
sha1_P(A, B, C, D, E, W[0]);
|
||||
sha1_P(E, A, B, C, D, W[1]);
|
||||
sha1_P(D, E, A, B, C, W[2]);
|
||||
sha1_P(C, D, E, A, B, W[3]);
|
||||
sha1_P(B, C, D, E, A, W[4]);
|
||||
sha1_P(A, B, C, D, E, W[5]);
|
||||
sha1_P(E, A, B, C, D, W[6]);
|
||||
sha1_P(D, E, A, B, C, W[7]);
|
||||
sha1_P(C, D, E, A, B, W[8]);
|
||||
sha1_P(B, C, D, E, A, W[9]);
|
||||
sha1_P(A, B, C, D, E, W[10]);
|
||||
sha1_P(E, A, B, C, D, W[11]);
|
||||
sha1_P(D, E, A, B, C, W[12]);
|
||||
sha1_P(C, D, E, A, B, W[13]);
|
||||
sha1_P(B, C, D, E, A, W[14]);
|
||||
sha1_P(A, B, C, D, E, W[15]);
|
||||
sha1_P(E, A, B, C, D, sha1_R(16));
|
||||
sha1_P(D, E, A, B, C, sha1_R(17));
|
||||
sha1_P(C, D, E, A, B, sha1_R(18));
|
||||
sha1_P(B, C, D, E, A, sha1_R(19));
|
||||
|
||||
#undef sha1_K
|
||||
#undef sha1_F
|
||||
|
||||
#define sha1_F(x, y, z) (x ^ y ^ z)
|
||||
#define sha1_K 0x6ED9EBA1
|
||||
|
||||
sha1_P(A, B, C, D, E, sha1_R(20));
|
||||
sha1_P(E, A, B, C, D, sha1_R(21));
|
||||
sha1_P(D, E, A, B, C, sha1_R(22));
|
||||
sha1_P(C, D, E, A, B, sha1_R(23));
|
||||
sha1_P(B, C, D, E, A, sha1_R(24));
|
||||
sha1_P(A, B, C, D, E, sha1_R(25));
|
||||
sha1_P(E, A, B, C, D, sha1_R(26));
|
||||
sha1_P(D, E, A, B, C, sha1_R(27));
|
||||
sha1_P(C, D, E, A, B, sha1_R(28));
|
||||
sha1_P(B, C, D, E, A, sha1_R(29));
|
||||
sha1_P(A, B, C, D, E, sha1_R(30));
|
||||
sha1_P(E, A, B, C, D, sha1_R(31));
|
||||
sha1_P(D, E, A, B, C, sha1_R(32));
|
||||
sha1_P(C, D, E, A, B, sha1_R(33));
|
||||
sha1_P(B, C, D, E, A, sha1_R(34));
|
||||
sha1_P(A, B, C, D, E, sha1_R(35));
|
||||
sha1_P(E, A, B, C, D, sha1_R(36));
|
||||
sha1_P(D, E, A, B, C, sha1_R(37));
|
||||
sha1_P(C, D, E, A, B, sha1_R(38));
|
||||
sha1_P(B, C, D, E, A, sha1_R(39));
|
||||
|
||||
#undef sha1_K
|
||||
#undef sha1_F
|
||||
|
||||
#define sha1_F(x, y, z) ((x & y) | (z & (x | y)))
|
||||
#define sha1_K 0x8F1BBCDC
|
||||
|
||||
sha1_P(A, B, C, D, E, sha1_R(40));
|
||||
sha1_P(E, A, B, C, D, sha1_R(41));
|
||||
sha1_P(D, E, A, B, C, sha1_R(42));
|
||||
sha1_P(C, D, E, A, B, sha1_R(43));
|
||||
sha1_P(B, C, D, E, A, sha1_R(44));
|
||||
sha1_P(A, B, C, D, E, sha1_R(45));
|
||||
sha1_P(E, A, B, C, D, sha1_R(46));
|
||||
sha1_P(D, E, A, B, C, sha1_R(47));
|
||||
sha1_P(C, D, E, A, B, sha1_R(48));
|
||||
sha1_P(B, C, D, E, A, sha1_R(49));
|
||||
sha1_P(A, B, C, D, E, sha1_R(50));
|
||||
sha1_P(E, A, B, C, D, sha1_R(51));
|
||||
sha1_P(D, E, A, B, C, sha1_R(52));
|
||||
sha1_P(C, D, E, A, B, sha1_R(53));
|
||||
sha1_P(B, C, D, E, A, sha1_R(54));
|
||||
sha1_P(A, B, C, D, E, sha1_R(55));
|
||||
sha1_P(E, A, B, C, D, sha1_R(56));
|
||||
sha1_P(D, E, A, B, C, sha1_R(57));
|
||||
sha1_P(C, D, E, A, B, sha1_R(58));
|
||||
sha1_P(B, C, D, E, A, sha1_R(59));
|
||||
|
||||
#undef sha1_K
|
||||
#undef sha1_F
|
||||
|
||||
#define sha1_F(x, y, z) (x ^ y ^ z)
|
||||
#define sha1_K 0xCA62C1D6
|
||||
|
||||
sha1_P(A, B, C, D, E, sha1_R(60));
|
||||
sha1_P(E, A, B, C, D, sha1_R(61));
|
||||
sha1_P(D, E, A, B, C, sha1_R(62));
|
||||
sha1_P(C, D, E, A, B, sha1_R(63));
|
||||
sha1_P(B, C, D, E, A, sha1_R(64));
|
||||
sha1_P(A, B, C, D, E, sha1_R(65));
|
||||
sha1_P(E, A, B, C, D, sha1_R(66));
|
||||
sha1_P(D, E, A, B, C, sha1_R(67));
|
||||
sha1_P(C, D, E, A, B, sha1_R(68));
|
||||
sha1_P(B, C, D, E, A, sha1_R(69));
|
||||
sha1_P(A, B, C, D, E, sha1_R(70));
|
||||
sha1_P(E, A, B, C, D, sha1_R(71));
|
||||
sha1_P(D, E, A, B, C, sha1_R(72));
|
||||
sha1_P(C, D, E, A, B, sha1_R(73));
|
||||
sha1_P(B, C, D, E, A, sha1_R(74));
|
||||
sha1_P(A, B, C, D, E, sha1_R(75));
|
||||
sha1_P(E, A, B, C, D, sha1_R(76));
|
||||
sha1_P(D, E, A, B, C, sha1_R(77));
|
||||
sha1_P(C, D, E, A, B, sha1_R(78));
|
||||
sha1_P(B, C, D, E, A, sha1_R(79));
|
||||
|
||||
#undef sha1_K
|
||||
#undef sha1_F
|
||||
|
||||
state[0] += A;
|
||||
state[1] += B;
|
||||
state[2] += C;
|
||||
state[3] += D;
|
||||
state[4] += E;
|
||||
}
|
||||
|
||||
// Public methods
|
||||
|
||||
void SHA1Builder::begin() {
|
||||
total[0] = 0;
|
||||
total[1] = 0;
|
||||
|
||||
state[0] = 0x67452301;
|
||||
state[1] = 0xEFCDAB89;
|
||||
state[2] = 0x98BADCFE;
|
||||
state[3] = 0x10325476;
|
||||
state[4] = 0xC3D2E1F0;
|
||||
|
||||
memset(buffer, 0x00, sizeof(buffer));
|
||||
memset(hash, 0x00, sizeof(hash));
|
||||
}
|
||||
|
||||
void SHA1Builder::add(const uint8_t *data, size_t len) {
|
||||
size_t fill;
|
||||
uint32_t left;
|
||||
|
||||
if (len == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
left = total[0] & 0x3F;
|
||||
fill = 64 - left;
|
||||
|
||||
total[0] += (uint32_t)len;
|
||||
total[0] &= 0xFFFFFFFF;
|
||||
|
||||
if (total[0] < (uint32_t)len) {
|
||||
total[1]++;
|
||||
}
|
||||
|
||||
if (left && len >= fill) {
|
||||
memcpy((void *)(buffer + left), data, fill);
|
||||
process(buffer);
|
||||
data += fill;
|
||||
len -= fill;
|
||||
left = 0;
|
||||
}
|
||||
|
||||
while (len >= 64) {
|
||||
process(data);
|
||||
data += 64;
|
||||
len -= 64;
|
||||
}
|
||||
|
||||
if (len > 0) {
|
||||
memcpy((void *)(buffer + left), data, len);
|
||||
}
|
||||
}
|
||||
|
||||
void SHA1Builder::calculate(void) {
|
||||
uint32_t last, padn;
|
||||
uint32_t high, low;
|
||||
uint8_t msglen[8];
|
||||
|
||||
high = (total[0] >> 29) | (total[1] << 3);
|
||||
low = (total[0] << 3);
|
||||
|
||||
PUT_UINT32_BE(high, msglen, 0);
|
||||
PUT_UINT32_BE(low, msglen, 4);
|
||||
|
||||
last = total[0] & 0x3F;
|
||||
padn = (last < 56) ? (56 - last) : (120 - last);
|
||||
|
||||
add((uint8_t *)sha1_padding, padn);
|
||||
add(msglen, 8);
|
||||
|
||||
PUT_UINT32_BE(state[0], hash, 0);
|
||||
PUT_UINT32_BE(state[1], hash, 4);
|
||||
PUT_UINT32_BE(state[2], hash, 8);
|
||||
PUT_UINT32_BE(state[3], hash, 12);
|
||||
PUT_UINT32_BE(state[4], hash, 16);
|
||||
}
|
||||
|
||||
void SHA1Builder::getBytes(uint8_t *output) {
|
||||
memcpy(output, hash, SHA1_HASH_SIZE);
|
||||
}
|
||||
|
||||
#endif // ESP_IDF_VERSION_MAJOR < 5
|
44
src/BackPort_SHA1Builder.h
Normal file
44
src/BackPort_SHA1Builder.h
Normal file
@ -0,0 +1,44 @@
|
||||
// Copyright 2024 Espressif Systems (Shanghai) PTE LTD
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#include <Arduino.h>
|
||||
#if ESP_IDF_VERSION_MAJOR < 5
|
||||
|
||||
#ifndef SHA1Builder_h
|
||||
#define SHA1Builder_h
|
||||
|
||||
#include <Stream.h>
|
||||
#include <WString.h>
|
||||
|
||||
#define SHA1_HASH_SIZE 20
|
||||
|
||||
class SHA1Builder {
|
||||
private:
|
||||
uint32_t total[2]; /* number of bytes processed */
|
||||
uint32_t state[5]; /* intermediate digest state */
|
||||
unsigned char buffer[64]; /* data block being processed */
|
||||
uint8_t hash[SHA1_HASH_SIZE]; /* SHA-1 result */
|
||||
|
||||
void process(const uint8_t* data);
|
||||
|
||||
public:
|
||||
void begin();
|
||||
void add(const uint8_t* data, size_t len);
|
||||
void calculate();
|
||||
void getBytes(uint8_t* output);
|
||||
};
|
||||
|
||||
#endif // SHA1Builder_h
|
||||
|
||||
#endif // ESP_IDF_VERSION_MAJOR < 5
|
16
src/ChunkPrint.cpp
Normal file
16
src/ChunkPrint.cpp
Normal file
@ -0,0 +1,16 @@
|
||||
#include <ChunkPrint.h>
|
||||
|
||||
ChunkPrint::ChunkPrint(uint8_t* destination, size_t from, size_t len)
|
||||
: _destination(destination), _to_skip(from), _to_write(len), _pos{0} {}
|
||||
|
||||
size_t ChunkPrint::write(uint8_t c) {
|
||||
if (_to_skip > 0) {
|
||||
_to_skip--;
|
||||
return 1;
|
||||
} else if (_to_write > 0) {
|
||||
_to_write--;
|
||||
_destination[_pos++] = c;
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
18
src/ChunkPrint.h
Normal file
18
src/ChunkPrint.h
Normal file
@ -0,0 +1,18 @@
|
||||
#ifndef CHUNKPRINT_H
|
||||
#define CHUNKPRINT_H
|
||||
|
||||
#include <Print.h>
|
||||
|
||||
class ChunkPrint : public Print {
|
||||
private:
|
||||
uint8_t* _destination;
|
||||
size_t _to_skip;
|
||||
size_t _to_write;
|
||||
size_t _pos;
|
||||
|
||||
public:
|
||||
ChunkPrint(uint8_t* destination, size_t from, size_t len);
|
||||
size_t write(uint8_t c);
|
||||
size_t write(const uint8_t* buffer, size_t size) { return this->Print::write(buffer, size); }
|
||||
};
|
||||
#endif
|
File diff suppressed because it is too large
Load Diff
256
src/Middleware.cpp
Normal file
256
src/Middleware.cpp
Normal file
@ -0,0 +1,256 @@
|
||||
#include "WebAuthentication.h"
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
AsyncMiddlewareChain::~AsyncMiddlewareChain() {
|
||||
for (AsyncMiddleware* m : _middlewares)
|
||||
if (m->_freeOnRemoval)
|
||||
delete m;
|
||||
}
|
||||
|
||||
void AsyncMiddlewareChain::addMiddleware(ArMiddlewareCallback fn) {
|
||||
AsyncMiddlewareFunction* m = new AsyncMiddlewareFunction(fn);
|
||||
m->_freeOnRemoval = true;
|
||||
_middlewares.emplace_back(m);
|
||||
}
|
||||
|
||||
void AsyncMiddlewareChain::addMiddleware(AsyncMiddleware* middleware) {
|
||||
if (middleware)
|
||||
_middlewares.emplace_back(middleware);
|
||||
}
|
||||
|
||||
void AsyncMiddlewareChain::addMiddlewares(std::vector<AsyncMiddleware*> middlewares) {
|
||||
for (AsyncMiddleware* m : middlewares)
|
||||
addMiddleware(m);
|
||||
}
|
||||
|
||||
bool AsyncMiddlewareChain::removeMiddleware(AsyncMiddleware* middleware) {
|
||||
// remove all middlewares from _middlewares vector being equal to middleware, delete them having _freeOnRemoval flag to true and resize the vector.
|
||||
const size_t size = _middlewares.size();
|
||||
_middlewares.erase(std::remove_if(_middlewares.begin(), _middlewares.end(), [middleware](AsyncMiddleware* m) {
|
||||
if (m == middleware) {
|
||||
if (m->_freeOnRemoval)
|
||||
delete m;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}),
|
||||
_middlewares.end());
|
||||
return size != _middlewares.size();
|
||||
}
|
||||
|
||||
void AsyncMiddlewareChain::_runChain(AsyncWebServerRequest* request, ArMiddlewareNext finalizer) {
|
||||
if (!_middlewares.size())
|
||||
return finalizer();
|
||||
ArMiddlewareNext next;
|
||||
std::list<AsyncMiddleware*>::iterator it = _middlewares.begin();
|
||||
next = [this, &next, &it, request, finalizer]() {
|
||||
if (it == _middlewares.end())
|
||||
return finalizer();
|
||||
AsyncMiddleware* m = *it;
|
||||
it++;
|
||||
return m->run(request, next);
|
||||
};
|
||||
return next();
|
||||
}
|
||||
|
||||
void AsyncAuthenticationMiddleware::setUsername(const char* username) {
|
||||
_username = username;
|
||||
_hasCreds = _username.length() && _credentials.length();
|
||||
}
|
||||
|
||||
void AsyncAuthenticationMiddleware::setPassword(const char* password) {
|
||||
_credentials = password;
|
||||
_hash = false;
|
||||
_hasCreds = _username.length() && _credentials.length();
|
||||
}
|
||||
|
||||
void AsyncAuthenticationMiddleware::setPasswordHash(const char* hash) {
|
||||
_credentials = hash;
|
||||
_hash = _credentials.length();
|
||||
_hasCreds = _username.length() && _credentials.length();
|
||||
}
|
||||
|
||||
bool AsyncAuthenticationMiddleware::generateHash() {
|
||||
// ensure we have all the necessary data
|
||||
if (!_hasCreds)
|
||||
return false;
|
||||
|
||||
// if we already have a hash, do nothing
|
||||
if (_hash)
|
||||
return false;
|
||||
|
||||
switch (_authMethod) {
|
||||
case AsyncAuthType::AUTH_DIGEST:
|
||||
_credentials = generateDigestHash(_username.c_str(), _credentials.c_str(), _realm.c_str());
|
||||
_hash = true;
|
||||
return true;
|
||||
|
||||
case AsyncAuthType::AUTH_BASIC:
|
||||
_credentials = generateBasicHash(_username.c_str(), _credentials.c_str());
|
||||
_hash = true;
|
||||
return true;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool AsyncAuthenticationMiddleware::allowed(AsyncWebServerRequest* request) const {
|
||||
if (_authMethod == AsyncAuthType::AUTH_NONE)
|
||||
return true;
|
||||
|
||||
if (_authMethod == AsyncAuthType::AUTH_DENIED)
|
||||
return false;
|
||||
|
||||
if (!_hasCreds)
|
||||
return true;
|
||||
|
||||
return request->authenticate(_username.c_str(), _credentials.c_str(), _realm.c_str(), _hash);
|
||||
}
|
||||
|
||||
void AsyncAuthenticationMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
return allowed(request) ? next() : request->requestAuthentication(_authMethod, _realm.c_str(), _authFailMsg.c_str());
|
||||
}
|
||||
|
||||
void AsyncHeaderFreeMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
std::vector<const char*> reqHeaders;
|
||||
request->getHeaderNames(reqHeaders);
|
||||
for (const char* h : reqHeaders) {
|
||||
bool keep = false;
|
||||
for (const char* k : _toKeep) {
|
||||
if (strcasecmp(h, k) == 0) {
|
||||
keep = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!keep) {
|
||||
request->removeHeader(h);
|
||||
}
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
void AsyncHeaderFilterMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
for (auto it = _toRemove.begin(); it != _toRemove.end(); ++it)
|
||||
request->removeHeader(*it);
|
||||
next();
|
||||
}
|
||||
|
||||
void AsyncLoggingMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
if (!isEnabled()) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
_out->print(F("* Connection from "));
|
||||
_out->print(request->client()->remoteIP().toString());
|
||||
_out->print(':');
|
||||
_out->println(request->client()->remotePort());
|
||||
_out->print('>');
|
||||
_out->print(' ');
|
||||
_out->print(request->methodToString());
|
||||
_out->print(' ');
|
||||
_out->print(request->url().c_str());
|
||||
_out->print(F(" HTTP/1."));
|
||||
_out->println(request->version());
|
||||
for (auto& h : request->getHeaders()) {
|
||||
if (h.value().length()) {
|
||||
_out->print('>');
|
||||
_out->print(' ');
|
||||
_out->print(h.name());
|
||||
_out->print(':');
|
||||
_out->print(' ');
|
||||
_out->println(h.value());
|
||||
}
|
||||
}
|
||||
_out->println(F(">"));
|
||||
uint32_t elapsed = millis();
|
||||
next();
|
||||
elapsed = millis() - elapsed;
|
||||
AsyncWebServerResponse* response = request->getResponse();
|
||||
if (response) {
|
||||
_out->print(F("* Processed in "));
|
||||
_out->print(elapsed);
|
||||
_out->println(F(" ms"));
|
||||
_out->print('<');
|
||||
_out->print(F(" HTTP/1."));
|
||||
_out->print(request->version());
|
||||
_out->print(' ');
|
||||
_out->print(response->code());
|
||||
_out->print(' ');
|
||||
_out->println(AsyncWebServerResponse::responseCodeToString(response->code()));
|
||||
for (auto& h : response->getHeaders()) {
|
||||
if (h.value().length()) {
|
||||
_out->print('<');
|
||||
_out->print(' ');
|
||||
_out->print(h.name());
|
||||
_out->print(':');
|
||||
_out->print(' ');
|
||||
_out->println(h.value());
|
||||
}
|
||||
}
|
||||
_out->println('<');
|
||||
} else {
|
||||
_out->println(F("* Connection closed!"));
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncCorsMiddleware::addCORSHeaders(AsyncWebServerResponse* response) {
|
||||
response->addHeader(asyncsrv::T_CORS_ACAO, _origin.c_str());
|
||||
response->addHeader(asyncsrv::T_CORS_ACAM, _methods.c_str());
|
||||
response->addHeader(asyncsrv::T_CORS_ACAH, _headers.c_str());
|
||||
response->addHeader(asyncsrv::T_CORS_ACAC, _credentials ? asyncsrv::T_TRUE : asyncsrv::T_FALSE);
|
||||
response->addHeader(asyncsrv::T_CORS_ACMA, String(_maxAge).c_str());
|
||||
}
|
||||
|
||||
void AsyncCorsMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
// Origin header ? => CORS handling
|
||||
if (request->hasHeader(asyncsrv::T_CORS_O)) {
|
||||
// check if this is a preflight request => handle it and return
|
||||
if (request->method() == HTTP_OPTIONS) {
|
||||
AsyncWebServerResponse* response = request->beginResponse(200);
|
||||
addCORSHeaders(response);
|
||||
request->send(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// CORS request, no options => let the request pass and add CORS headers after
|
||||
next();
|
||||
AsyncWebServerResponse* response = request->getResponse();
|
||||
if (response) {
|
||||
addCORSHeaders(response);
|
||||
}
|
||||
|
||||
} else {
|
||||
// NO Origin header => no CORS handling
|
||||
next();
|
||||
}
|
||||
}
|
||||
|
||||
bool AsyncRateLimitMiddleware::isRequestAllowed(uint32_t& retryAfterSeconds) {
|
||||
uint32_t now = millis();
|
||||
|
||||
while (!_requestTimes.empty() && _requestTimes.front() <= now - _windowSizeMillis)
|
||||
_requestTimes.pop_front();
|
||||
|
||||
_requestTimes.push_back(now);
|
||||
|
||||
if (_requestTimes.size() > _maxRequests) {
|
||||
_requestTimes.pop_front();
|
||||
retryAfterSeconds = (_windowSizeMillis - (now - _requestTimes.front())) / 1000 + 1;
|
||||
return false;
|
||||
}
|
||||
|
||||
retryAfterSeconds = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void AsyncRateLimitMiddleware::run(AsyncWebServerRequest* request, ArMiddlewareNext next) {
|
||||
uint32_t retryAfterSeconds;
|
||||
if (isRequestAllowed(retryAfterSeconds)) {
|
||||
next();
|
||||
} else {
|
||||
AsyncWebServerResponse* response = request->beginResponse(429);
|
||||
response->addHeader(asyncsrv::T_retry_after, retryAfterSeconds);
|
||||
request->send(response);
|
||||
}
|
||||
}
|
@ -1,544 +0,0 @@
|
||||
#include "SPIFFSEditor.h"
|
||||
#include <FS.h>
|
||||
|
||||
//File: edit.htm.gz, Size: 4151
|
||||
#define edit_htm_gz_len 4151
|
||||
const uint8_t edit_htm_gz[] PROGMEM = {
|
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x05, 0xBE, 0x11, 0x99, 0x6D, 0x24, 0xE1,
|
||||
0x49, 0x12, 0xB2, 0x40, 0x01, 0x0A, 0x9E, 0x2D, 0x1E, 0x62, 0xEA, 0xEA, 0x23, 0x50, 0x86, 0x6E,
|
||||
0x79, 0x76, 0x98, 0x05, 0x82, 0xC5, 0x01, 0x75, 0x37, 0x5A, 0x30, 0xE3, 0x60, 0x41, 0xAE, 0x8E,
|
||||
0xB9, 0x19, 0x61, 0xCC, 0x77, 0x75, 0x15, 0xA1, 0xF2, 0xB8, 0xB6, 0xEE, 0x14, 0x4F, 0x9D, 0x92,
|
||||
0x56, 0x4E, 0x49, 0xCB, 0xB8, 0x4A, 0xE0, 0x34, 0x3F, 0x18, 0xC3, 0x3C, 0xCE, 0xD4, 0x51, 0x05,
|
||||
0xCC, 0xA7, 0x23, 0x02, 0x9C, 0x7C, 0x40, 0x6D, 0xBA, 0x7A, 0x63, 0xDD, 0x41, 0xA9, 0x3A, 0xC8,
|
||||
0xAF, 0x6A, 0xC4, 0x2F, 0x6B, 0x44, 0xDD, 0xEE, 0x3A, 0x64, 0x5F, 0x21, 0x07, 0x55, 0xE4, 0xA0,
|
||||
0x8C, 0x7C, 0x28, 0x8D, 0x64, 0x1D, 0x72, 0xA0, 0x90, 0x93, 0x8A, 0x88, 0x89, 0x14, 0x51, 0x85,
|
||||
0xBD, 0x3A, 0x6A, 0x13, 0x05, 0xD2, 0xAD, 0xA4, 0x22, 0x66, 0x62, 0x83, 0x97, 0x92, 0x61, 0x40,
|
||||
0x7D, 0x77, 0xA3, 0x09, 0x33, 0x2C, 0xB6, 0xDD, 0xAD, 0xE6, 0x9A, 0x33, 0x12, 0x75, 0x46, 0x56,
|
||||
0x65, 0x30, 0x2B, 0x33, 0xA8, 0xF5, 0xC8, 0x1D, 0xD5, 0xD6, 0x31, 0x98, 0x99, 0x56, 0x60, 0x47,
|
||||
0xDC, 0x0B, 0x98, 0x77, 0xEB, 0x2E, 0xBD, 0xC5, 0x9C,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x28, 0x49, 0x7A, 0xB2, 0x73, 0x95, 0x49, 0x6B, 0x25, 0x06, 0xFE, 0xC8,
|
||||
0xD7, 0xF0, 0xC7, 0xA1, 0xD0, 0xA3, 0x83, 0x9B, 0x49, 0x2B, 0x83, 0xA4, 0x23, 0x64, 0x83, 0xA9,
|
||||
0x37, 0xE4, 0xBB, 0xA8, 0x2D, 0x2F, 0xCB, 0xB4, 0x16, 0x50, 0x70, 0x71, 0x83, 0xBB, 0x11, 0x30,
|
||||
0x52, 0x5A, 0xC4, 0x9E, 0x94, 0xA8, 0xC7, 0x8F, 0x10, 0x1F, 0x53, 0x4A, 0x20, 0x06, 0x20, 0xA6,
|
||||
0x40, 0xD0, 0xA7, 0x42, 0x8A, 0x54, 0xE6, 0x92, 0x53, 0x2A, 0x20, 0xCA, 0x48, 0xCD, 0xE2, 0xC1,
|
||||
0x85, 0x78, 0xD4, 0x46, 0xD6, 0x80, 0xFD, 0xDC, 0xBD, 0x73, 0x33, 0xDE, 0x90, 0x68, 0x09, 0x56,
|
||||
0x36, 0x3D, 0x9A, 0xA6, 0x52, 0x5C, 0x54, 0xC7, 0x19, 0xF8, 0xA8, 0xA1, 0x03, 0x5A, 0x23, 0x84,
|
||||
0x11, 0x1E, 0x84, 0x8A, 0x01, 0x40, 0x7F, 0x42, 0xC3, 0x1C, 0x22, 0x70, 0x08, 0x20, 0x82, 0xA0,
|
||||
0x7F, 0x49, 0x0D, 0xF7, 0x64, 0x05, 0xC9, 0xF8, 0xD8, 0x6D, 0x35, 0xF0, 0x9D, 0x66, 0x95, 0xEC,
|
||||
0x20, 0xA5, 0xBD, 0x68, 0x24, 0xFA, 0x64, 0x98, 0x1A, 0x50, 0x00, 0xAC, 0xD9, 0x01, 0xA0, 0x1E,
|
||||
0x24, 0x5E, 0x63, 0x2B, 0x3F, 0xEF, 0x04, 0x2A, 0xBB, 0x00, 0xAB, 0xBB, 0x8E, 0x87, 0x5F, 0x39,
|
||||
0x4F, 0x19, 0xA7, 0x39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34, 0xE6, 0x63, 0x79, 0x29, 0xBF, 0x2D,
|
||||
0xA0, 0x54, 0xA9, 0xD3, 0x68, 0x78, 0x3E, 0xFF, 0x9A, 0x42, 0x19, 0x1D, 0x65, 0xFE, 0x28, 0x20,
|
||||
0x09, 0xC5, 0x82, 0xA3, 0x41, 0xBE, 0x92, 0xFB, 0x46, 0xC0, 0x86, 0x69, 0x03, 0x93, 0x6D, 0xCB,
|
||||
0xDE, 0xB2, 0x77, 0x71, 0x64, 0x7F, 0x4D, 0xF7, 0x57, 0x4F, 0xD8, 0x5F, 0x34, 0x69, 0x58, 0x0B,
|
||||
0xE7, 0xB5, 0xAB, 0x8A, 0x4D, 0x6A, 0x83, 0xFB, 0xC4, 0xA7, 0x70, 0x3D, 0x6F, 0xB3, 0xCC, 0xB6,
|
||||
0x1A, 0xE4, 0x5F, 0x60, 0xD4, 0x31, 0xBA, 0x95, 0x2F, 0x92, 0xF4, 0x81, 0x7B, 0x18, 0x5B, 0x17,
|
||||
0x54, 0x26, 0x70, 0x49, 0xD5, 0x87, 0x34, 0xB9, 0xD3, 0x9C, 0x2F, 0x39, 0xC3, 0xB7, 0x3C, 0xA8,
|
||||
0x03, 0xE4, 0x37, 0x9C, 0x72, 0x39, 0xB0, 0xBF, 0x07, 0x5D, 0x33, 0x2A, 0x41, 0x79, 0xB1, 0x26,
|
||||
0x9B, 0xE6, 0x7C, 0x02, 0x82, 0x01, 0x70, 0xB1, 0xA3, 0x48, 0xCD, 0x2B, 0xCB, 0x98, 0x9B, 0x57,
|
||||
0x96, 0x54, 0xE2, 0x5F, 0x59, 0xCC, 0xDB, 0x9F, 0xFC, 0xDB, 0x4C, 0xF9, 0x7F, 0x5B, 0x28, 0x36,
|
||||
0x32, 0xF9, 0xE1, 0x09, 0xF7, 0x56, 0x3F, 0x45, 0xAD, 0x47, 0x51, 0xBB, 0xF7, 0xFF, 0x17, 0x53,
|
||||
0xE8, 0x9D, 0x36, 0x92, 0x29, 0x00, 0x00
|
||||
};
|
||||
|
||||
#define SPIFFS_MAXLENGTH_FILEPATH 32
|
||||
const char *excludeListFile = "/.exclude.files";
|
||||
|
||||
typedef struct ExcludeListS {
|
||||
char *item;
|
||||
ExcludeListS *next;
|
||||
} ExcludeList;
|
||||
|
||||
static ExcludeList *excludes = NULL;
|
||||
|
||||
static bool matchWild(const char *pattern, const char *testee) {
|
||||
const char *nxPat = NULL, *nxTst = NULL;
|
||||
|
||||
while (*testee) {
|
||||
if (( *pattern == '?' ) || (*pattern == *testee)){
|
||||
pattern++;testee++;
|
||||
continue;
|
||||
}
|
||||
if (*pattern=='*'){
|
||||
nxPat=pattern++; nxTst=testee;
|
||||
continue;
|
||||
}
|
||||
if (nxPat){
|
||||
pattern = nxPat+1; testee=++nxTst;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
while (*pattern=='*'){pattern++;}
|
||||
return (*pattern == 0);
|
||||
}
|
||||
|
||||
static bool addExclude(const char *item){
|
||||
size_t len = strlen(item);
|
||||
if(!len){
|
||||
return false;
|
||||
}
|
||||
ExcludeList *e = (ExcludeList *)malloc(sizeof(ExcludeList));
|
||||
if(!e){
|
||||
return false;
|
||||
}
|
||||
e->item = (char *)malloc(len+1);
|
||||
if(!e->item){
|
||||
free(e);
|
||||
return false;
|
||||
}
|
||||
memcpy(e->item, item, len+1);
|
||||
e->next = excludes;
|
||||
excludes = e;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void loadExcludeList(fs::FS &_fs, const char *filename){
|
||||
static char linebuf[SPIFFS_MAXLENGTH_FILEPATH];
|
||||
fs::File excludeFile=_fs.open(filename, "r");
|
||||
if(!excludeFile){
|
||||
//addExclude("/*.js.gz");
|
||||
return;
|
||||
}
|
||||
#ifdef ESP32
|
||||
if(excludeFile.isDirectory()){
|
||||
excludeFile.close();
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (excludeFile.size() > 0){
|
||||
uint8_t idx;
|
||||
bool isOverflowed = false;
|
||||
while (excludeFile.available()){
|
||||
linebuf[0] = '\0';
|
||||
idx = 0;
|
||||
int lastChar;
|
||||
do {
|
||||
lastChar = excludeFile.read();
|
||||
if(lastChar != '\r'){
|
||||
linebuf[idx++] = (char) lastChar;
|
||||
}
|
||||
} while ((lastChar >= 0) && (lastChar != '\n') && (idx < SPIFFS_MAXLENGTH_FILEPATH));
|
||||
|
||||
if(isOverflowed){
|
||||
isOverflowed = (lastChar != '\n');
|
||||
continue;
|
||||
}
|
||||
isOverflowed = (idx >= SPIFFS_MAXLENGTH_FILEPATH);
|
||||
linebuf[idx-1] = '\0';
|
||||
if(!addExclude(linebuf)){
|
||||
excludeFile.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
excludeFile.close();
|
||||
}
|
||||
|
||||
static bool isExcluded(fs::FS &_fs, const char *filename) {
|
||||
if(excludes == NULL){
|
||||
loadExcludeList(_fs, excludeListFile);
|
||||
}
|
||||
ExcludeList *e = excludes;
|
||||
while(e){
|
||||
if (matchWild(e->item, filename)){
|
||||
return true;
|
||||
}
|
||||
e = e->next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// WEB HANDLER IMPLEMENTATION
|
||||
|
||||
#ifdef ESP32
|
||||
SPIFFSEditor::SPIFFSEditor(const fs::FS& fs, const String& username, const String& password)
|
||||
#else
|
||||
SPIFFSEditor::SPIFFSEditor(const String& username, const String& password, const fs::FS& fs)
|
||||
#endif
|
||||
:_fs(fs)
|
||||
,_username(username)
|
||||
,_password(password)
|
||||
,_authenticated(false)
|
||||
,_startTime(0)
|
||||
{}
|
||||
|
||||
bool SPIFFSEditor::canHandle(AsyncWebServerRequest *request){
|
||||
if(request->url().equalsIgnoreCase("/edit")){
|
||||
if(request->method() == HTTP_GET){
|
||||
if(request->hasParam("list"))
|
||||
return true;
|
||||
if(request->hasParam("edit")){
|
||||
request->_tempFile = _fs.open(request->arg("edit"), "r");
|
||||
if(!request->_tempFile){
|
||||
return false;
|
||||
}
|
||||
#ifdef ESP32
|
||||
if(request->_tempFile.isDirectory()){
|
||||
request->_tempFile.close();
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
if(request->hasParam("download")){
|
||||
request->_tempFile = _fs.open(request->arg("download"), "r");
|
||||
if(!request->_tempFile){
|
||||
return false;
|
||||
}
|
||||
#ifdef ESP32
|
||||
if(request->_tempFile.isDirectory()){
|
||||
request->_tempFile.close();
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
request->addInterestingHeader("If-Modified-Since");
|
||||
return true;
|
||||
}
|
||||
else if(request->method() == HTTP_POST)
|
||||
return true;
|
||||
else if(request->method() == HTTP_DELETE)
|
||||
return true;
|
||||
else if(request->method() == HTTP_PUT)
|
||||
return true;
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
void SPIFFSEditor::handleRequest(AsyncWebServerRequest *request){
|
||||
if(_username.length() && _password.length() && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
|
||||
if(request->method() == HTTP_GET){
|
||||
if(request->hasParam("list")){
|
||||
String path = request->getParam("list")->value();
|
||||
#ifdef ESP32
|
||||
File dir = _fs.open(path);
|
||||
#else
|
||||
Dir dir = _fs.openDir(path);
|
||||
#endif
|
||||
path = String();
|
||||
String output = "[";
|
||||
#ifdef ESP32
|
||||
File entry = dir.openNextFile();
|
||||
while(entry){
|
||||
#else
|
||||
while(dir.next()){
|
||||
fs::File entry = dir.openFile("r");
|
||||
#endif
|
||||
if (isExcluded(_fs, entry.name())) {
|
||||
#ifdef ESP32
|
||||
entry = dir.openNextFile();
|
||||
#endif
|
||||
continue;
|
||||
}
|
||||
if (output != "[") output += ',';
|
||||
output += "{\"type\":\"";
|
||||
output += "file";
|
||||
output += "\",\"name\":\"";
|
||||
output += String(entry.name());
|
||||
output += "\",\"size\":";
|
||||
output += String(entry.size());
|
||||
output += "}";
|
||||
#ifdef ESP32
|
||||
entry = dir.openNextFile();
|
||||
#else
|
||||
entry.close();
|
||||
#endif
|
||||
}
|
||||
#ifdef ESP32
|
||||
dir.close();
|
||||
#endif
|
||||
output += "]";
|
||||
request->send(200, "application/json", output);
|
||||
output = String();
|
||||
}
|
||||
else if(request->hasParam("edit") || request->hasParam("download")){
|
||||
request->send(request->_tempFile, request->_tempFile.name(), String(), request->hasParam("download"));
|
||||
}
|
||||
else {
|
||||
const char * buildTime = __DATE__ " " __TIME__ " GMT";
|
||||
if (request->header("If-Modified-Since").equals(buildTime)) {
|
||||
request->send(304);
|
||||
} else {
|
||||
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", edit_htm_gz, edit_htm_gz_len);
|
||||
response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Last-Modified", buildTime);
|
||||
request->send(response);
|
||||
}
|
||||
}
|
||||
} else if(request->method() == HTTP_DELETE){
|
||||
if(request->hasParam("path", true)){
|
||||
_fs.remove(request->getParam("path", true)->value());
|
||||
request->send(200, "", "DELETE: "+request->getParam("path", true)->value());
|
||||
} else
|
||||
request->send(404);
|
||||
} else if(request->method() == HTTP_POST){
|
||||
if(request->hasParam("data", true, true) && _fs.exists(request->getParam("data", true, true)->value()))
|
||||
request->send(200, "", "UPLOADED: "+request->getParam("data", true, true)->value());
|
||||
else
|
||||
request->send(500);
|
||||
} else if(request->method() == HTTP_PUT){
|
||||
if(request->hasParam("path", true)){
|
||||
String filename = request->getParam("path", true)->value();
|
||||
if(_fs.exists(filename)){
|
||||
request->send(200);
|
||||
} else {
|
||||
fs::File f = _fs.open(filename, "w");
|
||||
if(f){
|
||||
f.write((uint8_t)0x00);
|
||||
f.close();
|
||||
request->send(200, "", "CREATE: "+filename);
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
}
|
||||
} else
|
||||
request->send(400);
|
||||
}
|
||||
}
|
||||
|
||||
void SPIFFSEditor::handleUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final){
|
||||
if(!index){
|
||||
if(!_username.length() || request->authenticate(_username.c_str(),_password.c_str())){
|
||||
_authenticated = true;
|
||||
request->_tempFile = _fs.open(filename, "w");
|
||||
_startTime = millis();
|
||||
}
|
||||
}
|
||||
if(_authenticated && request->_tempFile){
|
||||
if(len){
|
||||
request->_tempFile.write(data,len);
|
||||
}
|
||||
if(final){
|
||||
request->_tempFile.close();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,24 +0,0 @@
|
||||
#ifndef SPIFFSEditor_H_
|
||||
#define SPIFFSEditor_H_
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
class SPIFFSEditor: public AsyncWebHandler {
|
||||
private:
|
||||
fs::FS _fs;
|
||||
String _username;
|
||||
String _password;
|
||||
bool _authenticated;
|
||||
uint32_t _startTime;
|
||||
public:
|
||||
#ifdef ESP32
|
||||
SPIFFSEditor(const fs::FS& fs, const String& username=String(), const String& password=String());
|
||||
#else
|
||||
SPIFFSEditor(const String& username=String(), const String& password=String(), const fs::FS& fs=SPIFFS);
|
||||
#endif
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final;
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final;
|
||||
virtual void handleUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) override final;
|
||||
virtual bool isRequestHandlerTrivial() override final {return false;}
|
||||
};
|
||||
|
||||
#endif
|
@ -1,193 +0,0 @@
|
||||
/*
|
||||
Asynchronous WebServer library for Espressif MCUs
|
||||
|
||||
Copyright (c) 2016 Hristo Gochkov. All rights reserved.
|
||||
This file is part of the esp8266 core 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
|
||||
*/
|
||||
#ifndef STRINGARRAY_H_
|
||||
#define STRINGARRAY_H_
|
||||
|
||||
#include "stddef.h"
|
||||
#include "WString.h"
|
||||
|
||||
template <typename T>
|
||||
class LinkedListNode {
|
||||
T _value;
|
||||
public:
|
||||
LinkedListNode<T>* next;
|
||||
LinkedListNode(const T val): _value(val), next(nullptr) {}
|
||||
~LinkedListNode(){}
|
||||
const T& value() const { return _value; };
|
||||
T& value(){ return _value; }
|
||||
};
|
||||
|
||||
template <typename T, template<typename> class Item = LinkedListNode>
|
||||
class LinkedList {
|
||||
public:
|
||||
typedef Item<T> ItemType;
|
||||
typedef std::function<void(const T&)> OnRemove;
|
||||
typedef std::function<bool(const T&)> Predicate;
|
||||
private:
|
||||
ItemType* _root;
|
||||
OnRemove _onRemove;
|
||||
|
||||
class Iterator {
|
||||
ItemType* _node;
|
||||
public:
|
||||
Iterator(ItemType* current = nullptr) : _node(current) {}
|
||||
Iterator(const Iterator& i) : _node(i._node) {}
|
||||
Iterator& operator ++() { _node = _node->next; return *this; }
|
||||
bool operator != (const Iterator& i) const { return _node != i._node; }
|
||||
const T& operator * () const { return _node->value(); }
|
||||
const T* operator -> () const { return &_node->value(); }
|
||||
};
|
||||
|
||||
public:
|
||||
typedef const Iterator ConstIterator;
|
||||
ConstIterator begin() const { return ConstIterator(_root); }
|
||||
ConstIterator end() const { return ConstIterator(nullptr); }
|
||||
|
||||
LinkedList(OnRemove onRemove) : _root(nullptr), _onRemove(onRemove) {}
|
||||
~LinkedList(){}
|
||||
void add(const T& t){
|
||||
auto it = new ItemType(t);
|
||||
if(!_root){
|
||||
_root = it;
|
||||
} else {
|
||||
auto i = _root;
|
||||
while(i->next) i = i->next;
|
||||
i->next = it;
|
||||
}
|
||||
}
|
||||
T& front() const {
|
||||
return _root->value();
|
||||
}
|
||||
|
||||
bool isEmpty() const {
|
||||
return _root == nullptr;
|
||||
}
|
||||
size_t length() const {
|
||||
size_t i = 0;
|
||||
auto it = _root;
|
||||
while(it){
|
||||
i++;
|
||||
it = it->next;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
size_t count_if(Predicate predicate) const {
|
||||
size_t i = 0;
|
||||
auto it = _root;
|
||||
while(it){
|
||||
if (!predicate){
|
||||
i++;
|
||||
}
|
||||
else if (predicate(it->value())) {
|
||||
i++;
|
||||
}
|
||||
it = it->next;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
const T* nth(size_t N) const {
|
||||
size_t i = 0;
|
||||
auto it = _root;
|
||||
while(it){
|
||||
if(i++ == N)
|
||||
return &(it->value());
|
||||
it = it->next;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
bool remove(const T& t){
|
||||
auto it = _root;
|
||||
auto pit = _root;
|
||||
while(it){
|
||||
if(it->value() == t){
|
||||
if(it == _root){
|
||||
_root = _root->next;
|
||||
} else {
|
||||
pit->next = it->next;
|
||||
}
|
||||
|
||||
if (_onRemove) {
|
||||
_onRemove(it->value());
|
||||
}
|
||||
|
||||
delete it;
|
||||
return true;
|
||||
}
|
||||
pit = it;
|
||||
it = it->next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
bool remove_first(Predicate predicate){
|
||||
auto it = _root;
|
||||
auto pit = _root;
|
||||
while(it){
|
||||
if(predicate(it->value())){
|
||||
if(it == _root){
|
||||
_root = _root->next;
|
||||
} else {
|
||||
pit->next = it->next;
|
||||
}
|
||||
if (_onRemove) {
|
||||
_onRemove(it->value());
|
||||
}
|
||||
delete it;
|
||||
return true;
|
||||
}
|
||||
pit = it;
|
||||
it = it->next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void free(){
|
||||
while(_root != nullptr){
|
||||
auto it = _root;
|
||||
_root = _root->next;
|
||||
if (_onRemove) {
|
||||
_onRemove(it->value());
|
||||
}
|
||||
delete it;
|
||||
}
|
||||
_root = nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
class StringArray : public LinkedList<String> {
|
||||
public:
|
||||
|
||||
StringArray() : LinkedList(nullptr) {}
|
||||
|
||||
bool containsIgnoreCase(const String& str){
|
||||
for (const auto& s : *this) {
|
||||
if (str.equalsIgnoreCase(s)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#endif /* STRINGARRAY_H_ */
|
@ -20,222 +20,214 @@
|
||||
*/
|
||||
#include "WebAuthentication.h"
|
||||
#include <libb64/cencode.h>
|
||||
#ifdef ESP32
|
||||
#include "mbedtls/md5.h"
|
||||
#if defined(ESP32) || defined(TARGET_RP2040)
|
||||
#include <MD5Builder.h>
|
||||
#else
|
||||
#include "md5.h"
|
||||
#include "md5.h"
|
||||
#endif
|
||||
#include "literals.h"
|
||||
|
||||
using namespace asyncsrv;
|
||||
|
||||
// Basic Auth hash = base64("username:password")
|
||||
|
||||
bool checkBasicAuthentication(const char * hash, const char * username, const char * password){
|
||||
if(username == NULL || password == NULL || hash == NULL)
|
||||
bool checkBasicAuthentication(const char* hash, const char* username, const char* password) {
|
||||
if (username == NULL || password == NULL || hash == NULL)
|
||||
return false;
|
||||
return generateBasicHash(username, password).equalsIgnoreCase(hash);
|
||||
}
|
||||
|
||||
size_t toencodeLen = strlen(username)+strlen(password)+1;
|
||||
size_t encodedLen = base64_encode_expected_len(toencodeLen);
|
||||
if(strlen(hash) != encodedLen)
|
||||
return false;
|
||||
String generateBasicHash(const char* username, const char* password) {
|
||||
if (username == NULL || password == NULL)
|
||||
return emptyString;
|
||||
|
||||
char *toencode = new char[toencodeLen+1];
|
||||
if(toencode == NULL){
|
||||
return false;
|
||||
size_t toencodeLen = strlen(username) + strlen(password) + 1;
|
||||
|
||||
char* toencode = new char[toencodeLen + 1];
|
||||
if (toencode == NULL) {
|
||||
return emptyString;
|
||||
}
|
||||
char *encoded = new char[base64_encode_expected_len(toencodeLen)+1];
|
||||
if(encoded == NULL){
|
||||
char* encoded = new char[base64_encode_expected_len(toencodeLen) + 1];
|
||||
if (encoded == NULL) {
|
||||
delete[] toencode;
|
||||
return false;
|
||||
return emptyString;
|
||||
}
|
||||
sprintf(toencode, "%s:%s", username, password);
|
||||
if(base64_encode_chars(toencode, toencodeLen, encoded) > 0 && memcmp(hash, encoded, encodedLen) == 0){
|
||||
sprintf_P(toencode, PSTR("%s:%s"), username, password);
|
||||
if (base64_encode_chars(toencode, toencodeLen, encoded) > 0) {
|
||||
String res = String(encoded);
|
||||
delete[] toencode;
|
||||
delete[] encoded;
|
||||
return true;
|
||||
return res;
|
||||
}
|
||||
delete[] toencode;
|
||||
delete[] encoded;
|
||||
return false;
|
||||
return emptyString;
|
||||
}
|
||||
|
||||
static bool getMD5(uint8_t * data, uint16_t len, char * output){//33 bytes or more
|
||||
#ifdef ESP32
|
||||
mbedtls_md5_context _ctx;
|
||||
static bool getMD5(uint8_t* data, uint16_t len, char* output) { // 33 bytes or more
|
||||
#if defined(ESP32) || defined(TARGET_RP2040)
|
||||
MD5Builder md5;
|
||||
md5.begin();
|
||||
md5.add(data, len);
|
||||
md5.calculate();
|
||||
md5.getChars(output);
|
||||
#else
|
||||
md5_context_t _ctx;
|
||||
#endif
|
||||
uint8_t i;
|
||||
uint8_t * _buf = (uint8_t*)malloc(16);
|
||||
if(_buf == NULL)
|
||||
md5_context_t _ctx;
|
||||
|
||||
uint8_t* _buf = (uint8_t*)malloc(16);
|
||||
if (_buf == NULL)
|
||||
return false;
|
||||
memset(_buf, 0x00, 16);
|
||||
#ifdef ESP32
|
||||
mbedtls_md5_init(&_ctx);
|
||||
#if ESP_IDF_VERSION_MAJOR < 5
|
||||
mbedtls_md5_starts_ret(&_ctx);
|
||||
mbedtls_md5_update_ret(&_ctx, data, len);
|
||||
mbedtls_md5_finish_ret(&_ctx, _buf);
|
||||
#else
|
||||
mbedtls_md5_starts(&_ctx);
|
||||
mbedtls_md5_update(&_ctx, data, len);
|
||||
mbedtls_md5_finish(&_ctx, _buf);
|
||||
#endif
|
||||
#else
|
||||
|
||||
MD5Init(&_ctx);
|
||||
MD5Update(&_ctx, data, len);
|
||||
MD5Final(_buf, &_ctx);
|
||||
#endif
|
||||
for(i = 0; i < 16; i++) {
|
||||
sprintf(output + (i * 2), "%02x", _buf[i]);
|
||||
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
sprintf_P(output + (i * 2), PSTR("%02x"), _buf[i]);
|
||||
}
|
||||
|
||||
free(_buf);
|
||||
#endif
|
||||
return true;
|
||||
}
|
||||
|
||||
static String genRandomMD5(){
|
||||
String genRandomMD5() {
|
||||
#ifdef ESP8266
|
||||
uint32_t r = RANDOM_REG32;
|
||||
#else
|
||||
uint32_t r = rand();
|
||||
#endif
|
||||
char * out = (char*)malloc(33);
|
||||
if(out == NULL || !getMD5((uint8_t*)(&r), 4, out))
|
||||
return "";
|
||||
char* out = (char*)malloc(33);
|
||||
if (out == NULL || !getMD5((uint8_t*)(&r), 4, out))
|
||||
return emptyString;
|
||||
String res = String(out);
|
||||
free(out);
|
||||
return res;
|
||||
}
|
||||
|
||||
static String stringMD5(const String& in){
|
||||
char * out = (char*)malloc(33);
|
||||
if(out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out))
|
||||
return "";
|
||||
static String stringMD5(const String& in) {
|
||||
char* out = (char*)malloc(33);
|
||||
if (out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out))
|
||||
return emptyString;
|
||||
String res = String(out);
|
||||
free(out);
|
||||
return res;
|
||||
}
|
||||
|
||||
String generateDigestHash(const char * username, const char * password, const char * realm){
|
||||
if(username == NULL || password == NULL || realm == NULL){
|
||||
return "";
|
||||
String generateDigestHash(const char* username, const char* password, const char* realm) {
|
||||
if (username == NULL || password == NULL || realm == NULL) {
|
||||
return emptyString;
|
||||
}
|
||||
char * out = (char*)malloc(33);
|
||||
String res = String(username);
|
||||
res.concat(":");
|
||||
res.concat(realm);
|
||||
res.concat(":");
|
||||
String in = res;
|
||||
char* out = (char*)malloc(33);
|
||||
|
||||
String in;
|
||||
in.reserve(strlen(username) + strlen(realm) + strlen(password) + 2);
|
||||
in.concat(username);
|
||||
in.concat(':');
|
||||
in.concat(realm);
|
||||
in.concat(':');
|
||||
in.concat(password);
|
||||
if(out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out))
|
||||
return "";
|
||||
res.concat(out);
|
||||
|
||||
if (out == NULL || !getMD5((uint8_t*)(in.c_str()), in.length(), out))
|
||||
return emptyString;
|
||||
|
||||
in = String(out);
|
||||
free(out);
|
||||
return res;
|
||||
return in;
|
||||
}
|
||||
|
||||
String requestDigestAuthentication(const char * realm){
|
||||
String header = "realm=\"";
|
||||
if(realm == NULL)
|
||||
header.concat("asyncesp");
|
||||
else
|
||||
header.concat(realm);
|
||||
header.concat( "\", qop=\"auth\", nonce=\"");
|
||||
header.concat(genRandomMD5());
|
||||
header.concat("\", opaque=\"");
|
||||
header.concat(genRandomMD5());
|
||||
header.concat("\"");
|
||||
return header;
|
||||
}
|
||||
|
||||
bool checkDigestAuthentication(const char * header, const char * method, const char * username, const char * password, const char * realm, bool passwordIsHash, const char * nonce, const char * opaque, const char * uri){
|
||||
if(username == NULL || password == NULL || header == NULL || method == NULL){
|
||||
//os_printf("AUTH FAIL: missing requred fields\n");
|
||||
bool checkDigestAuthentication(const char* header, const char* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri)
|
||||
{
|
||||
if (username == NULL || password == NULL || header == NULL || method == NULL) {
|
||||
// os_printf("AUTH FAIL: missing requred fields\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
String myHeader = String(header);
|
||||
int nextBreak = myHeader.indexOf(",");
|
||||
if(nextBreak < 0){
|
||||
//os_printf("AUTH FAIL: no variables\n");
|
||||
String myHeader(header);
|
||||
int nextBreak = myHeader.indexOf(',');
|
||||
if (nextBreak < 0) {
|
||||
// os_printf("AUTH FAIL: no variables\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
String myUsername = String();
|
||||
String myRealm = String();
|
||||
String myNonce = String();
|
||||
String myUri = String();
|
||||
String myResponse = String();
|
||||
String myQop = String();
|
||||
String myNc = String();
|
||||
String myCnonce = String();
|
||||
String myUsername;
|
||||
String myRealm;
|
||||
String myNonce;
|
||||
String myUri;
|
||||
String myResponse;
|
||||
String myQop;
|
||||
String myNc;
|
||||
String myCnonce;
|
||||
|
||||
myHeader += ", ";
|
||||
myHeader += (char)0x2c; // ','
|
||||
myHeader += (char)0x20; // ' '
|
||||
do {
|
||||
String avLine = myHeader.substring(0, nextBreak);
|
||||
String avLine(myHeader.substring(0, nextBreak));
|
||||
avLine.trim();
|
||||
myHeader = myHeader.substring(nextBreak+1);
|
||||
nextBreak = myHeader.indexOf(",");
|
||||
myHeader = myHeader.substring(nextBreak + 1);
|
||||
nextBreak = myHeader.indexOf(',');
|
||||
|
||||
int eqSign = avLine.indexOf("=");
|
||||
if(eqSign < 0){
|
||||
//os_printf("AUTH FAIL: no = sign\n");
|
||||
int eqSign = avLine.indexOf('=');
|
||||
if (eqSign < 0) {
|
||||
// os_printf("AUTH FAIL: no = sign\n");
|
||||
return false;
|
||||
}
|
||||
String varName = avLine.substring(0, eqSign);
|
||||
String varName(avLine.substring(0, eqSign));
|
||||
avLine = avLine.substring(eqSign + 1);
|
||||
if(avLine.startsWith("\"")){
|
||||
if (avLine.startsWith(String('"'))) {
|
||||
avLine = avLine.substring(1, avLine.length() - 1);
|
||||
}
|
||||
|
||||
if(varName.equals("username")){
|
||||
if(!avLine.equals(username)){
|
||||
//os_printf("AUTH FAIL: username\n");
|
||||
if (varName.equals(T_username)) {
|
||||
if (!avLine.equals(username)) {
|
||||
// os_printf("AUTH FAIL: username\n");
|
||||
return false;
|
||||
}
|
||||
myUsername = avLine;
|
||||
} else if(varName.equals("realm")){
|
||||
if(realm != NULL && !avLine.equals(realm)){
|
||||
//os_printf("AUTH FAIL: realm\n");
|
||||
} else if (varName.equals(T_realm)) {
|
||||
if (realm != NULL && !avLine.equals(realm)) {
|
||||
// os_printf("AUTH FAIL: realm\n");
|
||||
return false;
|
||||
}
|
||||
myRealm = avLine;
|
||||
} else if(varName.equals("nonce")){
|
||||
if(nonce != NULL && !avLine.equals(nonce)){
|
||||
//os_printf("AUTH FAIL: nonce\n");
|
||||
} else if (varName.equals(T_nonce)) {
|
||||
if (nonce != NULL && !avLine.equals(nonce)) {
|
||||
// os_printf("AUTH FAIL: nonce\n");
|
||||
return false;
|
||||
}
|
||||
myNonce = avLine;
|
||||
} else if(varName.equals("opaque")){
|
||||
if(opaque != NULL && !avLine.equals(opaque)){
|
||||
//os_printf("AUTH FAIL: opaque\n");
|
||||
} else if (varName.equals(T_opaque)) {
|
||||
if (opaque != NULL && !avLine.equals(opaque)) {
|
||||
// os_printf("AUTH FAIL: opaque\n");
|
||||
return false;
|
||||
}
|
||||
} else if(varName.equals("uri")){
|
||||
if(uri != NULL && !avLine.equals(uri)){
|
||||
//os_printf("AUTH FAIL: uri\n");
|
||||
} else if (varName.equals(T_uri)) {
|
||||
if (uri != NULL && !avLine.equals(uri)) {
|
||||
// os_printf("AUTH FAIL: uri\n");
|
||||
return false;
|
||||
}
|
||||
myUri = avLine;
|
||||
} else if(varName.equals("response")){
|
||||
} else if (varName.equals(T_response)) {
|
||||
myResponse = avLine;
|
||||
} else if(varName.equals("qop")){
|
||||
} else if (varName.equals(T_qop)) {
|
||||
myQop = avLine;
|
||||
} else if(varName.equals("nc")){
|
||||
} else if (varName.equals(T_nc)) {
|
||||
myNc = avLine;
|
||||
} else if(varName.equals("cnonce")){
|
||||
} else if (varName.equals(T_cnonce)) {
|
||||
myCnonce = avLine;
|
||||
}
|
||||
} while(nextBreak > 0);
|
||||
} while (nextBreak > 0);
|
||||
|
||||
String ha1 = (passwordIsHash) ? String(password) : stringMD5(myUsername + ":" + myRealm + ":" + String(password));
|
||||
String ha2 = String(method) + ":" + myUri;
|
||||
String response = ha1 + ":" + myNonce + ":" + myNc + ":" + myCnonce + ":" + myQop + ":" + stringMD5(ha2);
|
||||
String ha1 = passwordIsHash ? password : stringMD5(myUsername + ':' + myRealm + ':' + password).c_str();
|
||||
String ha2 = stringMD5(String(method) + ':' + myUri);
|
||||
String response = ha1 + ':' + myNonce + ':' + myNc + ':' + myCnonce + ':' + myQop + ':' + ha2;
|
||||
|
||||
if(myResponse.equals(stringMD5(response))){
|
||||
//os_printf("AUTH SUCCESS\n");
|
||||
if (myResponse.equals(stringMD5(response))) {
|
||||
// os_printf("AUTH SUCCESS\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
//os_printf("AUTH FAIL: password\n");
|
||||
// os_printf("AUTH FAIL: password\n");
|
||||
return false;
|
||||
}
|
||||
|
@ -24,11 +24,15 @@
|
||||
|
||||
#include "Arduino.h"
|
||||
|
||||
bool checkBasicAuthentication(const char * header, const char * username, const char * password);
|
||||
String requestDigestAuthentication(const char * realm);
|
||||
bool checkDigestAuthentication(const char * header, const char * method, const char * username, const char * password, const char * realm, bool passwordIsHash, const char * nonce, const char * opaque, const char * uri);
|
||||
bool checkBasicAuthentication(const char* header, const char* username, const char* password);
|
||||
|
||||
//for storing hashed versions on the device that can be authenticated against
|
||||
String generateDigestHash(const char * username, const char * password, const char * realm);
|
||||
bool checkDigestAuthentication(const char* header, const char* method, const char* username, const char* password, const char* realm, bool passwordIsHash, const char* nonce, const char* opaque, const char* uri);
|
||||
|
||||
// for storing hashed versions on the device that can be authenticated against
|
||||
String generateDigestHash(const char* username, const char* password, const char* realm);
|
||||
|
||||
String generateBasicHash(const char* username, const char* password);
|
||||
|
||||
String genRandomMD5();
|
||||
|
||||
#endif
|
||||
|
@ -23,19 +23,21 @@
|
||||
|
||||
#include <string>
|
||||
#ifdef ASYNCWEBSERVER_REGEX
|
||||
#include <regex>
|
||||
#include <regex>
|
||||
#endif
|
||||
|
||||
#include "stddef.h"
|
||||
#include <time.h>
|
||||
|
||||
class AsyncStaticWebHandler: public AsyncWebHandler {
|
||||
using File = fs::File;
|
||||
using FS = fs::FS;
|
||||
class AsyncStaticWebHandler : public AsyncWebHandler {
|
||||
using File = fs::File;
|
||||
using FS = fs::FS;
|
||||
|
||||
private:
|
||||
bool _getFile(AsyncWebServerRequest *request);
|
||||
bool _fileExists(AsyncWebServerRequest *request, const String& path);
|
||||
bool _getFile(AsyncWebServerRequest* request) const;
|
||||
bool _searchFile(AsyncWebServerRequest* request, const String& path);
|
||||
uint8_t _countBits(const uint8_t value) const;
|
||||
|
||||
protected:
|
||||
FS _fs;
|
||||
String _uri;
|
||||
@ -45,25 +47,33 @@ class AsyncStaticWebHandler: public AsyncWebHandler {
|
||||
String _last_modified;
|
||||
AwsTemplateProcessor _callback;
|
||||
bool _isDir;
|
||||
bool _gzipFirst;
|
||||
uint8_t _gzipStats;
|
||||
bool _tryGzipFirst = true;
|
||||
|
||||
public:
|
||||
AsyncStaticWebHandler(const char* uri, FS& fs, const char* path, const char* cache_control);
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final;
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final;
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
AsyncStaticWebHandler& setTryGzipFirst(bool value);
|
||||
AsyncStaticWebHandler& setIsDir(bool isDir);
|
||||
AsyncStaticWebHandler& setDefaultFile(const char* filename);
|
||||
AsyncStaticWebHandler& setCacheControl(const char* cache_control);
|
||||
|
||||
/**
|
||||
* @brief Set the Last-Modified time for the object
|
||||
*
|
||||
* @param last_modified
|
||||
* @return AsyncStaticWebHandler&
|
||||
*/
|
||||
AsyncStaticWebHandler& setLastModified(const char* last_modified);
|
||||
AsyncStaticWebHandler& setLastModified(struct tm* last_modified);
|
||||
#ifdef ESP8266
|
||||
AsyncStaticWebHandler& setLastModified(time_t last_modified);
|
||||
AsyncStaticWebHandler& setLastModified(); //sets to current time. Make sure sntp is runing and time is updated
|
||||
#endif
|
||||
AsyncStaticWebHandler& setTemplateProcessor(AwsTemplateProcessor newCallback) {_callback = newCallback; return *this;}
|
||||
// sets to current time. Make sure sntp is runing and time is updated
|
||||
AsyncStaticWebHandler& setLastModified();
|
||||
|
||||
AsyncStaticWebHandler& setTemplateProcessor(AwsTemplateProcessor newCallback);
|
||||
};
|
||||
|
||||
class AsyncCallbackWebHandler: public AsyncWebHandler {
|
||||
class AsyncCallbackWebHandler : public AsyncWebHandler {
|
||||
private:
|
||||
protected:
|
||||
String _uri;
|
||||
@ -72,80 +82,20 @@ class AsyncCallbackWebHandler: public AsyncWebHandler {
|
||||
ArUploadHandlerFunction _onUpload;
|
||||
ArBodyHandlerFunction _onBody;
|
||||
bool _isRegex;
|
||||
|
||||
public:
|
||||
AsyncCallbackWebHandler() : _uri(), _method(HTTP_ANY), _onRequest(NULL), _onUpload(NULL), _onBody(NULL), _isRegex(false) {}
|
||||
void setUri(const String& uri){
|
||||
_uri = uri;
|
||||
_isRegex = uri.startsWith("^") && uri.endsWith("$");
|
||||
}
|
||||
void setMethod(WebRequestMethodComposite method){ _method = method; }
|
||||
void onRequest(ArRequestHandlerFunction fn){ _onRequest = fn; }
|
||||
void onUpload(ArUploadHandlerFunction fn){ _onUpload = fn; }
|
||||
void onBody(ArBodyHandlerFunction fn){ _onBody = fn; }
|
||||
void setUri(const String& uri);
|
||||
void setMethod(WebRequestMethodComposite method) { _method = method; }
|
||||
void onRequest(ArRequestHandlerFunction fn) { _onRequest = fn; }
|
||||
void onUpload(ArUploadHandlerFunction fn) { _onUpload = fn; }
|
||||
void onBody(ArBodyHandlerFunction fn) { _onBody = fn; }
|
||||
|
||||
virtual bool canHandle(AsyncWebServerRequest *request) override final{
|
||||
|
||||
if(!_onRequest)
|
||||
return false;
|
||||
|
||||
if(!(_method & request->method()))
|
||||
return false;
|
||||
|
||||
#ifdef ASYNCWEBSERVER_REGEX
|
||||
if (_isRegex) {
|
||||
std::regex pattern(_uri.c_str());
|
||||
std::smatch matches;
|
||||
std::string s(request->url().c_str());
|
||||
if(std::regex_search(s, matches, pattern)) {
|
||||
for (size_t i = 1; i < matches.size(); ++i) { // start from 1
|
||||
request->_addPathParam(matches[i].str().c_str());
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
if (_uri.length() && _uri.startsWith("/*.")) {
|
||||
String uriTemplate = String (_uri);
|
||||
uriTemplate = uriTemplate.substring(uriTemplate.lastIndexOf("."));
|
||||
if (!request->url().endsWith(uriTemplate))
|
||||
return false;
|
||||
}
|
||||
else
|
||||
if (_uri.length() && _uri.endsWith("*")) {
|
||||
String uriTemplate = String(_uri);
|
||||
uriTemplate = uriTemplate.substring(0, uriTemplate.length() - 1);
|
||||
if (!request->url().startsWith(uriTemplate))
|
||||
return false;
|
||||
}
|
||||
else if(_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri+"/")))
|
||||
return false;
|
||||
|
||||
request->addInterestingHeader("ANY");
|
||||
return true;
|
||||
}
|
||||
|
||||
virtual void handleRequest(AsyncWebServerRequest *request) override final {
|
||||
if((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
if(_onRequest)
|
||||
_onRequest(request);
|
||||
else
|
||||
request->send(500);
|
||||
}
|
||||
virtual void handleUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) override final {
|
||||
if((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
if(_onUpload)
|
||||
_onUpload(request, filename, index, data, len, final);
|
||||
}
|
||||
virtual void handleBody(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) override final {
|
||||
if((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
if(_onBody)
|
||||
_onBody(request, data, len, index, total);
|
||||
}
|
||||
virtual bool isRequestHandlerTrivial() override final {return _onRequest ? false : true;}
|
||||
bool canHandle(AsyncWebServerRequest* request) const override final;
|
||||
void handleRequest(AsyncWebServerRequest* request) override final;
|
||||
void handleUpload(AsyncWebServerRequest* request, const String& filename, size_t index, uint8_t* data, size_t len, bool final) override final;
|
||||
void handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) override final;
|
||||
bool isRequestHandlerTrivial() const override final { return !_onRequest; }
|
||||
};
|
||||
|
||||
#endif /* ASYNCWEBSERVERHANDLERIMPL_H_ */
|
||||
|
@ -21,99 +21,110 @@
|
||||
#include "ESPAsyncWebServer.h"
|
||||
#include "WebHandlerImpl.h"
|
||||
|
||||
using namespace asyncsrv;
|
||||
|
||||
AsyncWebHandler& AsyncWebHandler::setFilter(ArRequestFilterFunction fn) {
|
||||
_filter = fn;
|
||||
return *this;
|
||||
}
|
||||
AsyncWebHandler& AsyncWebHandler::setAuthentication(const char* username, const char* password, AsyncAuthType authMethod) {
|
||||
if (!_authMiddleware) {
|
||||
_authMiddleware = new AsyncAuthenticationMiddleware();
|
||||
_authMiddleware->_freeOnRemoval = true;
|
||||
addMiddleware(_authMiddleware);
|
||||
}
|
||||
_authMiddleware->setUsername(username);
|
||||
_authMiddleware->setPassword(password);
|
||||
_authMiddleware->setAuthType(authMethod);
|
||||
return *this;
|
||||
};
|
||||
|
||||
AsyncStaticWebHandler::AsyncStaticWebHandler(const char* uri, FS& fs, const char* path, const char* cache_control)
|
||||
: _fs(fs), _uri(uri), _path(path), _default_file("index.htm"), _cache_control(cache_control), _last_modified(""), _callback(nullptr)
|
||||
{
|
||||
: _fs(fs), _uri(uri), _path(path), _default_file(F("index.htm")), _cache_control(cache_control), _last_modified(), _callback(nullptr) {
|
||||
// Ensure leading '/'
|
||||
if (_uri.length() == 0 || _uri[0] != '/') _uri = "/" + _uri;
|
||||
if (_path.length() == 0 || _path[0] != '/') _path = "/" + _path;
|
||||
if (_uri.length() == 0 || _uri[0] != '/')
|
||||
_uri = String('/') + _uri;
|
||||
if (_path.length() == 0 || _path[0] != '/')
|
||||
_path = String('/') + _path;
|
||||
|
||||
// If path ends with '/' we assume a hint that this is a directory to improve performance.
|
||||
// However - if it does not end with '/' we, can't assume a file, path can still be a directory.
|
||||
_isDir = _path[_path.length()-1] == '/';
|
||||
_isDir = _path[_path.length() - 1] == '/';
|
||||
|
||||
// Remove the trailing '/' so we can handle default file
|
||||
// Notice that root will be "" not "/"
|
||||
if (_uri[_uri.length()-1] == '/') _uri = _uri.substring(0, _uri.length()-1);
|
||||
if (_path[_path.length()-1] == '/') _path = _path.substring(0, _path.length()-1);
|
||||
|
||||
// Reset stats
|
||||
_gzipFirst = false;
|
||||
_gzipStats = 0xF8;
|
||||
if (_uri[_uri.length() - 1] == '/')
|
||||
_uri = _uri.substring(0, _uri.length() - 1);
|
||||
if (_path[_path.length() - 1] == '/')
|
||||
_path = _path.substring(0, _path.length() - 1);
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setIsDir(bool isDir){
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setTryGzipFirst(bool value) {
|
||||
_tryGzipFirst = value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setIsDir(bool isDir) {
|
||||
_isDir = isDir;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setDefaultFile(const char* filename){
|
||||
_default_file = String(filename);
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setDefaultFile(const char* filename) {
|
||||
_default_file = filename;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setCacheControl(const char* cache_control){
|
||||
_cache_control = String(cache_control);
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setCacheControl(const char* cache_control) {
|
||||
_cache_control = cache_control;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(const char* last_modified){
|
||||
_last_modified = String(last_modified);
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(const char* last_modified) {
|
||||
_last_modified = last_modified;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(struct tm* last_modified){
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(struct tm* last_modified) {
|
||||
char result[30];
|
||||
strftime (result,30,"%a, %d %b %Y %H:%M:%S %Z", last_modified);
|
||||
return setLastModified((const char *)result);
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(time_t last_modified){
|
||||
return setLastModified((struct tm *)gmtime(&last_modified));
|
||||
auto formatP = PSTR("%a, %d %b %Y %H:%M:%S GMT");
|
||||
char format[strlen_P(formatP) + 1];
|
||||
strcpy_P(format, formatP);
|
||||
#else
|
||||
static constexpr const char* format = "%a, %d %b %Y %H:%M:%S GMT";
|
||||
#endif
|
||||
|
||||
strftime(result, sizeof(result), format, last_modified);
|
||||
_last_modified = result;
|
||||
return *this;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(){
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified(time_t last_modified) {
|
||||
return setLastModified((struct tm*)gmtime(&last_modified));
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setLastModified() {
|
||||
time_t last_modified;
|
||||
if(time(&last_modified) == 0) //time is not yet set
|
||||
if (time(&last_modified) == 0) // time is not yet set
|
||||
return *this;
|
||||
return setLastModified(last_modified);
|
||||
}
|
||||
#endif
|
||||
bool AsyncStaticWebHandler::canHandle(AsyncWebServerRequest *request){
|
||||
if(request->method() != HTTP_GET
|
||||
|| !request->url().startsWith(_uri)
|
||||
|| !request->isExpectedRequestedConnType(RCT_DEFAULT, RCT_HTTP)
|
||||
){
|
||||
return false;
|
||||
}
|
||||
if (_getFile(request)) {
|
||||
// We interested in "If-Modified-Since" header to check if file was modified
|
||||
if (_last_modified.length())
|
||||
request->addInterestingHeader("If-Modified-Since");
|
||||
|
||||
if(_cache_control.length())
|
||||
request->addInterestingHeader("If-None-Match");
|
||||
|
||||
DEBUGF("[AsyncStaticWebHandler::canHandle] TRUE\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
bool AsyncStaticWebHandler::canHandle(AsyncWebServerRequest* request) const {
|
||||
return request->isHTTP() && request->method() == HTTP_GET && request->url().startsWith(_uri) && _getFile(request);
|
||||
}
|
||||
|
||||
bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest *request)
|
||||
{
|
||||
bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest* request) const {
|
||||
// Remove the found uri
|
||||
String path = request->url().substring(_uri.length());
|
||||
|
||||
// We can skip the file check and look for default if request is to the root of a directory or that request path ends with '/'
|
||||
bool canSkipFileCheck = (_isDir && path.length() == 0) || (path.length() && path[path.length()-1] == '/');
|
||||
bool canSkipFileCheck = (_isDir && path.length() == 0) || (path.length() && path[path.length() - 1] == '/');
|
||||
|
||||
path = _path + path;
|
||||
|
||||
// Do we have a file or .gz file
|
||||
if (!canSkipFileCheck && _fileExists(request, path))
|
||||
if (!canSkipFileCheck && const_cast<AsyncStaticWebHandler*>(this)->_searchFile(request, path))
|
||||
return true;
|
||||
|
||||
// Can't handle if not default file
|
||||
@ -121,39 +132,46 @@ bool AsyncStaticWebHandler::_getFile(AsyncWebServerRequest *request)
|
||||
return false;
|
||||
|
||||
// Try to add default file, ensure there is a trailing '/' ot the path.
|
||||
if (path.length() == 0 || path[path.length()-1] != '/')
|
||||
path += "/";
|
||||
if (path.length() == 0 || path[path.length() - 1] != '/')
|
||||
path += String('/');
|
||||
path += _default_file;
|
||||
|
||||
return _fileExists(request, path);
|
||||
return const_cast<AsyncStaticWebHandler*>(this)->_searchFile(request, path);
|
||||
}
|
||||
|
||||
#ifdef ESP32
|
||||
#define FILE_IS_REAL(f) (f == true && !f.isDirectory())
|
||||
#define FILE_IS_REAL(f) (f == true && !f.isDirectory())
|
||||
#else
|
||||
#define FILE_IS_REAL(f) (f == true)
|
||||
#define FILE_IS_REAL(f) (f == true)
|
||||
#endif
|
||||
|
||||
bool AsyncStaticWebHandler::_fileExists(AsyncWebServerRequest *request, const String& path)
|
||||
{
|
||||
bool AsyncStaticWebHandler::_searchFile(AsyncWebServerRequest* request, const String& path) {
|
||||
bool fileFound = false;
|
||||
bool gzipFound = false;
|
||||
|
||||
String gzip = path + ".gz";
|
||||
String gzip = path + T__gz;
|
||||
|
||||
if (_gzipFirst) {
|
||||
request->_tempFile = _fs.open(gzip, "r");
|
||||
gzipFound = FILE_IS_REAL(request->_tempFile);
|
||||
if (!gzipFound){
|
||||
request->_tempFile = _fs.open(path, "r");
|
||||
fileFound = FILE_IS_REAL(request->_tempFile);
|
||||
if (_tryGzipFirst) {
|
||||
if (_fs.exists(gzip)) {
|
||||
request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read);
|
||||
gzipFound = FILE_IS_REAL(request->_tempFile);
|
||||
}
|
||||
if (!gzipFound) {
|
||||
if (_fs.exists(path)) {
|
||||
request->_tempFile = _fs.open(path, fs::FileOpenMode::read);
|
||||
fileFound = FILE_IS_REAL(request->_tempFile);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
request->_tempFile = _fs.open(path, "r");
|
||||
fileFound = FILE_IS_REAL(request->_tempFile);
|
||||
if (!fileFound){
|
||||
request->_tempFile = _fs.open(gzip, "r");
|
||||
gzipFound = FILE_IS_REAL(request->_tempFile);
|
||||
if (_fs.exists(path)) {
|
||||
request->_tempFile = _fs.open(path, fs::FileOpenMode::read);
|
||||
fileFound = FILE_IS_REAL(request->_tempFile);
|
||||
}
|
||||
if (!fileFound) {
|
||||
if (_fs.exists(gzip)) {
|
||||
request->_tempFile = _fs.open(gzip, fs::FileOpenMode::read);
|
||||
gzipFound = FILE_IS_REAL(request->_tempFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -162,59 +180,134 @@ bool AsyncStaticWebHandler::_fileExists(AsyncWebServerRequest *request, const St
|
||||
if (found) {
|
||||
// Extract the file name from the path and keep it in _tempObject
|
||||
size_t pathLen = path.length();
|
||||
char * _tempPath = (char*)malloc(pathLen+1);
|
||||
snprintf(_tempPath, pathLen+1, "%s", path.c_str());
|
||||
char* _tempPath = (char*)malloc(pathLen + 1);
|
||||
snprintf_P(_tempPath, pathLen + 1, PSTR("%s"), path.c_str());
|
||||
request->_tempObject = (void*)_tempPath;
|
||||
|
||||
// Calculate gzip statistic
|
||||
_gzipStats = (_gzipStats << 1) + (gzipFound ? 1 : 0);
|
||||
if (_gzipStats == 0x00) _gzipFirst = false; // All files are not gzip
|
||||
else if (_gzipStats == 0xFF) _gzipFirst = true; // All files are gzip
|
||||
else _gzipFirst = _countBits(_gzipStats) > 4; // IF we have more gzip files - try gzip first
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
uint8_t AsyncStaticWebHandler::_countBits(const uint8_t value) const
|
||||
{
|
||||
uint8_t AsyncStaticWebHandler::_countBits(const uint8_t value) const {
|
||||
uint8_t w = value;
|
||||
uint8_t n;
|
||||
for (n=0; w!=0; n++) w&=w-1;
|
||||
for (n = 0; w != 0; n++)
|
||||
w &= w - 1;
|
||||
return n;
|
||||
}
|
||||
|
||||
void AsyncStaticWebHandler::handleRequest(AsyncWebServerRequest *request)
|
||||
{
|
||||
void AsyncStaticWebHandler::handleRequest(AsyncWebServerRequest* request) {
|
||||
// Get the filename from request->_tempObject and free it
|
||||
String filename = String((char*)request->_tempObject);
|
||||
String filename((char*)request->_tempObject);
|
||||
free(request->_tempObject);
|
||||
request->_tempObject = NULL;
|
||||
if((_username != "" && _password != "") && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
|
||||
if (request->_tempFile == true) {
|
||||
String etag = String(request->_tempFile.size());
|
||||
if (_last_modified.length() && _last_modified == request->header("If-Modified-Since")) {
|
||||
request->_tempFile.close();
|
||||
request->send(304); // Not modified
|
||||
} else if (_cache_control.length() && request->hasHeader("If-None-Match") && request->header("If-None-Match").equals(etag)) {
|
||||
request->_tempFile.close();
|
||||
AsyncWebServerResponse * response = new AsyncBasicResponse(304); // Not modified
|
||||
response->addHeader("Cache-Control", _cache_control);
|
||||
response->addHeader("ETag", etag);
|
||||
request->send(response);
|
||||
} else {
|
||||
AsyncWebServerResponse * response = new AsyncFileResponse(request->_tempFile, filename, String(), false, _callback);
|
||||
if (_last_modified.length())
|
||||
response->addHeader("Last-Modified", _last_modified);
|
||||
if (_cache_control.length()){
|
||||
response->addHeader("Cache-Control", _cache_control);
|
||||
response->addHeader("ETag", etag);
|
||||
}
|
||||
request->send(response);
|
||||
}
|
||||
} else {
|
||||
if (request->_tempFile != true){
|
||||
request->send(404);
|
||||
return;
|
||||
}
|
||||
|
||||
time_t lw = request->_tempFile.getLastWrite(); // get last file mod time (if supported by FS)
|
||||
// set etag to lastmod timestamp if available, otherwise to size
|
||||
String etag;
|
||||
if (lw) {
|
||||
setLastModified(lw);
|
||||
#if defined(TARGET_RP2040)
|
||||
// time_t == long long int
|
||||
constexpr size_t len = 1 + 8 * sizeof(time_t);
|
||||
char buf[len];
|
||||
char* ret = lltoa(lw ^ request->_tempFile.size(), buf, len, 10);
|
||||
etag = ret ? String(ret) : String(request->_tempFile.size());
|
||||
#else
|
||||
etag = lw ^ request->_tempFile.size(); // etag combines file size and lastmod timestamp
|
||||
#endif
|
||||
} else {
|
||||
etag = request->_tempFile.size();
|
||||
}
|
||||
|
||||
bool not_modified = false;
|
||||
|
||||
// if-none-match has precedence over if-modified-since
|
||||
if (request->hasHeader(T_INM))
|
||||
not_modified = request->header(T_INM).equals(etag);
|
||||
else if (_last_modified.length())
|
||||
not_modified = request->header(T_IMS).equals(_last_modified);
|
||||
|
||||
AsyncWebServerResponse* response;
|
||||
|
||||
if (not_modified){
|
||||
request->_tempFile.close();
|
||||
response = new AsyncBasicResponse(304); // Not modified
|
||||
} else {
|
||||
response = new AsyncFileResponse(request->_tempFile, filename, emptyString, false, _callback);
|
||||
}
|
||||
|
||||
response->addHeader(T_ETag, etag.c_str());
|
||||
|
||||
if (_last_modified.length())
|
||||
response->addHeader(T_Last_Modified, _last_modified.c_str());
|
||||
if (_cache_control.length())
|
||||
response->addHeader(T_Cache_Control, _cache_control.c_str());
|
||||
|
||||
request->send(response);
|
||||
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncStaticWebHandler::setTemplateProcessor(AwsTemplateProcessor newCallback) {
|
||||
_callback = newCallback;
|
||||
return *this;
|
||||
}
|
||||
|
||||
void AsyncCallbackWebHandler::setUri(const String& uri) {
|
||||
_uri = uri;
|
||||
_isRegex = uri.startsWith("^") && uri.endsWith("$");
|
||||
}
|
||||
|
||||
bool AsyncCallbackWebHandler::canHandle(AsyncWebServerRequest* request) const {
|
||||
if (!_onRequest || !request->isHTTP() || !(_method & request->method()))
|
||||
return false;
|
||||
|
||||
#ifdef ASYNCWEBSERVER_REGEX
|
||||
if (_isRegex) {
|
||||
std::regex pattern(_uri.c_str());
|
||||
std::smatch matches;
|
||||
std::string s(request->url().c_str());
|
||||
if (std::regex_search(s, matches, pattern)) {
|
||||
for (size_t i = 1; i < matches.size(); ++i) { // start from 1
|
||||
request->_addPathParam(matches[i].str().c_str());
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else
|
||||
#endif
|
||||
if (_uri.length() && _uri.startsWith("/*.")) {
|
||||
String uriTemplate = String(_uri);
|
||||
uriTemplate = uriTemplate.substring(uriTemplate.lastIndexOf("."));
|
||||
if (!request->url().endsWith(uriTemplate))
|
||||
return false;
|
||||
} else if (_uri.length() && _uri.endsWith("*")) {
|
||||
String uriTemplate = String(_uri);
|
||||
uriTemplate = uriTemplate.substring(0, uriTemplate.length() - 1);
|
||||
if (!request->url().startsWith(uriTemplate))
|
||||
return false;
|
||||
} else if (_uri.length() && (_uri != request->url() && !request->url().startsWith(_uri + "/")))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void AsyncCallbackWebHandler::handleRequest(AsyncWebServerRequest* request) {
|
||||
if (_onRequest)
|
||||
_onRequest(request);
|
||||
else
|
||||
request->send(500);
|
||||
}
|
||||
void AsyncCallbackWebHandler::handleUpload(AsyncWebServerRequest* request, const String& filename, size_t index, uint8_t* data, size_t len, bool final) {
|
||||
if (_onUpload)
|
||||
_onUpload(request, filename, index, data, len, final);
|
||||
}
|
||||
void AsyncCallbackWebHandler::handleBody(AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) {
|
||||
if (_onBody)
|
||||
_onBody(request, data, len, index, total);
|
||||
}
|
1183
src/WebRequest.cpp
1183
src/WebRequest.cpp
File diff suppressed because it is too large
Load Diff
@ -22,113 +22,137 @@
|
||||
#define ASYNCWEBSERVERRESPONSEIMPL_H_
|
||||
|
||||
#ifdef Arduino_h
|
||||
// arduino is not compatible with std::vector
|
||||
#undef min
|
||||
#undef max
|
||||
// arduino is not compatible with std::vector
|
||||
#undef min
|
||||
#undef max
|
||||
#endif
|
||||
#include "literals.h"
|
||||
#include <StreamString.h>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
// It is possible to restore these defines, but one can use _min and _max instead. Or std::min, std::max.
|
||||
|
||||
class AsyncBasicResponse: public AsyncWebServerResponse {
|
||||
class AsyncBasicResponse : public AsyncWebServerResponse {
|
||||
private:
|
||||
String _content;
|
||||
|
||||
public:
|
||||
AsyncBasicResponse(int code, const String& contentType=String(), const String& content=String());
|
||||
void _respond(AsyncWebServerRequest *request);
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time);
|
||||
bool _sourceValid() const { return true; }
|
||||
explicit AsyncBasicResponse(int code, const char* contentType = asyncsrv::empty, const char* content = asyncsrv::empty);
|
||||
AsyncBasicResponse(int code, const String& contentType, const String& content = emptyString) : AsyncBasicResponse(code, contentType.c_str(), content.c_str()) {}
|
||||
void _respond(AsyncWebServerRequest* request) override final;
|
||||
size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time) override final;
|
||||
bool _sourceValid() const override final { return true; }
|
||||
};
|
||||
|
||||
class AsyncAbstractResponse: public AsyncWebServerResponse {
|
||||
class AsyncAbstractResponse : public AsyncWebServerResponse {
|
||||
private:
|
||||
// amount of responce data in-flight, i.e. sent, but not acked yet
|
||||
size_t _in_flight{0};
|
||||
// in-flight queue credits
|
||||
size_t _in_flight_credit{2};
|
||||
String _head;
|
||||
// Data is inserted into cache at begin().
|
||||
// This is inefficient with vector, but if we use some other container,
|
||||
// Data is inserted into cache at begin().
|
||||
// This is inefficient with vector, but if we use some other container,
|
||||
// we won't be able to access it as contiguous array of bytes when reading from it,
|
||||
// so by gaining performance in one place, we'll lose it in another.
|
||||
std::vector<uint8_t> _cache;
|
||||
size_t _readDataFromCacheOrContent(uint8_t* data, const size_t len);
|
||||
size_t _fillBufferAndProcessTemplates(uint8_t* buf, size_t maxLen);
|
||||
|
||||
protected:
|
||||
AwsTemplateProcessor _callback;
|
||||
|
||||
public:
|
||||
AsyncAbstractResponse(AwsTemplateProcessor callback=nullptr);
|
||||
void _respond(AsyncWebServerRequest *request);
|
||||
size_t _ack(AsyncWebServerRequest *request, size_t len, uint32_t time);
|
||||
bool _sourceValid() const { return false; }
|
||||
virtual size_t _fillBuffer(uint8_t *buf __attribute__((unused)), size_t maxLen __attribute__((unused))) { return 0; }
|
||||
AsyncAbstractResponse(AwsTemplateProcessor callback = nullptr);
|
||||
virtual ~AsyncAbstractResponse() {}
|
||||
void _respond(AsyncWebServerRequest* request) override final;
|
||||
size_t _ack(AsyncWebServerRequest* request, size_t len, uint32_t time) override final;
|
||||
virtual bool _sourceValid() const { return false; }
|
||||
virtual size_t _fillBuffer(uint8_t* buf __attribute__((unused)), size_t maxLen __attribute__((unused))) { return 0; }
|
||||
};
|
||||
|
||||
#ifndef TEMPLATE_PLACEHOLDER
|
||||
#define TEMPLATE_PLACEHOLDER '%'
|
||||
#define TEMPLATE_PLACEHOLDER '%'
|
||||
#endif
|
||||
|
||||
#define TEMPLATE_PARAM_NAME_LENGTH 32
|
||||
class AsyncFileResponse: public AsyncAbstractResponse {
|
||||
using File = fs::File;
|
||||
using FS = fs::FS;
|
||||
class AsyncFileResponse : public AsyncAbstractResponse {
|
||||
using File = fs::File;
|
||||
using FS = fs::FS;
|
||||
|
||||
private:
|
||||
File _content;
|
||||
String _path;
|
||||
void _setContentType(const String& path);
|
||||
void _setContentTypeFromPath(const String& path);
|
||||
|
||||
public:
|
||||
AsyncFileResponse(FS &fs, const String& path, const String& contentType=String(), bool download=false, AwsTemplateProcessor callback=nullptr);
|
||||
AsyncFileResponse(File content, const String& path, const String& contentType=String(), bool download=false, AwsTemplateProcessor callback=nullptr);
|
||||
~AsyncFileResponse();
|
||||
bool _sourceValid() const { return !!(_content); }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
AsyncFileResponse(FS& fs, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
|
||||
AsyncFileResponse(FS& fs, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callback = nullptr) : AsyncFileResponse(fs, path, contentType.c_str(), download, callback) {}
|
||||
AsyncFileResponse(File content, const String& path, const char* contentType = asyncsrv::empty, bool download = false, AwsTemplateProcessor callback = nullptr);
|
||||
AsyncFileResponse(File content, const String& path, const String& contentType, bool download = false, AwsTemplateProcessor callack = nullptr) : AsyncFileResponse(content, path, contentType.c_str(), download, callack) {}
|
||||
~AsyncFileResponse() { _content.close(); }
|
||||
bool _sourceValid() const override final { return !!(_content); }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
};
|
||||
|
||||
class AsyncStreamResponse: public AsyncAbstractResponse {
|
||||
class AsyncStreamResponse : public AsyncAbstractResponse {
|
||||
private:
|
||||
Stream *_content;
|
||||
Stream* _content;
|
||||
|
||||
public:
|
||||
AsyncStreamResponse(Stream &stream, const String& contentType, size_t len, AwsTemplateProcessor callback=nullptr);
|
||||
bool _sourceValid() const { return !!(_content); }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
AsyncStreamResponse(Stream& stream, const char* contentType, size_t len, AwsTemplateProcessor callback = nullptr);
|
||||
AsyncStreamResponse(Stream& stream, const String& contentType, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncStreamResponse(stream, contentType.c_str(), len, callback) {}
|
||||
bool _sourceValid() const override final { return !!(_content); }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
};
|
||||
|
||||
class AsyncCallbackResponse: public AsyncAbstractResponse {
|
||||
class AsyncCallbackResponse : public AsyncAbstractResponse {
|
||||
private:
|
||||
AwsResponseFiller _content;
|
||||
size_t _filledLength;
|
||||
|
||||
public:
|
||||
AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback=nullptr);
|
||||
bool _sourceValid() const { return !!(_content); }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
AsyncCallbackResponse(const char* contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
|
||||
AsyncCallbackResponse(const String& contentType, size_t len, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncCallbackResponse(contentType.c_str(), len, callback, templateCallback) {}
|
||||
bool _sourceValid() const override final { return !!(_content); }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
};
|
||||
|
||||
class AsyncChunkedResponse: public AsyncAbstractResponse {
|
||||
class AsyncChunkedResponse : public AsyncAbstractResponse {
|
||||
private:
|
||||
AwsResponseFiller _content;
|
||||
size_t _filledLength;
|
||||
|
||||
public:
|
||||
AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback=nullptr);
|
||||
bool _sourceValid() const { return !!(_content); }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
AsyncChunkedResponse(const char* contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr);
|
||||
AsyncChunkedResponse(const String& contentType, AwsResponseFiller callback, AwsTemplateProcessor templateCallback = nullptr) : AsyncChunkedResponse(contentType.c_str(), callback, templateCallback) {}
|
||||
bool _sourceValid() const override final { return !!(_content); }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
};
|
||||
|
||||
class AsyncProgmemResponse: public AsyncAbstractResponse {
|
||||
class AsyncProgmemResponse : public AsyncAbstractResponse {
|
||||
private:
|
||||
const uint8_t * _content;
|
||||
const uint8_t* _content;
|
||||
size_t _readLength;
|
||||
|
||||
public:
|
||||
AsyncProgmemResponse(int code, const String& contentType, const uint8_t * content, size_t len, AwsTemplateProcessor callback=nullptr);
|
||||
bool _sourceValid() const { return true; }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
AsyncProgmemResponse(int code, const char* contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr);
|
||||
AsyncProgmemResponse(int code, const String& contentType, const uint8_t* content, size_t len, AwsTemplateProcessor callback = nullptr) : AsyncProgmemResponse(code, contentType.c_str(), content, len, callback) {}
|
||||
bool _sourceValid() const override final { return true; }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
};
|
||||
|
||||
class cbuf;
|
||||
|
||||
class AsyncResponseStream: public AsyncAbstractResponse, public Print {
|
||||
class AsyncResponseStream : public AsyncAbstractResponse, public Print {
|
||||
private:
|
||||
cbuf *_content;
|
||||
StreamString _content;
|
||||
|
||||
public:
|
||||
AsyncResponseStream(const String& contentType, size_t bufferSize);
|
||||
~AsyncResponseStream();
|
||||
bool _sourceValid() const { return (_state < RESPONSE_END); }
|
||||
virtual size_t _fillBuffer(uint8_t *buf, size_t maxLen) override;
|
||||
size_t write(const uint8_t *data, size_t len);
|
||||
AsyncResponseStream(const char* contentType, size_t bufferSize);
|
||||
AsyncResponseStream(const String& contentType, size_t bufferSize) : AsyncResponseStream(contentType.c_str(), bufferSize) {}
|
||||
bool _sourceValid() const override final { return (_state < RESPONSE_END); }
|
||||
size_t _fillBuffer(uint8_t* buf, size_t maxLen) override final;
|
||||
size_t write(const uint8_t* data, size_t len);
|
||||
size_t write(uint8_t data);
|
||||
using Print::write;
|
||||
};
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -21,110 +21,143 @@
|
||||
#include "ESPAsyncWebServer.h"
|
||||
#include "WebHandlerImpl.h"
|
||||
|
||||
bool ON_STA_FILTER(AsyncWebServerRequest *request) {
|
||||
using namespace asyncsrv;
|
||||
|
||||
bool ON_STA_FILTER(AsyncWebServerRequest* request) {
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
return WiFi.localIP() == request->client()->localIP();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
bool ON_AP_FILTER(AsyncWebServerRequest *request) {
|
||||
bool ON_AP_FILTER(AsyncWebServerRequest* request) {
|
||||
#ifndef CONFIG_IDF_TARGET_ESP32H2
|
||||
return WiFi.localIP() != request->client()->localIP();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifndef HAVE_FS_FILE_OPEN_MODE
|
||||
const char* fs::FileOpenMode::read = "r";
|
||||
const char* fs::FileOpenMode::write = "w";
|
||||
const char* fs::FileOpenMode::append = "a";
|
||||
#endif
|
||||
|
||||
AsyncWebServer::AsyncWebServer(uint16_t port)
|
||||
: _server(port)
|
||||
, _rewrites(LinkedList<AsyncWebRewrite*>([](AsyncWebRewrite* r){ delete r; }))
|
||||
, _handlers(LinkedList<AsyncWebHandler*>([](AsyncWebHandler* h){ delete h; }))
|
||||
{
|
||||
: _server(port) {
|
||||
_catchAllHandler = new AsyncCallbackWebHandler();
|
||||
if(_catchAllHandler == NULL)
|
||||
if (_catchAllHandler == NULL)
|
||||
return;
|
||||
_server.onClient([](void *s, AsyncClient* c){
|
||||
if(c == NULL)
|
||||
_server.onClient([](void* s, AsyncClient* c) {
|
||||
if (c == NULL)
|
||||
return;
|
||||
c->setRxTimeout(3);
|
||||
AsyncWebServerRequest *r = new AsyncWebServerRequest((AsyncWebServer*)s, c);
|
||||
if(r == NULL){
|
||||
c->close(true);
|
||||
c->free();
|
||||
AsyncWebServerRequest* r = new AsyncWebServerRequest((AsyncWebServer*)s, c);
|
||||
if (r == NULL) {
|
||||
c->abort();
|
||||
delete c;
|
||||
}
|
||||
}, this);
|
||||
},
|
||||
this);
|
||||
}
|
||||
|
||||
AsyncWebServer::~AsyncWebServer(){
|
||||
reset();
|
||||
AsyncWebServer::~AsyncWebServer() {
|
||||
reset();
|
||||
end();
|
||||
if(_catchAllHandler) delete _catchAllHandler;
|
||||
if (_catchAllHandler)
|
||||
delete _catchAllHandler;
|
||||
}
|
||||
|
||||
AsyncWebRewrite& AsyncWebServer::addRewrite(AsyncWebRewrite* rewrite){
|
||||
_rewrites.add(rewrite);
|
||||
return *rewrite;
|
||||
AsyncWebRewrite& AsyncWebServer::addRewrite(std::shared_ptr<AsyncWebRewrite> rewrite) {
|
||||
_rewrites.emplace_back(rewrite);
|
||||
return *_rewrites.back().get();
|
||||
}
|
||||
|
||||
bool AsyncWebServer::removeRewrite(AsyncWebRewrite *rewrite){
|
||||
return _rewrites.remove(rewrite);
|
||||
AsyncWebRewrite& AsyncWebServer::addRewrite(AsyncWebRewrite* rewrite) {
|
||||
_rewrites.emplace_back(rewrite);
|
||||
return *_rewrites.back().get();
|
||||
}
|
||||
|
||||
AsyncWebRewrite& AsyncWebServer::rewrite(const char* from, const char* to){
|
||||
return addRewrite(new AsyncWebRewrite(from, to));
|
||||
bool AsyncWebServer::removeRewrite(AsyncWebRewrite* rewrite) {
|
||||
return removeRewrite(rewrite->from().c_str(), rewrite->toUrl().c_str());
|
||||
}
|
||||
|
||||
AsyncWebHandler& AsyncWebServer::addHandler(AsyncWebHandler* handler){
|
||||
_handlers.add(handler);
|
||||
return *handler;
|
||||
bool AsyncWebServer::removeRewrite(const char* from, const char* to) {
|
||||
for (auto r = _rewrites.begin(); r != _rewrites.end(); ++r) {
|
||||
if (r->get()->from() == from && r->get()->toUrl() == to) {
|
||||
_rewrites.erase(r);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AsyncWebServer::removeHandler(AsyncWebHandler *handler){
|
||||
return _handlers.remove(handler);
|
||||
AsyncWebRewrite& AsyncWebServer::rewrite(const char* from, const char* to) {
|
||||
_rewrites.emplace_back(std::make_shared<AsyncWebRewrite>(from, to));
|
||||
return *_rewrites.back().get();
|
||||
}
|
||||
|
||||
void AsyncWebServer::begin(){
|
||||
AsyncWebHandler& AsyncWebServer::addHandler(AsyncWebHandler* handler) {
|
||||
_handlers.emplace_back(handler);
|
||||
return *(_handlers.back().get());
|
||||
}
|
||||
|
||||
bool AsyncWebServer::removeHandler(AsyncWebHandler* handler) {
|
||||
for (auto i = _handlers.begin(); i != _handlers.end(); ++i) {
|
||||
if (i->get() == handler) {
|
||||
_handlers.erase(i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void AsyncWebServer::begin() {
|
||||
_server.setNoDelay(true);
|
||||
_server.begin();
|
||||
}
|
||||
|
||||
void AsyncWebServer::end(){
|
||||
void AsyncWebServer::end() {
|
||||
_server.end();
|
||||
}
|
||||
|
||||
#if ASYNC_TCP_SSL_ENABLED
|
||||
void AsyncWebServer::onSslFileRequest(AcSSlFileHandler cb, void* arg){
|
||||
void AsyncWebServer::onSslFileRequest(AcSSlFileHandler cb, void* arg) {
|
||||
_server.onSslFileRequest(cb, arg);
|
||||
}
|
||||
|
||||
void AsyncWebServer::beginSecure(const char *cert, const char *key, const char *password){
|
||||
void AsyncWebServer::beginSecure(const char* cert, const char* key, const char* password) {
|
||||
_server.beginSecure(cert, key, password);
|
||||
}
|
||||
#endif
|
||||
|
||||
void AsyncWebServer::_handleDisconnect(AsyncWebServerRequest *request){
|
||||
void AsyncWebServer::_handleDisconnect(AsyncWebServerRequest* request) {
|
||||
delete request;
|
||||
}
|
||||
|
||||
void AsyncWebServer::_rewriteRequest(AsyncWebServerRequest *request){
|
||||
for(const auto& r: _rewrites){
|
||||
if (r->match(request)){
|
||||
void AsyncWebServer::_rewriteRequest(AsyncWebServerRequest* request) {
|
||||
for (const auto& r : _rewrites) {
|
||||
if (r->match(request)) {
|
||||
request->_url = r->toUrl();
|
||||
request->_addGetParams(r->params());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void AsyncWebServer::_attachHandler(AsyncWebServerRequest *request){
|
||||
for(const auto& h: _handlers){
|
||||
if (h->filter(request) && h->canHandle(request)){
|
||||
request->setHandler(h);
|
||||
void AsyncWebServer::_attachHandler(AsyncWebServerRequest* request) {
|
||||
for (auto& h : _handlers) {
|
||||
if (h->filter(request) && h->canHandle(request)) {
|
||||
request->setHandler(h.get());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
request->addInterestingHeader("ANY");
|
||||
|
||||
request->setHandler(_catchAllHandler);
|
||||
}
|
||||
|
||||
|
||||
AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody){
|
||||
AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody) {
|
||||
AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler();
|
||||
handler->setUri(uri);
|
||||
handler->setMethod(method);
|
||||
@ -135,59 +168,31 @@ AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodCom
|
||||
return *handler;
|
||||
}
|
||||
|
||||
AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload){
|
||||
AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler();
|
||||
handler->setUri(uri);
|
||||
handler->setMethod(method);
|
||||
handler->onRequest(onRequest);
|
||||
handler->onUpload(onUpload);
|
||||
addHandler(handler);
|
||||
return *handler;
|
||||
}
|
||||
|
||||
AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest){
|
||||
AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler();
|
||||
handler->setUri(uri);
|
||||
handler->setMethod(method);
|
||||
handler->onRequest(onRequest);
|
||||
addHandler(handler);
|
||||
return *handler;
|
||||
}
|
||||
|
||||
AsyncCallbackWebHandler& AsyncWebServer::on(const char* uri, ArRequestHandlerFunction onRequest){
|
||||
AsyncCallbackWebHandler* handler = new AsyncCallbackWebHandler();
|
||||
handler->setUri(uri);
|
||||
handler->onRequest(onRequest);
|
||||
addHandler(handler);
|
||||
return *handler;
|
||||
}
|
||||
|
||||
AsyncStaticWebHandler& AsyncWebServer::serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control){
|
||||
AsyncStaticWebHandler& AsyncWebServer::serveStatic(const char* uri, fs::FS& fs, const char* path, const char* cache_control) {
|
||||
AsyncStaticWebHandler* handler = new AsyncStaticWebHandler(uri, fs, path, cache_control);
|
||||
addHandler(handler);
|
||||
return *handler;
|
||||
}
|
||||
|
||||
void AsyncWebServer::onNotFound(ArRequestHandlerFunction fn){
|
||||
void AsyncWebServer::onNotFound(ArRequestHandlerFunction fn) {
|
||||
_catchAllHandler->onRequest(fn);
|
||||
}
|
||||
|
||||
void AsyncWebServer::onFileUpload(ArUploadHandlerFunction fn){
|
||||
void AsyncWebServer::onFileUpload(ArUploadHandlerFunction fn) {
|
||||
_catchAllHandler->onUpload(fn);
|
||||
}
|
||||
|
||||
void AsyncWebServer::onRequestBody(ArBodyHandlerFunction fn){
|
||||
void AsyncWebServer::onRequestBody(ArBodyHandlerFunction fn) {
|
||||
_catchAllHandler->onBody(fn);
|
||||
}
|
||||
|
||||
void AsyncWebServer::reset(){
|
||||
_rewrites.free();
|
||||
_handlers.free();
|
||||
|
||||
if (_catchAllHandler != NULL){
|
||||
void AsyncWebServer::reset() {
|
||||
_rewrites.clear();
|
||||
_handlers.clear();
|
||||
|
||||
if (_catchAllHandler != NULL) {
|
||||
_catchAllHandler->onRequest(NULL);
|
||||
_catchAllHandler->onUpload(NULL);
|
||||
_catchAllHandler->onBody(NULL);
|
||||
}
|
||||
}
|
||||
|
||||
|
627
src/edit.htm
627
src/edit.htm
@ -1,627 +0,0 @@
|
||||
<!--This is the plain html source of the hex encoded Editor-Page embedded in SPIFFSEditor.cpp -->
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>ESP Editor</title>
|
||||
<style type="text/css" media="screen">
|
||||
.cm {
|
||||
z-index: 300;
|
||||
position: absolute;
|
||||
left: 5px;
|
||||
border: 1px solid #444;
|
||||
background-color: #F5F5F5;
|
||||
display: none;
|
||||
box-shadow: 0 0 10px rgba( 0, 0, 0, .4 );
|
||||
font-size: 12px;
|
||||
font-family: sans-serif;
|
||||
font-weight:bold;
|
||||
}
|
||||
.cm ul {
|
||||
list-style: none;
|
||||
top: 0;
|
||||
left: 0;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.cm li {
|
||||
position: relative;
|
||||
min-width: 60px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.cm span {
|
||||
color: #444;
|
||||
display: inline-block;
|
||||
padding: 6px;
|
||||
}
|
||||
.cm li:hover { background: #444; }
|
||||
.cm li:hover span { color: #EEE; }
|
||||
.tvu ul, .tvu li {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.tvu input {
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
}
|
||||
.tvu {
|
||||
font: normal 12px Verdana, Arial, Sans-serif;
|
||||
-moz-user-select: none;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
color: #444;
|
||||
line-height: 16px;
|
||||
}
|
||||
.tvu span {
|
||||
margin-bottom:5px;
|
||||
padding: 0 0 0 18px;
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
height: 16px;
|
||||
vertical-align: middle;
|
||||
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADoSURBVBgZBcExblNBGAbA2ceegTRBuIKOgiihSZNTcC5LUHAihNJR0kGKCDcYJY6D3/77MdOinTvzAgCw8ysThIvn/VojIyMjIyPP+bS1sUQIV2s95pBDDvmbP/mdkft83tpYguZq5Jh/OeaYh+yzy8hTHvNlaxNNczm+la9OTlar1UdA/+C2A4trRCnD3jS8BB1obq2Gk6GU6QbQAS4BUaYSQAf4bhhKKTFdAzrAOwAxEUAH+KEM01SY3gM6wBsEAQB0gJ+maZoC3gI6iPYaAIBJsiRmHU0AALOeFC3aK2cWAACUXe7+AwO0lc9eTHYTAAAAAElFTkSuQmCC') no-repeat;
|
||||
background-position: 0px 0px;
|
||||
}
|
||||
.tvu span:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
@media screen and (-webkit-min-device-pixel-ratio:0){
|
||||
.tvu{
|
||||
-webkit-animation: webkit-adjacent-element-selector-bugfix infinite 1s;
|
||||
}
|
||||
|
||||
@-webkit-keyframes webkit-adjacent-element-selector-bugfix {
|
||||
from {
|
||||
padding: 0;
|
||||
}
|
||||
to {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
#uploader {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
left: 0;
|
||||
height:28px;
|
||||
line-height: 24px;
|
||||
padding-left: 10px;
|
||||
background-color: #444;
|
||||
color:#EEE;
|
||||
}
|
||||
#tree {
|
||||
position: absolute;
|
||||
top: 28px;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
width:160px;
|
||||
padding: 8px;
|
||||
}
|
||||
#editor, #preview {
|
||||
position: absolute;
|
||||
top: 28px;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 160px;
|
||||
border-left:1px solid #EEE;
|
||||
}
|
||||
#preview {
|
||||
background-color: #EEE;
|
||||
padding:5px;
|
||||
}
|
||||
#loader {
|
||||
position: absolute;
|
||||
top: 36%;
|
||||
right: 40%;
|
||||
}
|
||||
.loader {
|
||||
z-index: 10000;
|
||||
border: 8px solid #b5b5b5; /* Grey */
|
||||
border-top: 8px solid #3498db; /* Blue */
|
||||
border-bottom: 8px solid #3498db; /* Blue */
|
||||
border-radius: 50%;
|
||||
width: 240px;
|
||||
height: 240px;
|
||||
animation: spin 2s linear infinite;
|
||||
display:none;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
<script>
|
||||
if (typeof XMLHttpRequest === "undefined") {
|
||||
XMLHttpRequest = function () {
|
||||
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {}
|
||||
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {}
|
||||
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
|
||||
throw new Error("This browser does not support XMLHttpRequest.");
|
||||
};
|
||||
}
|
||||
|
||||
function ge(a){
|
||||
return document.getElementById(a);
|
||||
}
|
||||
function ce(a){
|
||||
return document.createElement(a);
|
||||
}
|
||||
|
||||
function sortByKey(array, key) {
|
||||
return array.sort(function(a, b) {
|
||||
var x = a[key]; var y = b[key];
|
||||
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
var QueuedRequester = function () {
|
||||
this.queue = [];
|
||||
this.running = false;
|
||||
this.xmlhttp = null;
|
||||
}
|
||||
QueuedRequester.prototype = {
|
||||
_request: function(req){
|
||||
this.running = true;
|
||||
if(!req instanceof Object) return;
|
||||
var that = this;
|
||||
|
||||
function ajaxCb(x,d){ return function(){
|
||||
if (x.readyState == 4){
|
||||
ge("loader").style.display = "none";
|
||||
d.callback(x.status, x.responseText);
|
||||
if(that.queue.length === 0) that.running = false;
|
||||
if(that.running) that._request(that.queue.shift());
|
||||
}
|
||||
}}
|
||||
|
||||
ge("loader").style.display = "block";
|
||||
|
||||
var p = "";
|
||||
if(req.params instanceof FormData){
|
||||
p = req.params;
|
||||
} else if(req.params instanceof Object){
|
||||
for (var key in req.params) {
|
||||
if(p === "")
|
||||
p += (req.method === "GET")?"?":"";
|
||||
else
|
||||
p += "&";
|
||||
p += encodeURIComponent(key)+"="+encodeURIComponent(req.params[key]);
|
||||
};
|
||||
}
|
||||
|
||||
this.xmlhttp = new XMLHttpRequest();
|
||||
this.xmlhttp.onreadystatechange = ajaxCb(this.xmlhttp, req);
|
||||
if(req.method === "GET"){
|
||||
this.xmlhttp.open(req.method, req.url+p, true);
|
||||
this.xmlhttp.send();
|
||||
} else {
|
||||
this.xmlhttp.open(req.method, req.url, true);
|
||||
if(p instanceof String)
|
||||
this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
|
||||
this.xmlhttp.send(p);
|
||||
}
|
||||
},
|
||||
stop: function(){
|
||||
if(this.running) this.running = false;
|
||||
if(this.xmlhttp && this.xmlhttp.readyState < 4){
|
||||
this.xmlhttp.abort();
|
||||
}
|
||||
},
|
||||
add: function(method, url, params, callback){
|
||||
this.queue.push({url:url,method:method,params:params,callback:callback});
|
||||
if(!this.running){
|
||||
this._request(this.queue.shift());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var requests = new QueuedRequester();
|
||||
|
||||
function createFileUploader(element, tree, editor){
|
||||
var xmlHttp;
|
||||
|
||||
var refresh = ce("button");
|
||||
refresh.innerHTML = 'Refresh List';
|
||||
ge(element).appendChild(refresh);
|
||||
|
||||
var input = ce("input");
|
||||
input.type = "file";
|
||||
input.multiple = false;
|
||||
input.name = "data";
|
||||
input.id="upload-select";
|
||||
ge(element).appendChild(input);
|
||||
|
||||
var path = ce("input");
|
||||
path.id = "upload-path";
|
||||
path.type = "text";
|
||||
path.name = "path";
|
||||
path.defaultValue = "/";
|
||||
ge(element).appendChild(path);
|
||||
|
||||
var button = ce("button");
|
||||
button.innerHTML = 'Upload';
|
||||
ge(element).appendChild(button);
|
||||
|
||||
var mkfile = ce("button");
|
||||
mkfile.innerHTML = 'Create';
|
||||
ge(element).appendChild(mkfile);
|
||||
|
||||
var filename = ce("input");
|
||||
filename.id = "editor-filename";
|
||||
filename.type = "text";
|
||||
filename.disabled= true;
|
||||
filename.size = 20;
|
||||
ge(element).appendChild(filename);
|
||||
|
||||
var savefile = ce("button");
|
||||
savefile.innerHTML = ' Save ' ;
|
||||
ge(element).appendChild(savefile);
|
||||
|
||||
function httpPostProcessRequest(status, responseText){
|
||||
if(status != 200)
|
||||
alert("ERROR["+status+"]: "+responseText);
|
||||
else
|
||||
tree.refreshPath(path.value);
|
||||
}
|
||||
function createPath(p){
|
||||
var formData = new FormData();
|
||||
formData.append("path", p);
|
||||
requests.add("PUT", "/edit", formData, httpPostProcessRequest);
|
||||
}
|
||||
|
||||
mkfile.onclick = function(e){
|
||||
createPath(path.value);
|
||||
editor.loadUrl(path.value);
|
||||
path.value="/";
|
||||
};
|
||||
|
||||
savefile.onclick = function(e){
|
||||
editor.execCommand('saveCommand');
|
||||
};
|
||||
|
||||
refresh.onclick = function(e){
|
||||
tree.refreshPath(path.value);
|
||||
};
|
||||
|
||||
button.onclick = function(e){
|
||||
if(input.files.length === 0){
|
||||
return;
|
||||
}
|
||||
var formData = new FormData();
|
||||
formData.append("data", input.files[0], path.value);
|
||||
requests.add("POST", "/edit", formData, httpPostProcessRequest);
|
||||
var uploadPath= ge("upload-path");
|
||||
uploadPath.value="/";
|
||||
var uploadSelect= ge("upload-select");
|
||||
uploadSelect.value="";
|
||||
};
|
||||
input.onchange = function(e){
|
||||
if(input.files.length === 0) return;
|
||||
var filename = input.files[0].name;
|
||||
var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
|
||||
var name = /(.*)\.[^.]+$/.exec(filename)[1];
|
||||
if(typeof name !== undefined){
|
||||
filename = name;
|
||||
}
|
||||
path.value = "/"+filename+"."+ext;
|
||||
};
|
||||
}
|
||||
|
||||
function createTree(element, editor){
|
||||
var preview = ge("preview");
|
||||
var treeRoot = ce("div");
|
||||
treeRoot.className = "tvu";
|
||||
ge(element).appendChild(treeRoot);
|
||||
|
||||
function loadDownload(path){
|
||||
ge('download-frame').src = "/edit?download="+path;
|
||||
}
|
||||
|
||||
function loadPreview(path){
|
||||
var edfname = ge("editor-filename");
|
||||
edfname.value=path;
|
||||
ge("editor").style.display = "none";
|
||||
preview.style.display = "block";
|
||||
preview.innerHTML = '<img src="/edit?edit='+path+'&_cb='+Date.now()+'" style="max-width:100%; max-height:100%; margin:auto; display:block;" />';
|
||||
}
|
||||
|
||||
function fillFileMenu(el, path){
|
||||
var list = ce("ul");
|
||||
el.appendChild(list);
|
||||
var action = ce("li");
|
||||
list.appendChild(action);
|
||||
if(isImageFile(path)){
|
||||
action.innerHTML = "<span>Preview</span>";
|
||||
action.onclick = function(e){
|
||||
loadPreview(path);
|
||||
if(document.body.getElementsByClassName('cm').length > 0) document.body.removeChild(el);
|
||||
};
|
||||
} else if(isTextFile(path)){
|
||||
action.innerHTML = "<span>Edit</span>";
|
||||
action.onclick = function(e){
|
||||
editor.loadUrl(path);
|
||||
if(document.body.getElementsByClassName('cm').length > 0) document.body.removeChild(el);
|
||||
};
|
||||
}
|
||||
var download = ce("li");
|
||||
list.appendChild(download);
|
||||
download.innerHTML = "<span>Download</span>";
|
||||
download.onclick = function(e){
|
||||
loadDownload(path);
|
||||
if(document.body.getElementsByClassName('cm').length > 0) document.body.removeChild(el);
|
||||
};
|
||||
var delFile = ce("li");
|
||||
list.appendChild(delFile);
|
||||
delFile.innerHTML = "<span>Delete</span>";
|
||||
delFile.onclick = function(e){
|
||||
httpDelete(path);
|
||||
if(document.body.getElementsByClassName('cm').length > 0) document.body.removeChild(el);
|
||||
};
|
||||
}
|
||||
|
||||
function showContextMenu(event, path, isfile){
|
||||
var divContext = ce("div");
|
||||
var scrollTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
|
||||
var scrollLeft = document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
|
||||
var left = event.clientX + scrollLeft;
|
||||
var top = event.clientY + scrollTop;
|
||||
divContext.className = 'cm';
|
||||
divContext.style.display = 'block';
|
||||
divContext.style.left = left + 'px';
|
||||
divContext.style.top = top + 'px';
|
||||
fillFileMenu(divContext, path);
|
||||
document.body.appendChild(divContext);
|
||||
var width = divContext.offsetWidth;
|
||||
var height = divContext.offsetHeight;
|
||||
divContext.onmouseout = function(e){
|
||||
if(e.clientX < left || e.clientX > (left + width) || e.clientY < top || e.clientY > (top + height)){
|
||||
if(document.body.getElementsByClassName('cm').length > 0) document.body.removeChild(divContext);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createTreeLeaf(path, name, size){
|
||||
var leaf = ce("li");
|
||||
leaf.id = name;
|
||||
var label = ce("span");
|
||||
label.innerHTML = name;
|
||||
leaf.appendChild(label);
|
||||
leaf.onclick = function(e){
|
||||
if(isTextFile(leaf.id.toLowerCase())){
|
||||
editor.loadUrl(leaf.id);
|
||||
} else if(isImageFile(leaf.id.toLowerCase())){
|
||||
loadPreview(leaf.id);
|
||||
}
|
||||
};
|
||||
leaf.oncontextmenu = function(e){
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
showContextMenu(e, leaf.id, true);
|
||||
};
|
||||
return leaf;
|
||||
}
|
||||
|
||||
function addList(parent, path, items){
|
||||
sortByKey(items, 'name');
|
||||
var list = ce("ul");
|
||||
parent.appendChild(list);
|
||||
var ll = items.length;
|
||||
for(var i = 0; i < ll; i++){
|
||||
if(items[i].type === "file")
|
||||
list.appendChild(createTreeLeaf(path, items[i].name, items[i].size));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function isTextFile(path){
|
||||
var ext = /(?:\.([^.]+))?$/.exec(path)[1];
|
||||
if(typeof ext !== undefined){
|
||||
switch(ext){
|
||||
case "txt":
|
||||
case "htm":
|
||||
case "html":
|
||||
case "js":
|
||||
case "css":
|
||||
case "xml":
|
||||
case "json":
|
||||
case "conf":
|
||||
case "ini":
|
||||
case "h":
|
||||
case "c":
|
||||
case "cpp":
|
||||
case "php":
|
||||
case "hex":
|
||||
case "ino":
|
||||
case "pde":
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isImageFile(path){
|
||||
var ext = /(?:\.([^.]+))?$/.exec(path)[1];
|
||||
if(typeof ext !== undefined){
|
||||
switch(ext){
|
||||
case "png":
|
||||
case "jpg":
|
||||
case "gif":
|
||||
case "bmp":
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
this.refreshPath = function(path){
|
||||
treeRoot.removeChild(treeRoot.childNodes[0]);
|
||||
httpGet(treeRoot, "/");
|
||||
};
|
||||
|
||||
function delCb(path){
|
||||
return function(status, responseText){
|
||||
if(status != 200){
|
||||
alert("ERROR["+status+"]: "+responseText);
|
||||
} else {
|
||||
treeRoot.removeChild(treeRoot.childNodes[0]);
|
||||
httpGet(treeRoot, "/");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function httpDelete(filename){
|
||||
var formData = new FormData();
|
||||
formData.append("path", filename);
|
||||
requests.add("DELETE", "/edit", formData, delCb(filename));
|
||||
}
|
||||
|
||||
function getCb(parent, path){
|
||||
return function(status, responseText){
|
||||
if(status == 200)
|
||||
addList(parent, path, JSON.parse(responseText));
|
||||
}
|
||||
}
|
||||
|
||||
function httpGet(parent, path){
|
||||
requests.add("GET", "/edit", { list: path }, getCb(parent, path));
|
||||
}
|
||||
|
||||
httpGet(treeRoot, "/");
|
||||
return this;
|
||||
}
|
||||
|
||||
function createEditor(element, file, lang, theme, type){
|
||||
function getLangFromFilename(filename){
|
||||
var lang = "plain";
|
||||
var ext = /(?:\.([^.]+))?$/.exec(filename)[1];
|
||||
if(typeof ext !== undefined){
|
||||
switch(ext){
|
||||
case "txt": lang = "plain"; break;
|
||||
case "hex": lang = "plain"; break;
|
||||
case "conf": lang = "plain"; break;
|
||||
case "htm": lang = "html"; break;
|
||||
case "js": lang = "javascript"; break;
|
||||
case "h": lang = "c_cpp"; break;
|
||||
case "c": lang = "c_cpp"; break;
|
||||
case "cpp": lang = "c_cpp"; break;
|
||||
case "css":
|
||||
case "scss":
|
||||
case "php":
|
||||
case "html":
|
||||
case "json":
|
||||
case "xml":
|
||||
case "ini": lang = ext;
|
||||
}
|
||||
}
|
||||
return lang;
|
||||
}
|
||||
|
||||
if(typeof file === "undefined") file = "/index.html";
|
||||
|
||||
if(typeof lang === "undefined"){
|
||||
lang = getLangFromFilename(file);
|
||||
}
|
||||
|
||||
if(typeof theme === "undefined") theme = "textmate";
|
||||
|
||||
if(typeof type === "undefined"){
|
||||
type = "text/"+lang;
|
||||
if(lang === "c_cpp") type = "text/plain";
|
||||
}
|
||||
|
||||
var editor = ace.edit(element);
|
||||
function httpPostProcessRequest(status, responseText){
|
||||
if(status != 200) alert("ERROR["+status+"]: "+responseText);
|
||||
}
|
||||
function httpPost(filename, data, type){
|
||||
var formData = new FormData();
|
||||
formData.append("data", new Blob([data], { type: type }), filename);
|
||||
requests.add("POST", "/edit", formData, httpPostProcessRequest);
|
||||
}
|
||||
function httpGetProcessRequest(status, responseText){
|
||||
ge("preview").style.display = "none";
|
||||
ge("editor").style.display = "block";
|
||||
if(status == 200)
|
||||
editor.setValue(responseText);
|
||||
else
|
||||
editor.setValue("");
|
||||
editor.clearSelection();
|
||||
}
|
||||
function httpGet(theUrl){
|
||||
requests.add("GET", "/edit", { edit: theUrl }, httpGetProcessRequest);
|
||||
}
|
||||
|
||||
if(lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
|
||||
editor.setTheme("ace/theme/"+theme);
|
||||
editor.$blockScrolling = Infinity;
|
||||
editor.getSession().setUseSoftTabs(true);
|
||||
editor.getSession().setTabSize(2);
|
||||
editor.setHighlightActiveLine(true);
|
||||
editor.setShowPrintMargin(false);
|
||||
editor.commands.addCommand({
|
||||
name: 'saveCommand',
|
||||
bindKey: {win: 'Ctrl-S', mac: 'Command-S'},
|
||||
exec: function(editor) {
|
||||
httpPost(file, editor.getValue()+"", type);
|
||||
},
|
||||
readOnly: false
|
||||
});
|
||||
editor.commands.addCommand({
|
||||
name: 'undoCommand',
|
||||
bindKey: {win: 'Ctrl-Z', mac: 'Command-Z'},
|
||||
exec: function(editor) {
|
||||
editor.getSession().getUndoManager().undo(false);
|
||||
},
|
||||
readOnly: false
|
||||
});
|
||||
editor.commands.addCommand({
|
||||
name: 'redoCommand',
|
||||
bindKey: {win: 'Ctrl-Shift-Z', mac: 'Command-Shift-Z'},
|
||||
exec: function(editor) {
|
||||
editor.getSession().getUndoManager().redo(false);
|
||||
},
|
||||
readOnly: false
|
||||
});
|
||||
editor.loadUrl = function(filename){
|
||||
var edfname = ge("editor-filename");
|
||||
edfname.value=filename;
|
||||
file = filename;
|
||||
lang = getLangFromFilename(file);
|
||||
type = "text/"+lang;
|
||||
if(lang !== "plain") editor.getSession().setMode("ace/mode/"+lang);
|
||||
httpGet(file);
|
||||
};
|
||||
return editor;
|
||||
}
|
||||
function onBodyLoad(){
|
||||
var vars = {};
|
||||
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; });
|
||||
var editor = createEditor("editor", vars.file, vars.lang, vars.theme);
|
||||
var tree = createTree("tree", editor);
|
||||
createFileUploader("uploader", tree, editor);
|
||||
if(typeof vars.file === "undefined") vars.file = "/index.htm";
|
||||
editor.loadUrl(vars.file);
|
||||
};
|
||||
</script>
|
||||
<script id='ace' src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.6/ace.js" type="text/javascript" charset="utf-8"></script>
|
||||
<script>
|
||||
if (typeof ace.edit == "undefined") {
|
||||
var script = document.createElement('script');
|
||||
script.src = "/ace.js";
|
||||
script.async = false;
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body onload="onBodyLoad();">
|
||||
<div id="loader" class="loader"></div>
|
||||
<div id="uploader"></div>
|
||||
<div id="tree"></div>
|
||||
<div id="editor"></div>
|
||||
<div id="preview" style="display:none;"></div>
|
||||
<iframe id=download-frame style='display:none;'></iframe>
|
||||
</body>
|
||||
</html>
|
183
src/literals.h
Normal file
183
src/literals.h
Normal file
@ -0,0 +1,183 @@
|
||||
#pragma once
|
||||
|
||||
namespace asyncsrv {
|
||||
|
||||
static constexpr const char* empty = "";
|
||||
|
||||
static constexpr const char* T__opaque = "\", opaque=\"";
|
||||
static constexpr const char* T_100_CONTINUE = "100-continue";
|
||||
static constexpr const char* T_13 = "13";
|
||||
static constexpr const char* T_ACCEPT = "accept";
|
||||
static constexpr const char* T_Accept_Ranges = "accept-ranges";
|
||||
static constexpr const char* T_app_xform_urlencoded = "application/x-www-form-urlencoded";
|
||||
static constexpr const char* T_AUTH = "authorization";
|
||||
static constexpr const char* T_auth_nonce = "\", qop=\"auth\", nonce=\"";
|
||||
static constexpr const char* T_BASIC = "basic";
|
||||
static constexpr const char* T_BASIC_REALM = "basic realm=\"";
|
||||
static constexpr const char* T_BEARER = "bearer";
|
||||
static constexpr const char* T_BODY = "body";
|
||||
static constexpr const char* T_Cache_Control = "cache-control";
|
||||
static constexpr const char* T_chunked = "chunked";
|
||||
static constexpr const char* T_close = "close";
|
||||
static constexpr const char* T_cnonce = "cnonce";
|
||||
static constexpr const char* T_Connection = "connection";
|
||||
static constexpr const char* T_Content_Disposition = "content-disposition";
|
||||
static constexpr const char* T_Content_Encoding = "content-encoding";
|
||||
static constexpr const char* T_Content_Length = "content-length";
|
||||
static constexpr const char* T_Content_Type = "content-type";
|
||||
static constexpr const char* T_Cookie = "cookie";
|
||||
static constexpr const char* T_CORS_ACAC = "access-control-allow-credentials";
|
||||
static constexpr const char* T_CORS_ACAH = "access-control-allow-headers";
|
||||
static constexpr const char* T_CORS_ACAM = "access-control-allow-methods";
|
||||
static constexpr const char* T_CORS_ACAO = "access-control-allow-origin";
|
||||
static constexpr const char* T_CORS_ACMA = "access-control-max-age";
|
||||
static constexpr const char* T_CORS_O = "origin";
|
||||
static constexpr const char* T_data_ = "data: ";
|
||||
static constexpr const char* T_DIGEST = "digest";
|
||||
static constexpr const char* T_DIGEST_ = "digest ";
|
||||
static constexpr const char* T_ETag = "etag";
|
||||
static constexpr const char* T_event_ = "event: ";
|
||||
static constexpr const char* T_EXPECT = "expect";
|
||||
static constexpr const char* T_FALSE = "false";
|
||||
static constexpr const char* T_filename = "filename";
|
||||
static constexpr const char* T_gzip = "gzip";
|
||||
static constexpr const char* T_Host = "host";
|
||||
static constexpr const char* T_HTTP_1_0 = "HTTP/1.0";
|
||||
static constexpr const char* T_HTTP_100_CONT = "HTTP/1.1 100 Continue\r\n\r\n";
|
||||
static constexpr const char* T_id__ = "id: ";
|
||||
static constexpr const char* T_IMS = "if-modified-since";
|
||||
static constexpr const char* T_INM = "if-none-match";
|
||||
static constexpr const char* T_keep_alive = "keep-alive";
|
||||
static constexpr const char* T_Last_Event_ID = "last-event-id";
|
||||
static constexpr const char* T_Last_Modified = "last-modified";
|
||||
static constexpr const char* T_LOCATION = "location";
|
||||
static constexpr const char* T_LOGIN_REQ = "Login Required";
|
||||
static constexpr const char* T_MULTIPART_ = "multipart/";
|
||||
static constexpr const char* T_name = "name";
|
||||
static constexpr const char* T_nc = "nc";
|
||||
static constexpr const char* T_no_cache = "no-cache";
|
||||
static constexpr const char* T_nonce = "nonce";
|
||||
static constexpr const char* T_none = "none";
|
||||
static constexpr const char* T_opaque = "opaque";
|
||||
static constexpr const char* T_qop = "qop";
|
||||
static constexpr const char* T_realm = "realm";
|
||||
static constexpr const char* T_realm__ = "realm=\"";
|
||||
static constexpr const char* T_response = "response";
|
||||
static constexpr const char* T_retry_ = "retry: ";
|
||||
static constexpr const char* T_retry_after = "retry-after";
|
||||
static constexpr const char* T_nn = "\n\n";
|
||||
static constexpr const char* T_rn = "\r\n";
|
||||
static constexpr const char* T_rnrn = "\r\n\r\n";
|
||||
static constexpr const char* T_Transfer_Encoding = "transfer-encoding";
|
||||
static constexpr const char* T_TRUE = "true";
|
||||
static constexpr const char* T_UPGRADE = "upgrade";
|
||||
static constexpr const char* T_uri = "uri";
|
||||
static constexpr const char* T_username = "username";
|
||||
static constexpr const char* T_WS = "websocket";
|
||||
static constexpr const char* T_WWW_AUTH = "www-authenticate";
|
||||
|
||||
// HTTP Methods
|
||||
|
||||
static constexpr const char* T_ANY = "ANY";
|
||||
static constexpr const char* T_GET = "GET";
|
||||
static constexpr const char* T_POST = "POST";
|
||||
static constexpr const char* T_PUT = "PUT";
|
||||
static constexpr const char* T_DELETE = "DELETE";
|
||||
static constexpr const char* T_PATCH = "PATCH";
|
||||
static constexpr const char* T_HEAD = "HEAD";
|
||||
static constexpr const char* T_OPTIONS = "OPTIONS";
|
||||
static constexpr const char* T_UNKNOWN = "UNKNOWN";
|
||||
|
||||
// Req content types
|
||||
static constexpr const char* T_RCT_NOT_USED = "RCT_NOT_USED";
|
||||
static constexpr const char* T_RCT_DEFAULT = "RCT_DEFAULT";
|
||||
static constexpr const char* T_RCT_HTTP = "RCT_HTTP";
|
||||
static constexpr const char* T_RCT_WS = "RCT_WS";
|
||||
static constexpr const char* T_RCT_EVENT = "RCT_EVENT";
|
||||
static constexpr const char* T_ERROR = "ERROR";
|
||||
|
||||
// extentions & MIME-Types
|
||||
static constexpr const char* T__css = ".css";
|
||||
static constexpr const char* T__eot = ".eot";
|
||||
static constexpr const char* T__gif = ".gif";
|
||||
static constexpr const char* T__gz = ".gz";
|
||||
static constexpr const char* T__htm = ".htm";
|
||||
static constexpr const char* T__html = ".html";
|
||||
static constexpr const char* T__ico = ".ico";
|
||||
static constexpr const char* T__jpg = ".jpg";
|
||||
static constexpr const char* T__js = ".js";
|
||||
static constexpr const char* T__json = ".json";
|
||||
static constexpr const char* T__pdf = ".pdf";
|
||||
static constexpr const char* T__png = ".png";
|
||||
static constexpr const char* T__svg = ".svg";
|
||||
static constexpr const char* T__ttf = ".ttf";
|
||||
static constexpr const char* T__woff = ".woff";
|
||||
static constexpr const char* T__woff2 = ".woff2";
|
||||
static constexpr const char* T__xml = ".xml";
|
||||
static constexpr const char* T__zip = ".zip";
|
||||
static constexpr const char* T_application_javascript = "application/javascript";
|
||||
static constexpr const char* T_application_json = "application/json";
|
||||
static constexpr const char* T_application_msgpack = "application/msgpack";
|
||||
static constexpr const char* T_application_pdf = "application/pdf";
|
||||
static constexpr const char* T_application_x_gzip = "application/x-gzip";
|
||||
static constexpr const char* T_application_zip = "application/zip";
|
||||
static constexpr const char* T_font_eot = "font/eot";
|
||||
static constexpr const char* T_font_ttf = "font/ttf";
|
||||
static constexpr const char* T_font_woff = "font/woff";
|
||||
static constexpr const char* T_font_woff2 = "font/woff2";
|
||||
static constexpr const char* T_image_gif = "image/gif";
|
||||
static constexpr const char* T_image_jpeg = "image/jpeg";
|
||||
static constexpr const char* T_image_png = "image/png";
|
||||
static constexpr const char* T_image_svg_xml = "image/svg+xml";
|
||||
static constexpr const char* T_image_x_icon = "image/x-icon";
|
||||
static constexpr const char* T_text_css = "text/css";
|
||||
static constexpr const char* T_text_event_stream = "text/event-stream";
|
||||
static constexpr const char* T_text_html = "text/html";
|
||||
static constexpr const char* T_text_plain = "text/plain";
|
||||
static constexpr const char* T_text_xml = "text/xml";
|
||||
|
||||
// Responce codes
|
||||
static constexpr const char* T_HTTP_CODE_100 = "Continue";
|
||||
static constexpr const char* T_HTTP_CODE_101 = "Switching Protocols";
|
||||
static constexpr const char* T_HTTP_CODE_200 = "OK";
|
||||
static constexpr const char* T_HTTP_CODE_201 = "Created";
|
||||
static constexpr const char* T_HTTP_CODE_202 = "Accepted";
|
||||
static constexpr const char* T_HTTP_CODE_203 = "Non-Authoritative Information";
|
||||
static constexpr const char* T_HTTP_CODE_204 = "No Content";
|
||||
static constexpr const char* T_HTTP_CODE_205 = "Reset Content";
|
||||
static constexpr const char* T_HTTP_CODE_206 = "Partial Content";
|
||||
static constexpr const char* T_HTTP_CODE_300 = "Multiple Choices";
|
||||
static constexpr const char* T_HTTP_CODE_301 = "Moved Permanently";
|
||||
static constexpr const char* T_HTTP_CODE_302 = "Found";
|
||||
static constexpr const char* T_HTTP_CODE_303 = "See Other";
|
||||
static constexpr const char* T_HTTP_CODE_304 = "Not Modified";
|
||||
static constexpr const char* T_HTTP_CODE_305 = "Use Proxy";
|
||||
static constexpr const char* T_HTTP_CODE_307 = "Temporary Redirect";
|
||||
static constexpr const char* T_HTTP_CODE_400 = "Bad Request";
|
||||
static constexpr const char* T_HTTP_CODE_401 = "Unauthorized";
|
||||
static constexpr const char* T_HTTP_CODE_402 = "Payment Required";
|
||||
static constexpr const char* T_HTTP_CODE_403 = "Forbidden";
|
||||
static constexpr const char* T_HTTP_CODE_404 = "Not Found";
|
||||
static constexpr const char* T_HTTP_CODE_405 = "Method Not Allowed";
|
||||
static constexpr const char* T_HTTP_CODE_406 = "Not Acceptable";
|
||||
static constexpr const char* T_HTTP_CODE_407 = "Proxy Authentication Required";
|
||||
static constexpr const char* T_HTTP_CODE_408 = "Request Time-out";
|
||||
static constexpr const char* T_HTTP_CODE_409 = "Conflict";
|
||||
static constexpr const char* T_HTTP_CODE_410 = "Gone";
|
||||
static constexpr const char* T_HTTP_CODE_411 = "Length Required";
|
||||
static constexpr const char* T_HTTP_CODE_412 = "Precondition Failed";
|
||||
static constexpr const char* T_HTTP_CODE_413 = "Request Entity Too Large";
|
||||
static constexpr const char* T_HTTP_CODE_414 = "Request-URI Too Large";
|
||||
static constexpr const char* T_HTTP_CODE_415 = "Unsupported Media Type";
|
||||
static constexpr const char* T_HTTP_CODE_416 = "Requested range not satisfiable";
|
||||
static constexpr const char* T_HTTP_CODE_417 = "Expectation Failed";
|
||||
static constexpr const char* T_HTTP_CODE_429 = "Too Many Requests";
|
||||
static constexpr const char* T_HTTP_CODE_500 = "Internal Server Error";
|
||||
static constexpr const char* T_HTTP_CODE_501 = "Not Implemented";
|
||||
static constexpr const char* T_HTTP_CODE_502 = "Bad Gateway";
|
||||
static constexpr const char* T_HTTP_CODE_503 = "Service Unavailable";
|
||||
static constexpr const char* T_HTTP_CODE_504 = "Gateway Time-out";
|
||||
static constexpr const char* T_HTTP_CODE_505 = "HTTP Version not supported";
|
||||
static constexpr const char* T_HTTP_CODE_ANY = "Unknown code";
|
||||
|
||||
} // namespace asyncsrv {}
|
Reference in New Issue
Block a user