diff --git a/.github/scripts/install-arduino-ide.sh b/.github/scripts/install-arduino-ide.sh index eacf55bc..902c95b9 100755 --- a/.github/scripts/install-arduino-ide.sh +++ b/.github/scripts/install-arduino-ide.sh @@ -98,8 +98,8 @@ function build_sketch(){ # build_sketch [extra-options] 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")"' ..." + #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 \ @@ -131,14 +131,14 @@ function count_sketches() # count_sketches local sketchdir=$(dirname $sketch) local sketchdirname=$(basename $sketchdir) local sketchname=$(basename $sketch) - if [[ "${sketchdirname}.ino" != "$sketchname" ]]; then + if [[ "$sketchdirname.ino" != "$sketchname" ]]; then continue - fi; - if [[ -f "$sketchdir/.skip.$target" ]]; then + elif [[ -f "$sketchdir/.skip.$target" ]]; then continue + else + echo $sketch >> sketches.txt + sketchnum=$(($sketchnum + 1)) fi - echo $sketch >> sketches.txt - sketchnum=$(($sketchnum + 1)) done return $sketchnum } @@ -168,13 +168,13 @@ function build_sketches() # build_sketches < echo "ERROR: Chunks count must be positive number" return 1 fi - if [ "$chunk_idex" -ge "$chunks_num" ]; then + if [ "$chunk_idex" -ge "$chunks_num" ] && [ "$chunks_num" -ge 2 ]; then echo "ERROR: Chunk index must be less than chunks count" return 1 fi set +e - count_sketches "$examples" + count_sketches "$examples" "$target" local sketchcount=$? set -e local sketches=$(cat sketches.txt) @@ -186,19 +186,27 @@ function build_sketches() # build_sketches < 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 + local start_index=0 + local end_index=0 + if [ "$chunk_idex" -ge "$chunks_num" ]; then + start_index=$chunk_idex end_index=$sketchcount - fi + else + start_index=$(( $chunk_idex * $chunk_size )) + if [ "$sketchcount" -le "$start_index" ]; then + echo "Skipping job" + return 0 + fi + + end_index=$(( $(( $chunk_idex + 1 )) * $chunk_size )) + if [ "$end_index" -gt "$sketchcount" ]; then + end_index=$sketchcount + fi + fi local start_num=$(( $start_index + 1 )) - echo "Found $sketchcount Sketches"; + echo "Found $sketchcount Sketches for target '$target'"; + echo "Chunk Index : $chunk_idex" echo "Chunk Count : $chunks_num" echo "Chunk Size : $chunk_size" echo "Start Sketch: $start_num" @@ -218,6 +226,8 @@ function build_sketches() # build_sketches < || [ "$sketchnum" -gt "$end_index" ]; then continue fi + echo "" + echo "Building Sketch Index $(($sketchnum - 1)) - $sketchdirname" build_sketch "$fqbn" "$sketch" "$xtra_opts" local result=$? if [ $result -ne 0 ]; then diff --git a/.github/scripts/on-push.sh b/.github/scripts/on-push.sh index c06a4c71..e7d0d0af 100755 --- a/.github/scripts/on-push.sh +++ b/.github/scripts/on-push.sh @@ -24,7 +24,7 @@ BUILD_PIO=0 if [ "$#" -lt 2 ] || [ "$CHUNKS_CNT" -le 0 ]; then CHUNK_INDEX=0 CHUNKS_CNT=1 -elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ]; then +elif [ "$CHUNK_INDEX" -gt "$CHUNKS_CNT" ] && [ "$CHUNKS_CNT" -ge 2 ]; then CHUNK_INDEX=$CHUNKS_CNT elif [ "$CHUNK_INDEX" -eq "$CHUNKS_CNT" ]; then BUILD_PIO=1 @@ -69,6 +69,19 @@ if [ "$BUILD_PIO" -eq 0 ]; then else build_sketches "$FQBN" "$TARGET" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT" fi + + # ArduinoIDE ESP32C3 Test + TARGET="esp32c3" + FQBN="espressif:esp32:esp32c3:PartitionScheme=huge_app" + if [ "$OS_IS_WINDOWS" == "1" ]; then + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" + elif [ "$OS_IS_MACOS" == "1" ]; then + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFi/examples/WiFiClient/WiFiClient.ino" && \ + build_sketch "$FQBN" "$ARDUINO_ESP32_PATH/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino" + else + build_sketches "$FQBN" "$TARGET" "$ARDUINO_ESP32_PATH/libraries" "$CHUNK_INDEX" "$CHUNKS_CNT" + fi else source ./.github/scripts/install-platformio-esp32.sh # PlatformIO ESP32 Test diff --git a/.gitignore b/.gitignore index aa021a40..14ef5315 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ tools/xtensa-esp32-elf tools/xtensa-esp32s2-elf +tools/riscv32-esp-elf tools/dist tools/esptool tools/esptool.exe diff --git a/CMakeLists.txt b/CMakeLists.txt index be5a65c3..6570e50c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -124,7 +124,7 @@ set(BLE_SRCS set(includedirs - variants/esp32/ + variants/${IDF_TARGET}/ cores/esp32/ libraries/ArduinoOTA/src libraries/AsyncUDP/src diff --git a/boards.txt b/boards.txt index e36c304c..c2211a3c 100644 --- a/boards.txt +++ b/boards.txt @@ -17,6 +17,137 @@ menu.EventsCore=Events Run On ### DO NOT PUT BOARDS ABOVE THE OFFICIAL ESPRESSIF BOARDS! ### ############################################################## +esp32c3.name=ESP32C3 Dev Module + +esp32c3.upload.tool=esptool_py +esp32c3.upload.maximum_size=1310720 +esp32c3.upload.maximum_data_size=327680 +esp32c3.upload.flags= + +esp32c3.serial.disableDTR=false +esp32c3.serial.disableRTS=false + +esp32c3.build.tarch=riscv32 +esp32c3.build.target=esp +esp32c3.build.mcu=esp32c3 +esp32c3.build.core=esp32 +esp32c3.build.variant=esp32c3 +esp32c3.build.board=ESP32C3_DEV +esp32c3.build.bootloader_addr=0x0 + +esp32c3.build.serial=0 +esp32c3.build.f_cpu=160000000L +esp32c3.build.flash_size=4MB +esp32c3.build.flash_freq=80m +esp32c3.build.flash_mode=qio +esp32c3.build.boot=qio +esp32c3.build.partitions=default +esp32c3.build.defines= + +esp32c3.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS) +esp32c3.menu.PartitionScheme.default.build.partitions=default +esp32c3.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS) +esp32c3.menu.PartitionScheme.defaultffat.build.partitions=default_ffat +esp32c3.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT) +esp32c3.menu.PartitionScheme.default_8MB.build.partitions=default_8MB +esp32c3.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336 +esp32c3.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS) +esp32c3.menu.PartitionScheme.minimal.build.partitions=minimal +esp32c3.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS) +esp32c3.menu.PartitionScheme.no_ota.build.partitions=no_ota +esp32c3.menu.PartitionScheme.no_ota.upload.maximum_size=2097152 +esp32c3.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS) +esp32c3.menu.PartitionScheme.noota_3g.build.partitions=noota_3g +esp32c3.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576 +esp32c3.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS) +esp32c3.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat +esp32c3.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152 +esp32c3.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS) +esp32c3.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat +esp32c3.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576 +esp32c3.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS) +esp32c3.menu.PartitionScheme.huge_app.build.partitions=huge_app +esp32c3.menu.PartitionScheme.huge_app.upload.maximum_size=3145728 +esp32c3.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS) +esp32c3.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs +esp32c3.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080 +esp32c3.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT) +esp32c3.menu.PartitionScheme.fatflash.build.partitions=ffat +esp32c3.menu.PartitionScheme.fatflash.upload.maximum_size=2097152 +esp32c3.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9MB FATFS) +esp32c3.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB +esp32c3.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728 + +esp32c3.menu.CPUFreq.160=160MHz (WiFi) +esp32c3.menu.CPUFreq.160.build.f_cpu=160000000L +esp32c3.menu.CPUFreq.80=80MHz (WiFi) +esp32c3.menu.CPUFreq.80.build.f_cpu=80000000L +esp32c3.menu.CPUFreq.40=40MHz +esp32c3.menu.CPUFreq.40.build.f_cpu=40000000L +esp32c3.menu.CPUFreq.20=20MHz +esp32c3.menu.CPUFreq.20.build.f_cpu=20000000L +esp32c3.menu.CPUFreq.10=10MHz +esp32c3.menu.CPUFreq.10.build.f_cpu=10000000L + +esp32c3.menu.FlashMode.qio=QIO +esp32c3.menu.FlashMode.qio.build.flash_mode=dio +esp32c3.menu.FlashMode.qio.build.boot=qio +esp32c3.menu.FlashMode.dio=DIO +esp32c3.menu.FlashMode.dio.build.flash_mode=dio +esp32c3.menu.FlashMode.dio.build.boot=dio +esp32c3.menu.FlashMode.qout=QOUT +esp32c3.menu.FlashMode.qout.build.flash_mode=dout +esp32c3.menu.FlashMode.qout.build.boot=qout +esp32c3.menu.FlashMode.dout=DOUT +esp32c3.menu.FlashMode.dout.build.flash_mode=dout +esp32c3.menu.FlashMode.dout.build.boot=dout + +esp32c3.menu.FlashFreq.80=80MHz +esp32c3.menu.FlashFreq.80.build.flash_freq=80m +esp32c3.menu.FlashFreq.40=40MHz +esp32c3.menu.FlashFreq.40.build.flash_freq=40m + +esp32c3.menu.FlashSize.4M=4MB (32Mb) +esp32c3.menu.FlashSize.4M.build.flash_size=4MB +esp32c3.menu.FlashSize.8M=8MB (64Mb) +esp32c3.menu.FlashSize.8M.build.flash_size=8MB +esp32c3.menu.FlashSize.8M.build.partitions=default_8MB +esp32c3.menu.FlashSize.2M=2MB (16Mb) +esp32c3.menu.FlashSize.2M.build.flash_size=2MB +esp32c3.menu.FlashSize.2M.build.partitions=minimal +esp32c3.menu.FlashSize.16M=16MB (128Mb) +esp32c3.menu.FlashSize.16M.build.flash_size=16MB + +esp32c3.menu.UploadSpeed.921600=921600 +esp32c3.menu.UploadSpeed.921600.upload.speed=921600 +esp32c3.menu.UploadSpeed.115200=115200 +esp32c3.menu.UploadSpeed.115200.upload.speed=115200 +esp32c3.menu.UploadSpeed.256000.windows=256000 +esp32c3.menu.UploadSpeed.256000.upload.speed=256000 +esp32c3.menu.UploadSpeed.230400.windows.upload.speed=256000 +esp32c3.menu.UploadSpeed.230400=230400 +esp32c3.menu.UploadSpeed.230400.upload.speed=230400 +esp32c3.menu.UploadSpeed.460800.linux=460800 +esp32c3.menu.UploadSpeed.460800.macosx=460800 +esp32c3.menu.UploadSpeed.460800.upload.speed=460800 +esp32c3.menu.UploadSpeed.512000.windows=512000 +esp32c3.menu.UploadSpeed.512000.upload.speed=512000 + +esp32c3.menu.DebugLevel.none=None +esp32c3.menu.DebugLevel.none.build.code_debug=0 +esp32c3.menu.DebugLevel.error=Error +esp32c3.menu.DebugLevel.error.build.code_debug=1 +esp32c3.menu.DebugLevel.warn=Warn +esp32c3.menu.DebugLevel.warn.build.code_debug=2 +esp32c3.menu.DebugLevel.info=Info +esp32c3.menu.DebugLevel.info.build.code_debug=3 +esp32c3.menu.DebugLevel.debug=Debug +esp32c3.menu.DebugLevel.debug.build.code_debug=4 +esp32c3.menu.DebugLevel.verbose=Verbose +esp32c3.menu.DebugLevel.verbose.build.code_debug=5 + +############################################################## + esp32s2.name=ESP32S2 Dev Module esp32s2.vid.0=0x303a esp32s2.pid.0=0x0002 @@ -31,6 +162,9 @@ esp32s2.upload.wait_for_upload_port=true esp32s2.serial.disableDTR=false esp32s2.serial.disableRTS=false +esp32s2.build.tarch=xtensa +esp32s2.build.bootloader_addr=0x1000 +esp32s2.build.target=esp32s2 esp32s2.build.mcu=esp32s2 esp32s2.build.core=esp32 esp32s2.build.variant=esp32s2 @@ -171,6 +305,9 @@ esp32.upload.flags= esp32.serial.disableDTR=true esp32.serial.disableRTS=true +esp32.build.tarch=xtensa +esp32.build.bootloader_addr=0x1000 +esp32.build.target=esp32 esp32.build.mcu=esp32 esp32.build.core=esp32 esp32.build.variant=esp32 @@ -326,6 +463,9 @@ esp32wrover.upload.flags= esp32wrover.serial.disableDTR=true esp32wrover.serial.disableRTS=true +esp32wrover.build.tarch=xtensa +esp32wrover.build.bootloader_addr=0x1000 +esp32wrover.build.target=esp32 esp32wrover.build.mcu=esp32 esp32wrover.build.core=esp32 esp32wrover.build.variant=esp32 @@ -427,6 +567,9 @@ pico32.upload.flags= pico32.serial.disableDTR=true pico32.serial.disableRTS=true +pico32.build.tarch=xtensa +pico32.build.bootloader_addr=0x1000 +pico32.build.target=esp32 pico32.build.mcu=esp32 pico32.build.core=esp32 pico32.build.variant=pico32 @@ -486,6 +629,9 @@ esp32wroverkit.upload.maximum_data_size=327680 esp32wroverkit.upload.flags= esp32wroverkit.serial.disableDTR=true esp32wroverkit.serial.disableRTS=true +esp32wroverkit.build.tarch=xtensa +esp32wroverkit.build.bootloader_addr=0x1000 +esp32wroverkit.build.target=esp32 esp32wroverkit.build.mcu=esp32 esp32wroverkit.build.core=esp32 esp32wroverkit.build.variant=esp32 @@ -608,6 +754,9 @@ tinypico.upload.flags= tinypico.serial.disableDTR=true tinypico.serial.disableRTS=true +tinypico.build.tarch=xtensa +tinypico.build.bootloader_addr=0x1000 +tinypico.build.target=esp32 tinypico.build.mcu=esp32 tinypico.build.core=esp32 tinypico.build.variant=um_tinypico @@ -692,6 +841,9 @@ feathers2.upload.wait_for_upload_port=true feathers2.serial.disableDTR=false feathers2.serial.disableRTS=false +feathers2.build.tarch=xtensa +feathers2.build.bootloader_addr=0x1000 +feathers2.build.target=esp32s2 feathers2.build.mcu=esp32s2 feathers2.build.core=esp32 feathers2.build.variant=um_feathers2 @@ -815,6 +967,9 @@ pros2.upload.wait_for_upload_port=true pros2.serial.disableDTR=false pros2.serial.disableRTS=false +pros2.build.tarch=xtensa +pros2.build.bootloader_addr=0x1000 +pros2.build.target=esp32s2 pros2.build.mcu=esp32s2 pros2.build.core=esp32 pros2.build.variant=um_pros2 @@ -935,6 +1090,9 @@ S_ODI_Ultra.upload.wait_for_upload_port=true S_ODI_Ultra.serial.disableDTR=true S_ODI_Ultra.serial.disableRTS=true +S_ODI_Ultra.build.tarch=xtensa +S_ODI_Ultra.build.bootloader_addr=0x1000 +S_ODI_Ultra.build.target=esp32 S_ODI_Ultra.build.mcu=esp32 S_ODI_Ultra.build.core=esp32 S_ODI_Ultra.build.variant=S_ODI_Ultra_v1 @@ -994,6 +1152,9 @@ micros2.upload.wait_for_upload_port=true micros2.serial.disableDTR=false micros2.serial.disableRTS=false +micros2.build.tarch=xtensa +micros2.build.bootloader_addr=0x1000 +micros2.build.target=esp32s2 micros2.build.mcu=esp32s2 micros2.build.core=esp32 micros2.build.variant=micro_s2 @@ -1113,6 +1274,9 @@ magicbit.upload.flags= magicbit.serial.disableDTR=true magicbit.serial.disableRTS=true +magicbit.build.tarch=xtensa +magicbit.build.bootloader_addr=0x1000 +magicbit.build.target=esp32 magicbit.build.mcu=esp32 magicbit.build.core=esp32 magicbit.build.variant=magicbit @@ -1148,6 +1312,9 @@ turta_iot_node.upload.flags= turta_iot_node.serial.disableDTR=true turta_iot_node.serial.disableRTS=true +turta_iot_node.build.tarch=xtensa +turta_iot_node.build.bootloader_addr=0x1000 +turta_iot_node.build.target=esp32 turta_iot_node.build.mcu=esp32 turta_iot_node.build.core=esp32 turta_iot_node.build.variant=pico32 @@ -1191,6 +1358,9 @@ ttgo-lora32-v1.upload.flags= ttgo-lora32-v1.serial.disableDTR=true ttgo-lora32-v1.serial.disableRTS=true +ttgo-lora32-v1.build.tarch=xtensa +ttgo-lora32-v1.build.bootloader_addr=0x1000 +ttgo-lora32-v1.build.target=esp32 ttgo-lora32-v1.build.mcu=esp32 ttgo-lora32-v1.build.core=esp32 ttgo-lora32-v1.build.variant=ttgo-lora32-v1 @@ -1247,6 +1417,9 @@ ttgo-t1.upload.flags= ttgo-t1.serial.disableDTR=true ttgo-t1.serial.disableRTS=true +ttgo-t1.build.tarch=xtensa +ttgo-t1.build.bootloader_addr=0x1000 +ttgo-t1.build.target=esp32 ttgo-t1.build.mcu=esp32 ttgo-t1.build.core=esp32 ttgo-t1.build.variant=ttgo-t1 @@ -1369,6 +1542,9 @@ ttgo-t7-v13-mini32.upload.wait_for_upload_port=true ttgo-t7-v13-mini32.serial.disableDTR=true ttgo-t7-v13-mini32.serial.disableRTS=true +ttgo-t7-v13-mini32.build.tarch=xtensa +ttgo-t7-v13-mini32.build.bootloader_addr=0x1000 +ttgo-t7-v13-mini32.build.target=esp32 ttgo-t7-v13-mini32.build.mcu=esp32 ttgo-t7-v13-mini32.build.core=esp32 ttgo-t7-v13-mini32.build.variant=ttgo-t7-v13-mini32 @@ -1485,6 +1661,9 @@ ttgo-t7-v14-mini32.upload.wait_for_upload_port=true ttgo-t7-v14-mini32.serial.disableDTR=true ttgo-t7-v14-mini32.serial.disableRTS=true +ttgo-t7-v14-mini32.build.tarch=xtensa +ttgo-t7-v14-mini32.build.bootloader_addr=0x1000 +ttgo-t7-v14-mini32.build.target=esp32 ttgo-t7-v14-mini32.build.mcu=esp32 ttgo-t7-v14-mini32.build.core=esp32 ttgo-t7-v14-mini32.build.variant=ttgo-t7-v14-mini32 @@ -1601,6 +1780,9 @@ cw02.upload.flags= cw02.serial.disableDTR=true cw02.serial.disableRTS=true +cw02.build.tarch=xtensa +cw02.build.bootloader_addr=0x1000 +cw02.build.target=esp32 cw02.build.mcu=esp32 cw02.build.core=esp32 cw02.build.variant=xinabox @@ -1677,6 +1859,9 @@ esp32thing.upload.flags= esp32thing.serial.disableDTR=true esp32thing.serial.disableRTS=true +esp32thing.build.tarch=xtensa +esp32thing.build.bootloader_addr=0x1000 +esp32thing.build.target=esp32 esp32thing.build.mcu=esp32 esp32thing.build.core=esp32 esp32thing.build.variant=esp32thing @@ -1743,6 +1928,9 @@ esp32thing_plus.upload.wait_for_upload_port=true esp32thing_plus.serial.disableDTR=true esp32thing_plus.serial.disableRTS=true +esp32thing_plus.build.tarch=xtensa +esp32thing_plus.build.bootloader_addr=0x1000 +esp32thing_plus.build.target=esp32 esp32thing_plus.build.mcu=esp32 esp32thing_plus.build.core=esp32 esp32thing_plus.build.variant=esp32thing_plus @@ -1811,6 +1999,9 @@ sparkfun_esp32s2_thing_plus.upload.wait_for_upload_port=true sparkfun_esp32s2_thing_plus.serial.disableDTR=false sparkfun_esp32s2_thing_plus.serial.disableRTS=false +sparkfun_esp32s2_thing_plus.build.tarch=xtensa +sparkfun_esp32s2_thing_plus.build.bootloader_addr=0x1000 +sparkfun_esp32s2_thing_plus.build.target=esp32s2 sparkfun_esp32s2_thing_plus.build.mcu=esp32s2 sparkfun_esp32s2_thing_plus.build.core=esp32 sparkfun_esp32s2_thing_plus.build.variant=esp32s2thing_plus @@ -1951,6 +2142,9 @@ sparkfun_lora_gateway_1-channel.upload.flags= sparkfun_lora_gateway_1-channel.serial.disableDTR=true sparkfun_lora_gateway_1-channel.serial.disableRTS=true +sparkfun_lora_gateway_1-channel.build.tarch=xtensa +sparkfun_lora_gateway_1-channel.build.bootloader_addr=0x1000 +sparkfun_lora_gateway_1-channel.build.target=esp32 sparkfun_lora_gateway_1-channel.build.mcu=esp32 sparkfun_lora_gateway_1-channel.build.core=esp32 sparkfun_lora_gateway_1-channel.build.variant=sparkfun_lora_gateway_1-channel @@ -2022,6 +2216,9 @@ nina_w10.upload.flags= nina_w10.serial.disableDTR=true nina_w10.serial.disableRTS=true +nina_w10.build.tarch=xtensa +nina_w10.build.bootloader_addr=0x1000 +nina_w10.build.target=esp32 nina_w10.build.mcu=esp32 nina_w10.build.core=esp32 nina_w10.build.variant=nina_w10 @@ -2061,6 +2258,9 @@ widora-air.upload.flags= widora-air.serial.disableDTR=true widora-air.serial.disableRTS=true +widora-air.build.tarch=xtensa +widora-air.build.bootloader_addr=0x1000 +widora-air.build.target=esp32 widora-air.build.mcu=esp32 widora-air.build.core=esp32 widora-air.build.variant=widora-air @@ -2105,6 +2305,9 @@ esp320.upload.flags= esp320.serial.disableDTR=true esp320.serial.disableRTS=true +esp320.build.tarch=xtensa +esp320.build.bootloader_addr=0x1000 +esp320.build.target=esp32 esp320.build.mcu=esp32 esp320.build.core=esp32 esp320.build.variant=esp320 @@ -2149,6 +2352,9 @@ nano32.upload.flags= nano32.serial.disableDTR=true nano32.serial.disableRTS=true +nano32.build.tarch=xtensa +nano32.build.bootloader_addr=0x1000 +nano32.build.target=esp32 nano32.build.mcu=esp32 nano32.build.core=esp32 nano32.build.variant=nano32 @@ -2193,6 +2399,9 @@ d32.upload.flags= d32.serial.disableDTR=true d32.serial.disableRTS=true +d32.build.tarch=xtensa +d32.build.bootloader_addr=0x1000 +d32.build.target=esp32 d32.build.mcu=esp32 d32.build.core=esp32 d32.build.variant=d32 @@ -2266,6 +2475,9 @@ d32_pro.upload.flags= d32_pro.serial.disableDTR=true d32_pro.serial.disableRTS=true +d32_pro.build.tarch=xtensa +d32_pro.build.bootloader_addr=0x1000 +d32_pro.build.target=esp32 d32_pro.build.mcu=esp32 d32_pro.build.core=esp32 d32_pro.build.variant=d32_pro @@ -2348,6 +2560,9 @@ lolin32.upload.flags= lolin32.serial.disableDTR=true lolin32.serial.disableRTS=true +lolin32.build.tarch=xtensa +lolin32.build.bootloader_addr=0x1000 +lolin32.build.target=esp32 lolin32.build.mcu=esp32 lolin32.build.core=esp32 lolin32.build.variant=lolin32 @@ -2418,6 +2633,9 @@ lolin32-lite.upload.wait_for_upload_port=true lolin32-lite.serial.disableDTR=true lolin32-lite.serial.disableRTS=true +lolin32-lite.build.tarch=xtensa +lolin32-lite.build.bootloader_addr=0x1000 +lolin32-lite.build.target=esp32 lolin32-lite.build.mcu=esp32 lolin32-lite.build.core=esp32 lolin32-lite.build.variant=lolin32-lite @@ -2488,6 +2706,9 @@ pocket_32.upload.flags= pocket_32.serial.disableDTR=true pocket_32.serial.disableRTS=true +pocket_32.build.tarch=xtensa +pocket_32.build.bootloader_addr=0x1000 +pocket_32.build.target=esp32 pocket_32.build.mcu=esp32 pocket_32.build.core=esp32 pocket_32.build.variant=pocket_32 @@ -2532,6 +2753,9 @@ WeMosBat.upload.flags= WeMosBat.serial.disableDTR=true WeMosBat.serial.disableRTS=true +WeMosBat.build.tarch=xtensa +WeMosBat.build.bootloader_addr=0x1000 +WeMosBat.build.target=esp32 WeMosBat.build.mcu=esp32 WeMosBat.build.core=esp32 WeMosBat.build.variant=pocket_32 @@ -2589,6 +2813,9 @@ espea32.upload.flags= espea32.serial.disableDTR=true espea32.serial.disableRTS=true +espea32.build.tarch=xtensa +espea32.build.bootloader_addr=0x1000 +espea32.build.target=esp32 espea32.build.mcu=esp32 espea32.build.core=esp32 espea32.build.variant=espea32 @@ -2633,6 +2860,9 @@ quantum.upload.flags= quantum.serial.disableDTR=true quantum.serial.disableRTS=true +quantum.build.tarch=xtensa +quantum.build.bootloader_addr=0x1000 +quantum.build.target=esp32 quantum.build.mcu=esp32 quantum.build.core=esp32 quantum.build.variant=quantum @@ -2677,6 +2907,9 @@ node32s.upload.flags= node32s.serial.disableDTR=true node32s.serial.disableRTS=true +node32s.build.tarch=xtensa +node32s.build.bootloader_addr=0x1000 +node32s.build.target=esp32 node32s.build.mcu=esp32 node32s.build.core=esp32 node32s.build.variant=node32s @@ -2743,6 +2976,9 @@ hornbill32dev.upload.flags= hornbill32dev.serial.disableDTR=true hornbill32dev.serial.disableRTS=true +hornbill32dev.build.tarch=xtensa +hornbill32dev.build.bootloader_addr=0x1000 +hornbill32dev.build.target=esp32 hornbill32dev.build.mcu=esp32 hornbill32dev.build.core=esp32 hornbill32dev.build.variant=hornbill32dev @@ -2787,6 +3023,9 @@ hornbill32minima.upload.flags= hornbill32minima.serial.disableDTR=true hornbill32minima.serial.disableRTS=true +hornbill32minima.build.tarch=xtensa +hornbill32minima.build.bootloader_addr=0x1000 +hornbill32minima.build.target=esp32 hornbill32minima.build.mcu=esp32 hornbill32minima.build.core=esp32 hornbill32minima.build.variant=hornbill32minima @@ -2830,6 +3069,9 @@ firebeetle32.upload.flags= firebeetle32.serial.disableDTR=true firebeetle32.serial.disableRTS=true +firebeetle32.build.tarch=xtensa +firebeetle32.build.bootloader_addr=0x1000 +firebeetle32.build.target=esp32 firebeetle32.build.mcu=esp32 firebeetle32.build.core=esp32 firebeetle32.build.variant=firebeetle32 @@ -2874,6 +3116,9 @@ intorobot-fig.upload.flags= intorobot-fig.serial.disableDTR=true intorobot-fig.serial.disableRTS=true +intorobot-fig.build.tarch=xtensa +intorobot-fig.build.bootloader_addr=0x1000 +intorobot-fig.build.target=esp32 intorobot-fig.build.mcu=esp32 intorobot-fig.build.core=esp32 intorobot-fig.build.variant=intorobot-fig @@ -2918,6 +3163,9 @@ onehorse32dev.upload.flags= onehorse32dev.serial.disableDTR=true onehorse32dev.serial.disableRTS=true +onehorse32dev.build.tarch=xtensa +onehorse32dev.build.bootloader_addr=0x1000 +onehorse32dev.build.target=esp32 onehorse32dev.build.mcu=esp32 onehorse32dev.build.core=esp32 onehorse32dev.build.variant=onehorse32dev @@ -2962,6 +3210,9 @@ featheresp32.upload.flags= featheresp32.serial.disableDTR=true featheresp32.serial.disableRTS=true +featheresp32.build.tarch=xtensa +featheresp32.build.bootloader_addr=0x1000 +featheresp32.build.target=esp32 featheresp32.build.mcu=esp32 featheresp32.build.core=esp32 featheresp32.build.variant=feather_esp32 @@ -3036,6 +3287,9 @@ adafruit_metro_esp32s2.upload.wait_for_upload_port=true adafruit_metro_esp32s2.serial.disableDTR=false adafruit_metro_esp32s2.serial.disableRTS=false +adafruit_metro_esp32s2.build.tarch=xtensa +adafruit_metro_esp32s2.build.bootloader_addr=0x1000 +adafruit_metro_esp32s2.build.target=esp32s2 adafruit_metro_esp32s2.build.mcu=esp32s2 adafruit_metro_esp32s2.build.core=esp32 adafruit_metro_esp32s2.build.variant=adafruit_metro_esp32s2 @@ -3185,6 +3439,9 @@ adafruit_magtag29_esp32s2.upload.wait_for_upload_port=true adafruit_magtag29_esp32s2.serial.disableDTR=false adafruit_magtag29_esp32s2.serial.disableRTS=false +adafruit_magtag29_esp32s2.build.tarch=xtensa +adafruit_magtag29_esp32s2.build.bootloader_addr=0x1000 +adafruit_magtag29_esp32s2.build.target=esp32s2 adafruit_magtag29_esp32s2.build.mcu=esp32s2 adafruit_magtag29_esp32s2.build.core=esp32 adafruit_magtag29_esp32s2.build.variant=adafruit_magtag29_esp32s2 @@ -3325,6 +3582,9 @@ nodemcu-32s.upload.flags= nodemcu-32s.serial.disableDTR=true nodemcu-32s.serial.disableRTS=true +nodemcu-32s.build.tarch=xtensa +nodemcu-32s.build.bootloader_addr=0x1000 +nodemcu-32s.build.target=esp32 nodemcu-32s.build.mcu=esp32 nodemcu-32s.build.core=esp32 nodemcu-32s.build.variant=nodemcu-32s @@ -3369,6 +3629,9 @@ mhetesp32devkit.upload.flags= mhetesp32devkit.serial.disableDTR=true mhetesp32devkit.serial.disableRTS=true +mhetesp32devkit.build.tarch=xtensa +mhetesp32devkit.build.bootloader_addr=0x1000 +mhetesp32devkit.build.target=esp32 mhetesp32devkit.build.mcu=esp32 mhetesp32devkit.build.core=esp32 mhetesp32devkit.build.variant=mhetesp32devkit @@ -3435,6 +3698,9 @@ mhetesp32minikit.upload.flags= mhetesp32minikit.serial.disableDTR=true mhetesp32minikit.serial.disableRTS=true +mhetesp32minikit.build.tarch=xtensa +mhetesp32minikit.build.bootloader_addr=0x1000 +mhetesp32minikit.build.target=esp32 mhetesp32minikit.build.mcu=esp32 mhetesp32minikit.build.core=esp32 mhetesp32minikit.build.variant=mhetesp32minikit @@ -3503,6 +3769,9 @@ esp32vn-iot-uno.upload.flags= esp32vn-iot-uno.serial.disableDTR=true esp32vn-iot-uno.serial.disableRTS=true +esp32vn-iot-uno.build.tarch=xtensa +esp32vn-iot-uno.build.bootloader_addr=0x1000 +esp32vn-iot-uno.build.target=esp32 esp32vn-iot-uno.build.mcu=esp32 esp32vn-iot-uno.build.core=esp32 esp32vn-iot-uno.build.variant=esp32vn-iot-uno @@ -3547,6 +3816,9 @@ esp32doit-devkit-v1.upload.flags= esp32doit-devkit-v1.serial.disableDTR=true esp32doit-devkit-v1.serial.disableRTS=true +esp32doit-devkit-v1.build.tarch=xtensa +esp32doit-devkit-v1.build.bootloader_addr=0x1000 +esp32doit-devkit-v1.build.target=esp32 esp32doit-devkit-v1.build.mcu=esp32 esp32doit-devkit-v1.build.core=esp32 esp32doit-devkit-v1.build.variant=doitESP32devkitV1 @@ -3602,6 +3874,9 @@ esp32doit-espduino.upload.wait_for_upload_port=true esp32doit-espduino.serial.disableDTR=true esp32doit-espduino.serial.disableRTS=true +esp32doit-espduino.build.tarch=xtensa +esp32doit-espduino.build.bootloader_addr=0x1000 +esp32doit-espduino.build.target=esp32 esp32doit-espduino.build.mcu=esp32 esp32doit-espduino.build.core=esp32 esp32doit-espduino.build.variant=doitESPduino32 @@ -3657,6 +3932,9 @@ esp32-evb.upload.flags= esp32-evb.serial.disableDTR=true esp32-evb.serial.disableRTS=true +esp32-evb.build.tarch=xtensa +esp32-evb.build.bootloader_addr=0x1000 +esp32-evb.build.target=esp32 esp32-evb.build.mcu=esp32 esp32-evb.build.core=esp32 esp32-evb.build.variant=esp32-evb @@ -3699,6 +3977,9 @@ esp32-gateway.upload.flags= esp32-gateway.serial.disableDTR=true esp32-gateway.serial.disableRTS=true +esp32-gateway.build.tarch=xtensa +esp32-gateway.build.bootloader_addr=0x1000 +esp32-gateway.build.target=esp32 esp32-gateway.build.mcu=esp32 esp32-gateway.build.core=esp32 esp32-gateway.build.variant=esp32-gateway @@ -3747,6 +4028,9 @@ esp32-poe.upload.flags= esp32-poe.serial.disableDTR=true esp32-poe.serial.disableRTS=true +esp32-poe.build.tarch=xtensa +esp32-poe.build.bootloader_addr=0x1000 +esp32-poe.build.target=esp32 esp32-poe.build.mcu=esp32 esp32-poe.build.core=esp32 esp32-poe.build.variant=esp32-poe @@ -3789,6 +4073,9 @@ esp32-poe-iso.upload.flags= esp32-poe-iso.serial.disableDTR=true esp32-poe-iso.serial.disableRTS=true +esp32-poe-iso.build.tarch=xtensa +esp32-poe-iso.build.bootloader_addr=0x1000 +esp32-poe-iso.build.target=esp32 esp32-poe-iso.build.mcu=esp32 esp32-poe-iso.build.core=esp32 esp32-poe-iso.build.variant=esp32-poe-iso @@ -3831,6 +4118,9 @@ esp32-DevKitLipo.upload.flags= esp32-DevKitLipo.serial.disableDTR=true esp32-DevKitLipo.serial.disableRTS=true +esp32-DevKitLipo.build.tarch=xtensa +esp32-DevKitLipo.build.bootloader_addr=0x1000 +esp32-DevKitLipo.build.target=esp32 esp32-DevKitLipo.build.mcu=esp32 esp32-DevKitLipo.build.core=esp32 esp32-DevKitLipo.build.variant=esp32-devkit-lipo @@ -3904,6 +4194,9 @@ espino32.upload.flags= espino32.serial.disableDTR=true espino32.serial.disableRTS=true +espino32.build.tarch=xtensa +espino32.build.bootloader_addr=0x1000 +espino32.build.target=esp32 espino32.build.mcu=esp32 espino32.build.core=esp32 espino32.build.variant=espino32 @@ -3948,6 +4241,9 @@ m5stack-core-esp32.upload.flags= m5stack-core-esp32.serial.disableDTR=true m5stack-core-esp32.serial.disableRTS=true +m5stack-core-esp32.build.tarch=xtensa +m5stack-core-esp32.build.bootloader_addr=0x1000 +m5stack-core-esp32.build.target=esp32 m5stack-core-esp32.build.mcu=esp32 m5stack-core-esp32.build.core=esp32 m5stack-core-esp32.build.variant=m5stack_core_esp32 @@ -4027,6 +4323,9 @@ m5stack-fire.upload.flags= m5stack-fire.serial.disableDTR=true m5stack-fire.serial.disableRTS=true +m5stack-fire.build.tarch=xtensa +m5stack-fire.build.bootloader_addr=0x1000 +m5stack-fire.build.target=esp32 m5stack-fire.build.mcu=esp32 m5stack-fire.build.core=esp32 m5stack-fire.build.variant=m5stack_fire @@ -4094,6 +4393,9 @@ m5stick-c.upload.flags= m5stick-c.serial.disableDTR=true m5stick-c.serial.disableRTS=true +m5stick-c.build.tarch=xtensa +m5stick-c.build.bootloader_addr=0x1000 +m5stick-c.build.target=esp32 m5stick-c.build.mcu=esp32 m5stick-c.build.core=esp32 m5stick-c.build.variant=m5stick_c @@ -4155,6 +4457,9 @@ m5stack-atom.upload.flags= m5stack-atom.serial.disableDTR=true m5stack-atom.serial.disableRTS=true +m5stack-atom.build.tarch=xtensa +m5stack-atom.build.bootloader_addr=0x1000 +m5stack-atom.build.target=esp32 m5stack-atom.build.mcu=esp32 m5stack-atom.build.core=esp32 m5stack-atom.build.variant=m5stack_atom @@ -4218,6 +4523,9 @@ m5stack-core2.upload.flags= m5stack-core2.serial.disableDTR=true m5stack-core2.serial.disableRTS=true +m5stack-core2.build.tarch=xtensa +m5stack-core2.build.bootloader_addr=0x1000 +m5stack-core2.build.target=esp32 m5stack-core2.build.mcu=esp32 m5stack-core2.build.core=esp32 m5stack-core2.build.variant=m5stack_core2 @@ -4319,6 +4627,9 @@ m5stack-timer-cam.upload.wait_for_upload_port=true m5stack-timer-cam.serial.disableDTR=true m5stack-timer-cam.serial.disableRTS=true +m5stack-timer-cam.build.tarch=xtensa +m5stack-timer-cam.build.bootloader_addr=0x1000 +m5stack-timer-cam.build.target=esp32 m5stack-timer-cam.build.mcu=esp32 m5stack-timer-cam.build.core=esp32 m5stack-timer-cam.build.variant=m5stack_timer_cam @@ -4413,6 +4724,9 @@ m5stack-coreink.upload.flags= m5stack-coreink.serial.disableDTR=true m5stack-coreink.serial.disableRTS=true +m5stack-coreink.build.tarch=xtensa +m5stack-coreink.build.bootloader_addr=0x1000 +m5stack-coreink.build.target=esp32 m5stack-coreink.build.mcu=esp32 m5stack-coreink.build.core=esp32 m5stack-coreink.build.variant=m5stack_coreink @@ -4477,6 +4791,9 @@ odroid_esp32.upload.flags= odroid_esp32.serial.disableDTR=true odroid_esp32.serial.disableRTS=true +odroid_esp32.build.tarch=xtensa +odroid_esp32.build.bootloader_addr=0x1000 +odroid_esp32.build.target=esp32 odroid_esp32.build.mcu=esp32 odroid_esp32.build.core=esp32 odroid_esp32.build.variant=odroid_esp32 @@ -4557,6 +4874,9 @@ heltec_wifi_kit_32.upload.flags= heltec_wifi_kit_32.serial.disableDTR=true heltec_wifi_kit_32.serial.disableRTS=true +heltec_wifi_kit_32.build.tarch=xtensa +heltec_wifi_kit_32.build.bootloader_addr=0x1000 +heltec_wifi_kit_32.build.target=esp32 heltec_wifi_kit_32.build.mcu=esp32 heltec_wifi_kit_32.build.core=esp32 heltec_wifi_kit_32.build.variant=heltec_wifi_kit_32 @@ -4626,6 +4946,9 @@ heltec_wifi_lora_32.upload.flags= heltec_wifi_lora_32.serial.disableDTR=true heltec_wifi_lora_32.serial.disableRTS=true +heltec_wifi_lora_32.build.tarch=xtensa +heltec_wifi_lora_32.build.bootloader_addr=0x1000 +heltec_wifi_lora_32.build.target=esp32 heltec_wifi_lora_32.build.mcu=esp32 heltec_wifi_lora_32.build.core=esp32 heltec_wifi_lora_32.build.variant=heltec_wifi_lora_32 @@ -4723,6 +5046,9 @@ heltec_wifi_lora_32_V2.upload.flags= heltec_wifi_lora_32_V2.serial.disableDTR=true heltec_wifi_lora_32_V2.serial.disableRTS=true +heltec_wifi_lora_32_V2.build.tarch=xtensa +heltec_wifi_lora_32_V2.build.bootloader_addr=0x1000 +heltec_wifi_lora_32_V2.build.target=esp32 heltec_wifi_lora_32_V2.build.mcu=esp32 heltec_wifi_lora_32_V2.build.core=esp32 heltec_wifi_lora_32_V2.build.variant=heltec_wifi_lora_32_V2 @@ -4820,6 +5146,9 @@ heltec_wireless_stick.upload.flags= heltec_wireless_stick.serial.disableDTR=true heltec_wireless_stick.serial.disableRTS=true +heltec_wireless_stick.build.tarch=xtensa +heltec_wireless_stick.build.bootloader_addr=0x1000 +heltec_wireless_stick.build.target=esp32 heltec_wireless_stick.build.mcu=esp32 heltec_wireless_stick.build.core=esp32 heltec_wireless_stick.build.variant=heltec_wireless_stick @@ -4917,6 +5246,9 @@ heltec_wireless_stick_lite.upload.wait_for_upload_port=true heltec_wireless_stick_lite.serial.disableDTR=true heltec_wireless_stick_lite.serial.disableRTS=true +heltec_wireless_stick_lite.build.tarch=xtensa +heltec_wireless_stick_lite.build.bootloader_addr=0x1000 +heltec_wireless_stick_lite.build.target=esp32 heltec_wireless_stick_lite.build.mcu=esp32 heltec_wireless_stick_lite.build.core=esp32 heltec_wireless_stick_lite.build.variant=heltec_wireless_stick_lite @@ -5014,6 +5346,9 @@ espectro32.upload.flags= espectro32.serial.disableDTR=true espectro32.serial.disableRTS=true +espectro32.build.tarch=xtensa +espectro32.build.bootloader_addr=0x1000 +espectro32.build.target=esp32 espectro32.build.mcu=esp32 espectro32.build.core=esp32 espectro32.build.variant=espectro32 @@ -5090,6 +5425,9 @@ CoreESP32.upload.flags= CoreESP32.serial.disableDTR=false CoreESP32.serial.disableRTS=false +CoreESP32.build.tarch=xtensa +CoreESP32.build.bootloader_addr=0x1000 +CoreESP32.build.target=esp32 CoreESP32.build.mcu=esp32 CoreESP32.build.core=esp32 CoreESP32.build.variant=Microduino-esp32 @@ -5168,6 +5506,9 @@ alksesp32.upload.flags= alksesp32.serial.disableDTR=true alksesp32.serial.disableRTS=true +alksesp32.build.tarch=xtensa +alksesp32.build.bootloader_addr=0x1000 +alksesp32.build.target=esp32 alksesp32.build.mcu=esp32 alksesp32.build.core=esp32 alksesp32.build.variant=alksesp32 @@ -5300,6 +5641,9 @@ wipy3.upload.flags= wipy3.serial.disableDTR=true wipy3.serial.disableRTS=true +wipy3.build.tarch=xtensa +wipy3.build.bootloader_addr=0x1000 +wipy3.build.target=esp32 wipy3.build.mcu=esp32 wipy3.build.core=esp32 wipy3.build.variant=wipy3 @@ -5357,6 +5701,9 @@ bpi-bit.upload.flags= bpi-bit.serial.disableDTR=true bpi-bit.serial.disableRTS=true +bpi-bit.build.tarch=xtensa +bpi-bit.build.bootloader_addr=0x1000 +bpi-bit.build.target=esp32 bpi-bit.build.mcu=esp32 bpi-bit.build.core=esp32 bpi-bit.build.variant=bpi-bit @@ -5400,6 +5747,9 @@ wesp32.upload.flags= wesp32.serial.disableDTR=true wesp32.serial.disableRTS=true +wesp32.build.tarch=xtensa +wesp32.build.bootloader_addr=0x1000 +wesp32.build.target=esp32 wesp32.build.mcu=esp32 wesp32.build.core=esp32 wesp32.build.variant=wesp32 @@ -5457,6 +5807,9 @@ t-beam.upload.flags= t-beam.serial.disableDTR=true t-beam.serial.disableRTS=true +t-beam.build.tarch=xtensa +t-beam.build.bootloader_addr=0x1000 +t-beam.build.target=esp32 t-beam.build.mcu=esp32 t-beam.build.core=esp32 t-beam.build.variant=tbeam @@ -5520,6 +5873,9 @@ d-duino-32.upload.flags= d-duino-32.serial.disableDTR=true d-duino-32.serial.disableRTS=true +d-duino-32.build.tarch=xtensa +d-duino-32.build.bootloader_addr=0x1000 +d-duino-32.build.target=esp32 d-duino-32.build.mcu=esp32 d-duino-32.build.core=esp32 d-duino-32.build.variant=d-duino-32 @@ -5591,6 +5947,9 @@ lopy.upload.flags= lopy.serial.disableDTR=true lopy.serial.disableRTS=true +lopy.build.tarch=xtensa +lopy.build.bootloader_addr=0x1000 +lopy.build.target=esp32 lopy.build.mcu=esp32 lopy.build.core=esp32 lopy.build.variant=lopy @@ -5647,6 +6006,9 @@ lopy4.upload.flags= lopy4.serial.disableDTR=true lopy4.serial.disableRTS=true +lopy4.build.tarch=xtensa +lopy4.build.bootloader_addr=0x1000 +lopy4.build.target=esp32 lopy4.build.mcu=esp32 lopy4.build.core=esp32 lopy4.build.variant=lopy4 @@ -5710,6 +6072,9 @@ oroca_edubot.upload.flags= oroca_edubot.serial.disableDTR=true oroca_edubot.serial.disableRTS=true +oroca_edubot.build.tarch=xtensa +oroca_edubot.build.bootloader_addr=0x1000 +oroca_edubot.build.target=esp32 oroca_edubot.build.mcu=esp32 oroca_edubot.build.core=esp32 oroca_edubot.build.variant=oroca_edubot @@ -5776,6 +6141,9 @@ fm-devkit.upload.flags= fm-devkit.serial.disableDTR=true fm-devkit.serial.disableRTS=true +fm-devkit.build.tarch=xtensa +fm-devkit.build.bootloader_addr=0x1000 +fm-devkit.build.target=esp32 fm-devkit.build.mcu=esp32 fm-devkit.build.core=esp32 fm-devkit.build.variant=fm-devkit @@ -5829,6 +6197,9 @@ frogboard.upload.flags= frogboard.serial.disableDTR=true frogboard.serial.disableRTS=true +frogboard.build.tarch=xtensa +frogboard.build.bootloader_addr=0x1000 +frogboard.build.target=esp32 frogboard.build.mcu=esp32 frogboard.build.core=esp32 frogboard.build.variant=frog32 @@ -5922,6 +6293,9 @@ esp32cam.upload.speed=460800 esp32cam.serial.disableDTR=true esp32cam.serial.disableRTS=true +esp32cam.build.tarch=xtensa +esp32cam.build.bootloader_addr=0x1000 +esp32cam.build.target=esp32 esp32cam.build.mcu=esp32 esp32cam.build.core=esp32 esp32cam.build.variant=esp32 @@ -5979,6 +6353,9 @@ twatch.upload.wait_for_upload_port=true twatch.serial.disableDTR=true twatch.serial.disableRTS=true +twatch.build.tarch=xtensa +twatch.build.bootloader_addr=0x1000 +twatch.build.target=esp32 twatch.build.mcu=esp32 twatch.build.core=esp32 twatch.build.variant=twatch @@ -6057,6 +6434,9 @@ d1_mini32.upload.flags= d1_mini32.serial.disableDTR=true d1_mini32.serial.disableRTS=true +d1_mini32.build.tarch=xtensa +d1_mini32.build.bootloader_addr=0x1000 +d1_mini32.build.target=esp32 d1_mini32.build.mcu=esp32 d1_mini32.build.core=esp32 d1_mini32.build.variant=d1_mini32 @@ -6127,6 +6507,9 @@ gpy.upload.flags= gpy.serial.disableDTR=true gpy.serial.disableRTS=true +gpy.build.tarch=xtensa +gpy.build.bootloader_addr=0x1000 +gpy.build.target=esp32 gpy.build.mcu=esp32 gpy.build.core=esp32 gpy.build.variant=gpy @@ -6183,6 +6566,9 @@ vintlabs-devkit-v1.upload.flags= vintlabs-devkit-v1.serial.disableDTR=true vintlabs-devkit-v1.serial.disableRTS=true +vintlabs-devkit-v1.build.tarch=xtensa +vintlabs-devkit-v1.build.bootloader_addr=0x1000 +vintlabs-devkit-v1.build.target=esp32 vintlabs-devkit-v1.build.mcu=esp32 vintlabs-devkit-v1.build.core=esp32 vintlabs-devkit-v1.build.variant=vintlabsdevkitv1 @@ -6285,6 +6671,9 @@ honeylemon.upload.flags= honeylemon.serial.disableDTR=true honeylemon.serial.disableRTS=true +honeylemon.build.tarch=xtensa +honeylemon.build.bootloader_addr=0x1000 +honeylemon.build.target=esp32 honeylemon.build.mcu=esp32 honeylemon.build.core=esp32 honeylemon.build.variant=honeylemon @@ -6329,6 +6718,9 @@ mgbot-iotik32a.upload.flags= mgbot-iotik32a.serial.disableDTR=true mgbot-iotik32a.serial.disableRTS=true +mgbot-iotik32a.build.tarch=xtensa +mgbot-iotik32a.build.bootloader_addr=0x1000 +mgbot-iotik32a.build.target=esp32 mgbot-iotik32a.build.mcu=esp32 mgbot-iotik32a.build.core=esp32 mgbot-iotik32a.build.variant=mgbot-iotik32a @@ -6469,6 +6861,9 @@ mgbot-iotik32b.upload.flags= mgbot-iotik32b.serial.disableDTR=true mgbot-iotik32b.serial.disableRTS=true +mgbot-iotik32b.build.tarch=xtensa +mgbot-iotik32b.build.bootloader_addr=0x1000 +mgbot-iotik32b.build.target=esp32 mgbot-iotik32b.build.mcu=esp32 mgbot-iotik32b.build.core=esp32 mgbot-iotik32b.build.variant=mgbot-iotik32b @@ -6608,6 +7003,9 @@ piranha_esp-32.upload.flags= piranha_esp-32.serial.disableDTR=true piranha_esp-32.serial.disableRTS=true +piranha_esp-32.build.tarch=xtensa +piranha_esp-32.build.bootloader_addr=0x1000 +piranha_esp-32.build.target=esp32 piranha_esp-32.build.mcu=esp32 piranha_esp-32.build.core=esp32 piranha_esp-32.build.variant=piranha_esp-32 @@ -6674,6 +7072,9 @@ metro_esp-32.upload.flags= metro_esp-32.serial.disableDTR=true metro_esp-32.serial.disableRTS=true +metro_esp-32.build.tarch=xtensa +metro_esp-32.build.bootloader_addr=0x1000 +metro_esp-32.build.target=esp32 metro_esp-32.build.mcu=esp32 metro_esp-32.build.core=esp32 metro_esp-32.build.variant=metro_esp-32 @@ -6739,6 +7140,9 @@ sensesiot_weizen.upload.flags= sensesiot_weizen.serial.disableDTR=true sensesiot_weizen.serial.disableRTS=true +sensesiot_weizen.build.tarch=xtensa +sensesiot_weizen.build.bootloader_addr=0x1000 +sensesiot_weizen.build.target=esp32 sensesiot_weizen.build.mcu=esp32 sensesiot_weizen.build.core=esp32 sensesiot_weizen.build.variant=esp32 @@ -6782,6 +7186,9 @@ kits-edu.upload.wait_for_upload_port=true kits-edu.serial.disableDTR=true kits-edu.serial.disableRTS=true +kits-edu.build.tarch=xtensa +kits-edu.build.bootloader_addr=0x1000 +kits-edu.build.target=esp32 kits-edu.build.mcu=esp32 kits-edu.build.core=esp32 kits-edu.build.variant=pico32 @@ -6843,6 +7250,9 @@ mPython.upload.flags= mPython.serial.disableDTR=true mPython.serial.disableRTS=true +mPython.build.tarch=xtensa +mPython.build.bootloader_addr=0x1000 +mPython.build.target=esp32 mPython.build.mcu=esp32 mPython.build.core=esp32 mPython.build.variant=mpython @@ -6956,6 +7366,9 @@ OpenKB.upload.wait_for_upload_port=true OpenKB.serial.disableDTR=true OpenKB.serial.disableRTS=true +OpenKB.build.tarch=xtensa +OpenKB.build.bootloader_addr=0x1000 +OpenKB.build.target=esp32 OpenKB.build.mcu=esp32 OpenKB.build.core=esp32 OpenKB.build.variant=openkb @@ -7000,6 +7413,9 @@ wifiduino32.upload.wait_for_upload_port=true wifiduino32.serial.disableDTR=true wifiduino32.serial.disableRTS=true +wifiduino32.build.tarch=xtensa +wifiduino32.build.bootloader_addr=0x1000 +wifiduino32.build.target=esp32 wifiduino32.build.mcu=esp32 wifiduino32.build.core=esp32 wifiduino32.build.variant=wifiduino32 @@ -7066,6 +7482,9 @@ ttgo-lora32-v21new.upload.wait_for_upload_port=true ttgo-lora32-v21new.serial.disableDTR=true ttgo-lora32-v21new.serial.disableRTS=true +ttgo-lora32-v21new.build.tarch=xtensa +ttgo-lora32-v21new.build.bootloader_addr=0x1000 +ttgo-lora32-v21new.build.target=esp32 ttgo-lora32-v21new.build.mcu=esp32 ttgo-lora32-v21new.build.core=esp32 ttgo-lora32-v21new.build.variant=ttgo-lora32-v21new @@ -7095,6 +7514,9 @@ ttgo-lora32-v21new.upload.wait_for_upload_port=true ttgo-lora32-v21new.serial.disableDTR=true ttgo-lora32-v21new.serial.disableRTS=true +ttgo-lora32-v21new.build.tarch=xtensa +ttgo-lora32-v21new.build.bootloader_addr=0x1000 +ttgo-lora32-v21new.build.target=esp32 ttgo-lora32-v21new.build.mcu=esp32 ttgo-lora32-v21new.build.core=esp32 ttgo-lora32-v21new.build.variant=ttgo-lora32-v21new @@ -7174,6 +7596,9 @@ imbrios-logsens-v1p1.upload.wait_for_upload_port=true imbrios-logsens-v1p1.serial.disableDTR=true imbrios-logsens-v1p1.serial.disableRTS=true +imbrios-logsens-v1p1.build.tarch=xtensa +imbrios-logsens-v1p1.build.bootloader_addr=0x1000 +imbrios-logsens-v1p1.build.target=esp32 imbrios-logsens-v1p1.build.mcu=esp32 imbrios-logsens-v1p1.build.core=esp32 imbrios-logsens-v1p1.build.variant=imbrios-logsens-v1p1 @@ -7244,6 +7669,9 @@ healthypi4.upload.wait_for_upload_port=true healthypi4.serial.disableDTR=true healthypi4.serial.disableRTS=true +healthypi4.build.tarch=xtensa +healthypi4.build.bootloader_addr=0x1000 +healthypi4.build.target=esp32 healthypi4.build.mcu=esp32 healthypi4.build.core=esp32 healthypi4.build.variant=healthypi4 @@ -7311,6 +7739,9 @@ ET-Board.upload.wait_for_upload_port=true ET-Board.serial.disableDTR=true ET-Board.serial.disableRTS=true +ET-Board.build.tarch=xtensa +ET-Board.build.bootloader_addr=0x1000 +ET-Board.build.target=esp32 ET-Board.build.mcu=esp32 ET-Board.build.core=esp32 ET-Board.build.variant=ET-Board diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp index 0220c989..338e7dc9 100644 --- a/cores/esp32/Esp.cpp +++ b/cores/esp32/Esp.cpp @@ -37,6 +37,8 @@ extern "C" { #include "soc/efuse_reg.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/spi_flash.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/spi_flash.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -265,6 +267,10 @@ const char * EspClass::getChipModel(void) } #elif CONFIG_IDF_TARGET_ESP32S2 return "ESP32-S2"; +#elif CONFIG_IDF_TARGET_ESP32S3 + return "ESP32-S3"; +#elif CONFIG_IDF_TARGET_ESP32C3 + return "ESP32-C3"; #endif } diff --git a/cores/esp32/HardwareSerial.cpp b/cores/esp32/HardwareSerial.cpp index f26c7006..9e6a675c 100644 --- a/cores/esp32/HardwareSerial.cpp +++ b/cores/esp32/HardwareSerial.cpp @@ -66,6 +66,9 @@ void HardwareSerial::begin(unsigned long baud, uint32_t config, int8_t rxPin, in #elif CONFIG_IDF_TARGET_ESP32S2 rxPin = 44; txPin = 43; +#elif CONFIG_IDF_TARGET_ESP32C3 + rxPin = 20; + txPin = 21; #endif } if(_uart_nr == 1 && rxPin < 0 && txPin < 0) { diff --git a/cores/esp32/MD5Builder.h b/cores/esp32/MD5Builder.h index 0e6daa47..2588a74d 100644 --- a/cores/esp32/MD5Builder.h +++ b/cores/esp32/MD5Builder.h @@ -28,6 +28,8 @@ #include "esp32/rom/md5_hash.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/md5_hash.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/md5_hash.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif diff --git a/cores/esp32/esp32-hal-adc.c b/cores/esp32/esp32-hal-adc.c index 72e8ab00..37503ba0 100644 --- a/cores/esp32/esp32-hal-adc.c +++ b/cores/esp32/esp32-hal-adc.c @@ -16,16 +16,15 @@ #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_attr.h" -#include "soc/rtc_io_reg.h" #include "soc/rtc_cntl_reg.h" -#include "soc/sens_reg.h" - #include "driver/adc.h" #include "esp_system.h" #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 #include "esp_adc_cal.h" +#include "soc/sens_reg.h" +#include "soc/rtc_io_reg.h" #include "esp32/rom/ets_sys.h" #include "esp_intr_alloc.h" #define DEFAULT_VREF 1100 @@ -34,6 +33,10 @@ static uint16_t __analogVRef = 0; static uint8_t __analogVRefPin = 0; #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/ets_sys.h" +#include "soc/sens_reg.h" +#include "soc/rtc_io_reg.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -51,7 +54,9 @@ void __analogSetClockDiv(uint8_t clockDiv){ clockDiv = 1; } __analogClockDiv = clockDiv; +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 adc_set_clk_div(__analogClockDiv); +#endif } void __analogSetAttenuation(adc_attenuation_t attenuation) @@ -114,11 +119,14 @@ bool __adcAttachPin(uint8_t pin){ WRITE_PERI_REG(SENS_SAR_TOUCH_ENABLE_REG, touch); } #endif - } else if(pin == 25){ + } +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 + else if(pin == 25){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_XPD_DAC | RTC_IO_PDAC1_DAC_XPD_FORCE);//stop dac1 } else if(pin == 26){ CLEAR_PERI_REG_MASK(RTC_IO_PAD_DAC2_REG, RTC_IO_PDAC2_XPD_DAC | RTC_IO_PDAC2_DAC_XPD_FORCE);//stop dac2 } +#endif pinMode(pin, ANALOG); __analogSetPinAttenuation(pin, __analogAttenuation); diff --git a/cores/esp32/esp32-hal-cpu.c b/cores/esp32/esp32-hal-cpu.c index ac70c532..34124db1 100644 --- a/cores/esp32/esp32-hal-cpu.c +++ b/cores/esp32/esp32-hal-cpu.c @@ -16,7 +16,6 @@ #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" -#include "freertos/xtensa_timer.h" #include "esp_attr.h" #include "esp_log.h" #include "soc/rtc.h" @@ -29,9 +28,13 @@ #include "esp_system.h" #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 +#include "freertos/xtensa_timer.h" #include "esp32/rom/rtc.h" #elif CONFIG_IDF_TARGET_ESP32S2 +#include "freertos/xtensa_timer.h" #include "esp32s2/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/rtc.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -141,10 +144,14 @@ bool removeApbChangeCallback(void * arg, apb_change_cb_t cb){ } static uint32_t calculateApb(rtc_cpu_freq_config_t * conf){ +#if CONFIG_IDF_TARGET_ESP32C3 + return APB_CLK_FREQ; +#else if(conf->freq_mhz >= 80){ return 80 * MHZ; } return (conf->source_freq_mhz * MHZ) / conf->div; +#endif } void esp_timer_impl_update_apb_freq(uint32_t apb_ticks_per_us); //private in IDF @@ -219,8 +226,12 @@ bool setCpuFrequencyMhz(uint32_t cpu_freq_mhz){ esp_timer_impl_update_apb_freq(apb / MHZ); } //Update FreeRTOS Tick Divisor +#if CONFIG_IDF_TARGET_ESP32C3 + +#else uint32_t fcpu = (conf.freq_mhz >= 80)?(conf.freq_mhz * MHZ):(apb); _xt_tick_divisor = fcpu / XT_TICK_PER_SEC; +#endif //Call peripheral functions after the APB change if(apb_change_callbacks){ triggerApbChangeCallback(APB_AFTER_CHANGE, capb, apb); diff --git a/cores/esp32/esp32-hal-dac.c b/cores/esp32/esp32-hal-dac.c index d083e29e..30a08a71 100644 --- a/cores/esp32/esp32-hal-dac.c +++ b/cores/esp32/esp32-hal-dac.c @@ -13,24 +13,29 @@ // limitations under the License. #include "esp32-hal.h" -#include "esp_attr.h" + +#if CONFIG_IDF_TARGET_ESP32 #include "soc/rtc_io_reg.h" +#define DAC1 25 +#define DAC2 26 +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "soc/rtc_io_reg.h" +#define DAC1 17 +#define DAC2 18 +#elif CONFIG_IDF_TARGET_ESP32C3 +#define NODAC +#else +#error Target CONFIG_IDF_TARGET is not supported +#endif + +#ifndef NODAC +#include "esp_attr.h" #include "soc/rtc_cntl_reg.h" #include "soc/rtc_io_periph.h" #include "soc/sens_reg.h" #include "soc/sens_struct.h" #include "driver/dac.h" -#if CONFIG_IDF_TARGET_ESP32 -#define DAC1 25 -#define DAC2 26 -#elif CONFIG_IDF_TARGET_ESP32S2 -#define DAC1 17 -#define DAC2 18 -#else -#error Target CONFIG_IDF_TARGET is not supported -#endif - void ARDUINO_ISR_ATTR __dacWrite(uint8_t pin, uint8_t value) { if(pin < DAC1 || pin > DAC2){ @@ -54,3 +59,5 @@ void ARDUINO_ISR_ATTR __dacWrite(uint8_t pin, uint8_t value) } extern void dacWrite(uint8_t pin, uint8_t value) __attribute__ ((weak, alias("__dacWrite"))); + +#endif diff --git a/cores/esp32/esp32-hal-gpio.c b/cores/esp32/esp32-hal-gpio.c index 6ed48ee7..f0eb4dec 100644 --- a/cores/esp32/esp32-hal-gpio.c +++ b/cores/esp32/esp32-hal-gpio.c @@ -20,23 +20,25 @@ #include "soc/gpio_reg.h" #include "soc/io_mux_reg.h" #include "soc/gpio_struct.h" -#include "soc/rtc_io_reg.h" - +#include "driver/gpio.h" #include "esp_system.h" + #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 #include "esp32/rom/ets_sys.h" #include "esp32/rom/gpio.h" #include "esp_intr_alloc.h" +#include "soc/rtc_io_reg.h" #define GPIO_FUNC 2 #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/ets_sys.h" #include "esp32s2/rom/gpio.h" #include "esp_intr_alloc.h" #include "soc/periph_defs.h" +#include "soc/rtc_io_reg.h" #define GPIO_FUNC 1 #else -#error Target CONFIG_IDF_TARGET is not supported +#define USE_ESP_IDF_GPIO 1 #endif #else // ESP32 Before IDF 4.0 #include "rom/ets_sys.h" @@ -157,7 +159,45 @@ static InterruptHandle_t __pinInterruptHandlers[SOC_GPIO_PIN_COUNT] = {0,}; extern void ARDUINO_ISR_ATTR __pinMode(uint8_t pin, uint8_t mode) { +#if USE_ESP_IDF_GPIO + if (!GPIO_IS_VALID_GPIO(pin)) { + return; + } + gpio_config_t conf = { + .pin_bit_mask = (1ULL<= 0x20 && mode < ANALOG) {//function + PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[pin], mode >> 5); + } +#else if(!digitalPinIsValid(pin)) { return; } @@ -228,11 +268,7 @@ extern void ARDUINO_ISR_ATTR __pinMode(uint8_t pin, uint8_t mode) pinFunction |= FUN_IE;//input enable but required for output as well? if(mode & (INPUT | OUTPUT)) { -#if CONFIG_IDF_TARGET_ESP32 - pinFunction |= ((uint32_t)2 << MCU_SEL_S); -#elif CONFIG_IDF_TARGET_ESP32S2 - pinFunction |= ((uint32_t)1 << MCU_SEL_S); -#endif + pinFunction |= ((uint32_t)PIN_FUNC_GPIO << MCU_SEL_S); } else if(mode == SPECIAL) { #if CONFIG_IDF_TARGET_ESP32 pinFunction |= ((uint32_t)(((pin)==RX||(pin)==TX)?0:1) << MCU_SEL_S); @@ -250,10 +286,20 @@ extern void ARDUINO_ISR_ATTR __pinMode(uint8_t pin, uint8_t mode) } GPIO.pin[pin].val = pinControl; +#endif } extern void ARDUINO_ISR_ATTR __digitalWrite(uint8_t pin, uint8_t val) { +#if USE_ESP_IDF_GPIO + gpio_set_level((gpio_num_t)pin, val); +#elif CONFIG_IDF_TARGET_ESP32C3 + if (val) { + GPIO.out_w1ts.out_w1ts = (1 << pin); + } else { + GPIO.out_w1tc.out_w1tc = (1 << pin); + } +#else if(val) { if(pin < 32) { GPIO.out_w1ts = ((uint32_t)1 << pin); @@ -267,18 +313,37 @@ extern void ARDUINO_ISR_ATTR __digitalWrite(uint8_t pin, uint8_t val) GPIO.out1_w1tc.val = ((uint32_t)1 << (pin - 32)); } } +#endif } extern int ARDUINO_ISR_ATTR __digitalRead(uint8_t pin) { +#if USE_ESP_IDF_GPIO + return gpio_get_level((gpio_num_t)pin); +#elif CONFIG_IDF_TARGET_ESP32C3 + return (GPIO.in.data >> pin) & 0x1; +#else if(pin < 32) { return (GPIO.in >> pin) & 0x1; } else if(pin < GPIO_PIN_COUNT) { return (GPIO.in1.val >> (pin - 32)) & 0x1; } return 0; +#endif } +#if USE_ESP_IDF_GPIO +static void ARDUINO_ISR_ATTR __onPinInterrupt(void * arg) { + InterruptHandle_t * isr = (InterruptHandle_t*)arg; + if(isr->fn) { + if(isr->arg){ + ((voidFuncPtrArg)isr->fn)(isr->arg); + } else { + isr->fn(); + } + } +} +#else static intr_handle_t gpio_intr_handle = NULL; static void ARDUINO_ISR_ATTR __onPinInterrupt() @@ -320,6 +385,7 @@ static void ARDUINO_ISR_ATTR __onPinInterrupt() } while(++pin= 2){ + if(i2c_num >= SOC_I2C_NUM){ return NULL; } if(!clk_speed){ diff --git a/cores/esp32/esp32-hal-ledc.c b/cores/esp32/esp32-hal-ledc.c index 69e40274..e755f064 100644 --- a/cores/esp32/esp32-hal-ledc.c +++ b/cores/esp32/esp32-hal-ledc.c @@ -17,19 +17,25 @@ #include "freertos/task.h" #include "freertos/semphr.h" #include "esp32-hal-matrix.h" -#include "soc/dport_reg.h" #include "soc/ledc_reg.h" #include "soc/ledc_struct.h" +#include "driver/periph_ctrl.h" #include "esp_system.h" #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 +#include "soc/dport_reg.h" #include "esp32/rom/ets_sys.h" #define LAST_CHAN (15) #elif CONFIG_IDF_TARGET_ESP32S2 +#include "soc/dport_reg.h" #include "esp32s2/rom/ets_sys.h" #define LAST_CHAN (7) #define LEDC_DIV_NUM_HSTIMER0_V LEDC_CLK_DIV_LSTIMER0_V +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#define LAST_CHAN (7) +#define LEDC_DIV_NUM_HSTIMER0_V LEDC_CLK_DIV_LSTIMER0_V #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -111,8 +117,7 @@ static void _ledcSetupTimer(uint8_t chan, uint32_t div_num, uint8_t bit_num, boo static uint16_t _activeChannels = 0; if(!tHasStarted) { tHasStarted = true; - DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_LEDC_CLK_EN); - DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_LEDC_RST); + periph_module_enable(PERIPH_LEDC_MODULE); LEDC.conf.apb_clk_sel = 1;//LS use apb clock addApbChangeCallback((void*)&_activeChannels, _on_apb_change); @@ -302,7 +307,7 @@ void ledcAttachPin(uint8_t pin, uint8_t chan) return; } pinMode(pin, OUTPUT); -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 pinMatrixOutAttach(pin, LEDC_LS_SIG_OUT0_IDX + chan, false, false); #else pinMatrixOutAttach(pin, ((chan/8)?LEDC_LS_SIG_OUT0_IDX:LEDC_HS_SIG_OUT0_IDX) + (chan%8), false, false); diff --git a/cores/esp32/esp32-hal-matrix.c b/cores/esp32/esp32-hal-matrix.c index caa58d86..3d6069b8 100644 --- a/cores/esp32/esp32-hal-matrix.c +++ b/cores/esp32/esp32-hal-matrix.c @@ -21,6 +21,8 @@ #include "esp32/rom/gpio.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/gpio.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/gpio.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif diff --git a/cores/esp32/esp32-hal-misc.c b/cores/esp32/esp32-hal-misc.c index e640b36a..784ef573 100644 --- a/cores/esp32/esp32-hal-misc.c +++ b/cores/esp32/esp32-hal-misc.c @@ -40,6 +40,8 @@ #include "esp32/rom/rtc.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/rtc.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif diff --git a/cores/esp32/esp32-hal-rmt.c b/cores/esp32/esp32-hal-rmt.c index 345a3c5a..4927bede 100644 --- a/cores/esp32/esp32-hal-rmt.c +++ b/cores/esp32/esp32-hal-rmt.c @@ -28,15 +28,27 @@ */ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 #define MAX_CHANNELS 8 +#define MAX_DATA_PER_CHANNEL 64 +#define MAX_DATA_PER_ITTERATION 62 #elif CONFIG_IDF_TARGET_ESP32S2 #define MAX_CHANNELS 4 +#define MAX_DATA_PER_CHANNEL 64 +#define MAX_DATA_PER_ITTERATION 62 +#elif CONFIG_IDF_TARGET_ESP32C3 +#define MAX_CHANNELS 4 +#define MAX_DATA_PER_CHANNEL 48 +#define MAX_DATA_PER_ITTERATION 46 #else #error Target CONFIG_IDF_TARGET is not supported #endif -#define MAX_DATA_PER_CHANNEL 64 -#define MAX_DATA_PER_ITTERATION 62 #define _ABS(a) (a>0?a:-a) #define _LIMIT(a,b) (a>b?b:a) +#if CONFIG_IDF_TARGET_ESP32C3 +#define _INT_TX_END(channel) (1<<(channel)) +#define _INT_RX_END(channel) (4<<(channel)) +#define _INT_ERROR(channel) (16<<(channel)) +#define _INT_THR_EVNT(channel) (256<<(channel)) +#else #define __INT_TX_END (1) #define __INT_RX_END (2) #define __INT_ERROR (4) @@ -46,6 +58,7 @@ #define _INT_RX_END(channel) (__INT_RX_END<<(channel*3)) #define _INT_ERROR(channel) (__INT_ERROR<<(channel*3)) #define _INT_THR_EVNT(channel) ((__INT_THR_EVNT)<<(channel)) +#endif #if CONFIG_DISABLE_HAL_LOCKS # define RMT_MUTEX_LOCK(channel) @@ -55,7 +68,7 @@ # define RMT_MUTEX_UNLOCK(channel) xSemaphoreGive(g_rmt_objlocks[channel]) #endif /* CONFIG_DISABLE_HAL_LOCKS */ -#define _RMT_INTERNAL_DEBUG +//#define _RMT_INTERNAL_DEBUG #ifdef _RMT_INTERNAL_DEBUG # define DEBUG_INTERRUPT_START(pin) digitalWrite(pin, 1); # define DEBUG_INTERRUPT_END(pin) digitalWrite(pin, 0); @@ -162,12 +175,17 @@ bool rmtSetCarrier(rmt_obj_t* rmt, bool carrier_en, bool carrier_level, uint32_t size_t channel = rmt->channel; RMT_MUTEX_LOCK(channel); - +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_carrier[channel].low = low; + RMT.tx_carrier[channel].high = high; + RMT.rx_conf[channel].conf0.carrier_en = carrier_en; + RMT.rx_conf[channel].conf0.carrier_out_lv = carrier_level; +#else RMT.carrier_duty_ch[channel].low = low; RMT.carrier_duty_ch[channel].high = high; RMT.conf_ch[channel].conf0.carrier_en = carrier_en; RMT.conf_ch[channel].conf0.carrier_out_lv = carrier_level; - +#endif RMT_MUTEX_UNLOCK(channel); return true; @@ -183,8 +201,13 @@ bool rmtSetFilter(rmt_obj_t* rmt, bool filter_en, uint32_t filter_level) RMT_MUTEX_LOCK(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.rx_filter_thres = filter_level; + RMT.rx_conf[channel].conf1.rx_filter_en = filter_en; +#else RMT.conf_ch[channel].conf1.rx_filter_thres = filter_level; RMT.conf_ch[channel].conf1.rx_filter_en = filter_en; +#endif RMT_MUTEX_UNLOCK(channel); @@ -200,7 +223,11 @@ bool rmtSetRxThreshold(rmt_obj_t* rmt, uint32_t value) size_t channel = rmt->channel; RMT_MUTEX_LOCK(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf0.idle_thres = value; +#else RMT.conf_ch[channel].conf0.idle_thres = value; +#endif RMT_MUTEX_UNLOCK(channel); return true; @@ -265,7 +292,7 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size) int channel = rmt->channel; int allocated_size = MAX_DATA_PER_CHANNEL * rmt->buffers; - if (size > allocated_size) { + if (size > (allocated_size - 1)) { int half_tx_nr = MAX_DATA_PER_ITTERATION/2; RMT_MUTEX_LOCK(channel); @@ -279,6 +306,18 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size) rmt->intr_mode = E_TX_INTR | E_TXTHR_INTR; rmt->tx_state = E_SET_CONTI | E_FIRST_HALF; +#if CONFIG_IDF_TARGET_ESP32C3 + //uint32_t val = RMT.tx_conf[channel].val; + // init the tx limit for interruption + RMT.tx_lim[channel].limit = half_tx_nr+2; + //RMT.tx_conf[channel].val = val; + //RMT.tx_conf[channel].conf_update = 1; + // reset memory pointer + RMT.tx_conf[channel].mem_rst = 1; + //RMT.tx_conf[channel].mem_rst = 0; + RMT.tx_conf[channel].mem_rd_rst = 1; + //RMT.tx_conf[channel].mem_rd_rst = 0; +#else // init the tx limit for interruption RMT.tx_lim_ch[channel].limit = half_tx_nr+2; // reset memory pointer @@ -288,9 +327,9 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size) RMT.conf_ch[channel].conf1.mem_rd_rst = 0; RMT.conf_ch[channel].conf1.mem_wr_rst = 1; RMT.conf_ch[channel].conf1.mem_wr_rst = 0; - +#endif // set the tx end mark - RMTMEM.chan[channel].data32[MAX_DATA_PER_ITTERATION].val = 0; + //RMTMEM.chan[channel].data32[MAX_DATA_PER_ITTERATION].val = 0; // clear and enable both Tx completed and half tx event RMT.int_clr.val = _INT_TX_END(channel); @@ -304,6 +343,7 @@ bool rmtWrite(rmt_obj_t* rmt, rmt_data_t* data, size_t size) RMT_MUTEX_UNLOCK(channel); // start the transation + //return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION, true); return _rmtSendOnce(rmt, data, MAX_DATA_PER_ITTERATION, false); } else { // use one-go mode if data fits one buffer @@ -342,10 +382,15 @@ bool rmtBeginReceive(rmt_obj_t* rmt) RMT.int_clr.val = _INT_ERROR(channel); RMT.int_ena.val |= _INT_ERROR(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.mem_owner = 1; + RMT.rx_conf[channel].conf1.mem_wr_rst = 1; + RMT.rx_conf[channel].conf1.rx_en = 1; +#else RMT.conf_ch[channel].conf1.mem_owner = 1; RMT.conf_ch[channel].conf1.mem_wr_rst = 1; RMT.conf_ch[channel].conf1.rx_en = 1; - +#endif return true; } @@ -384,17 +429,26 @@ bool rmtRead(rmt_obj_t* rmt, rmt_rx_data_cb_t cb, void * arg) rmt->data_alloc = true; } +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.mem_owner = 1; +#else RMT.conf_ch[channel].conf1.mem_owner = 1; - +#endif RMT.int_clr.val = _INT_RX_END(channel); RMT.int_clr.val = _INT_ERROR(channel); RMT.int_ena.val |= _INT_RX_END(channel); RMT.int_ena.val |= _INT_ERROR(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.mem_wr_rst = 1; + + RMT.rx_conf[channel].conf1.rx_en = 1; +#else RMT.conf_ch[channel].conf1.mem_wr_rst = 1; RMT.conf_ch[channel].conf1.rx_en = 1; +#endif RMT_MUTEX_UNLOCK(channel); return true; @@ -407,7 +461,11 @@ bool rmtEnd(rmt_obj_t* rmt) { int channel = rmt->channel; RMT_MUTEX_LOCK(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.rx_en = 1; +#else RMT.conf_ch[channel].conf1.rx_en = 1; +#endif RMT_MUTEX_UNLOCK(channel); return true; @@ -437,7 +495,11 @@ bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag RMT_MUTEX_LOCK(channel); rmt->intr_mode = E_RX_INTR; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.mem_owner = 1; +#else RMT.conf_ch[channel].conf1.mem_owner = 1; +#endif RMT.int_clr.val = _INT_RX_END(channel); RMT.int_clr.val = _INT_ERROR(channel); @@ -445,9 +507,15 @@ bool rmtReadAsync(rmt_obj_t* rmt, rmt_data_t* data, size_t size, void* eventFlag RMT.int_ena.val |= _INT_RX_END(channel); RMT.int_ena.val |= _INT_ERROR(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[channel].conf1.mem_wr_rst = 1; + + RMT.rx_conf[channel].conf1.rx_en = 1; +#else RMT.conf_ch[channel].conf1.mem_wr_rst = 1; RMT.conf_ch[channel].conf1.rx_en = 1; +#endif RMT_MUTEX_UNLOCK(channel); // wait for data if requested so @@ -474,14 +542,20 @@ float rmtSetTick(rmt_obj_t* rmt, float tick) * rmt tick for 1 MHz -> 1us (1x) div_cnt = 0x01 256us (256x) div_cnt = 0x00 */ - int apb_div = _LIMIT(tick/12.5, 256); - int ref_div = _LIMIT(tick/1000, 256); - - float apb_tick = 12.5 * apb_div; - float ref_tick = 1000.0 * ref_div; size_t channel = rmt->channel; +#if CONFIG_IDF_TARGET_ESP32C3 + int apb_div = _LIMIT(tick/25.0, 256); + float apb_tick = 25.0 * apb_div; + RMT.tx_conf[channel].div_cnt = apb_div & 0xFF; + RMT.tx_conf[channel].conf_update = 1; + return apb_tick; +#else + int apb_div = _LIMIT(tick/12.5, 256); + int ref_div = _LIMIT(tick/1000, 256); + float apb_tick = 12.5 * apb_div; + float ref_tick = 1000.0 * ref_div; if (_ABS(apb_tick - tick) < _ABS(ref_tick - tick)) { RMT.conf_ch[channel].conf0.div_cnt = apb_div & 0xFF; RMT.conf_ch[channel].conf1.ref_always_on = 1; @@ -491,6 +565,7 @@ float rmtSetTick(rmt_obj_t* rmt, float tick) RMT.conf_ch[channel].conf1.ref_always_on = 0; return ref_tick; } +#endif } rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize) @@ -553,6 +628,47 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize) // - no carrier, filter // - timebase tick of 1us // - idle threshold set to 0x8000 (max pulse width + 1) +#if CONFIG_IDF_TARGET_ESP32C3 + + RMT.sys_conf.fifo_mask = 1; + + if (tx_not_rx) { + RMT.tx_lim[channel].limit = MAX_DATA_PER_ITTERATION/2 + 2; + RMT.tx_conf[channel].val = 0; +// RMT.tx_conf[channel].carrier_en = 0; +// RMT.tx_conf[channel].carrier_out_lv = 0; +// RMT.tx_conf[channel].tx_conti_mode = 0; +// RMT.tx_conf[channel].idle_out_lv = 0; // signal level for idle +// RMT.tx_conf[channel].tx_start = 0; +// RMT.tx_conf[channel].tx_stop = 0; +// RMT.tx_conf[channel].carrier_eff_en = 0; +// RMT.tx_conf[channel].afifo_rst = 0; +// RMT.tx_conf[channel].conf_update = 0; +// RMT.tx_conf[channel].mem_tx_wrap_en = 0; +// RMT.tx_conf[channel].mem_rst = 1; + + RMT.tx_conf[channel].idle_out_en = 1; // enable idle + RMT.tx_conf[channel].div_cnt = 1; + RMT.tx_conf[channel].mem_size = buffers; + RMT.tx_conf[channel].mem_rd_rst = 1; + RMT.tx_conf[channel].conf_update = 1; + } else { + RMT.rx_conf[channel].conf0.div_cnt = 1; + RMT.rx_conf[channel].conf0.mem_size = buffers; + RMT.rx_conf[channel].conf0.carrier_en = 0; + RMT.rx_conf[channel].conf0.carrier_out_lv = 0; + RMT.rx_conf[channel].conf0.idle_thres = 0x80; + RMT.rx_conf[channel].conf1.rx_filter_en = 0; + RMT.rx_conf[channel].conf1.rx_filter_thres = 0; + RMT.rx_conf[channel].conf1.mem_rst = 0; + RMT.rx_conf[channel].conf1.mem_rx_wrap_en = 0; + RMT.rx_conf[channel].conf1.afifo_rst = 0; + RMT.rx_conf[channel].conf1.conf_update = 0; + RMT.rx_conf[channel].conf1.rx_en = 1; + RMT.rx_conf[channel].conf1.mem_owner = 1; + RMT.rx_conf[channel].conf1.mem_wr_rst = 1; + } +#else RMT.conf_ch[channel].conf0.div_cnt = 1; RMT.conf_ch[channel].conf0.mem_size = buffers; RMT.conf_ch[channel].conf0.carrier_en = 0; @@ -585,7 +701,7 @@ rmt_obj_t* rmtInit(int pin, bool tx_not_rx, rmt_reserve_memsize_t memsize) RMT.conf_ch[channel].conf1.mem_owner = 1; RMT.conf_ch[channel].conf1.mem_wr_rst = 1; } - +#endif // install interrupt if at least one channel is active if (!intr_handle) { esp_intr_alloc(ETS_RMT_INTR_SOURCE, (int)ARDUINO_ISR_FLAG, _rmt_isr, NULL, &intr_handle); @@ -604,7 +720,11 @@ bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size, bool continuous return false; } int channel = rmt->channel; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.sys_conf.fifo_mask = 1; +#else RMT.apb_conf.fifo_mask = 1; +#endif if (data && size>0) { size_t i; volatile uint32_t* rmt_mem_ptr = &(RMTMEM.chan[channel].data32[0].val); @@ -616,9 +736,15 @@ bool _rmtSendOnce(rmt_obj_t* rmt, rmt_data_t* data, size_t size, bool continuous } RMT_MUTEX_LOCK(channel); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[channel].tx_conti_mode = continuous; + RMT.tx_conf[channel].mem_rd_rst = 1; + RMT.tx_conf[channel].tx_start = 1; +#else RMT.conf_ch[channel].conf1.tx_conti_mode = continuous; RMT.conf_ch[channel].conf1.mem_rd_rst = 1; RMT.conf_ch[channel].conf1.tx_start = 1; +#endif RMT_MUTEX_UNLOCK(channel); return true; @@ -643,6 +769,7 @@ static void _initPin(int pin, int channel, bool tx_not_rx) { if (!periph_enabled) { periph_enabled = true; + periph_module_reset( PERIPH_RMT_MODULE ); periph_module_enable( PERIPH_RMT_MODULE ); } if (tx_not_rx) { @@ -658,6 +785,7 @@ static void _initPin(int pin, int channel, bool tx_not_rx) static void ARDUINO_ISR_ATTR _rmt_isr(void* arg) { + //DEBUG_INTERRUPT_START(4); int intr_val = RMT.int_st.val; size_t ch; for (ch = 0; ch < MAX_CHANNELS; ch++) { @@ -692,9 +820,15 @@ static void ARDUINO_ISR_ATTR _rmt_isr(void* arg) (g_rmt_objects[ch].cb)(data_received, _rmt_get_mem_len(ch), g_rmt_objects[ch].arg); // restart the reception +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.rx_conf[ch].conf1.mem_owner = 1; + RMT.rx_conf[ch].conf1.mem_wr_rst = 1; + RMT.rx_conf[ch].conf1.rx_en = 1; +#else RMT.conf_ch[ch].conf1.mem_owner = 1; RMT.conf_ch[ch].conf1.mem_wr_rst = 1; RMT.conf_ch[ch].conf1.rx_en = 1; +#endif RMT.int_ena.val |= _INT_RX_END(ch); } else { // if not callback provide, expect only one Rx @@ -720,10 +854,17 @@ static void ARDUINO_ISR_ATTR _rmt_isr(void* arg) xEventGroupSetBits(g_rmt_objects[ch].events, RMT_FLAG_ERROR); } // reset memory +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[ch].mem_rd_rst = 1; + RMT.tx_conf[ch].mem_rd_rst = 0; + RMT.rx_conf[ch].conf1.mem_wr_rst = 1; + RMT.rx_conf[ch].conf1.mem_wr_rst = 0; +#else RMT.conf_ch[ch].conf1.mem_rd_rst = 1; RMT.conf_ch[ch].conf1.mem_rd_rst = 0; RMT.conf_ch[ch].conf1.mem_wr_rst = 1; RMT.conf_ch[ch].conf1.mem_wr_rst = 0; +#endif } if (intr_val & _INT_TX_END(ch)) { @@ -735,15 +876,24 @@ static void ARDUINO_ISR_ATTR _rmt_isr(void* arg) if (intr_val & _INT_THR_EVNT(ch)) { // clear the flag RMT.int_clr.val = _INT_THR_EVNT(ch); +#if CONFIG_IDF_TARGET_ESP32C3 + //RMT.int_clr.val = _INT_TX_END(ch); + //RMT.int_ena.val |= _INT_TX_END(ch); +#endif // initial setup of continuous mode if (g_rmt_objects[ch].tx_state & E_SET_CONTI) { +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[ch].tx_conti_mode = 1; +#else RMT.conf_ch[ch].conf1.tx_conti_mode = 1; +#endif g_rmt_objects[ch].intr_mode &= ~E_SET_CONTI; } _rmt_tx_mem_first(ch); } } + //DEBUG_INTERRUPT_END(4); } static void ARDUINO_ISR_ATTR _rmt_tx_mem_second(uint8_t ch) @@ -753,14 +903,23 @@ static void ARDUINO_ISR_ATTR _rmt_tx_mem_second(uint8_t ch) int half_tx_nr = MAX_DATA_PER_ITTERATION/2; int i; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_lim[ch].limit = half_tx_nr+2; +#else RMT.tx_lim_ch[ch].limit = half_tx_nr+2; +#endif RMT.int_clr.val = _INT_THR_EVNT(ch); RMT.int_ena.val |= _INT_THR_EVNT(ch); +#if CONFIG_IDF_TARGET_ESP32C3 + //RMT.int_clr.val = _INT_TX_END(ch); + //RMT.int_ena.val &= ~_INT_TX_END(ch); +#endif g_rmt_objects[ch].tx_state |= E_FIRST_HALF; if (data) { int remaining_size = g_rmt_objects[ch].data_size; + //ets_printf("RMT Tx[%d] %d\n", ch, remaining_size); // will the remaining data occupy the entire halfbuffer if (remaining_size > half_tx_nr) { for (i = 0; i < half_tx_nr; i++) { @@ -779,17 +938,30 @@ static void ARDUINO_ISR_ATTR _rmt_tx_mem_second(uint8_t ch) g_rmt_objects[ch].data_ptr = NULL; } +#if CONFIG_IDF_TARGET_ESP32C3 + RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0; + RMT.tx_conf[ch].tx_start = 1; +#endif } else if ((!(g_rmt_objects[ch].tx_state & E_LAST_DATA)) && (!(g_rmt_objects[ch].tx_state & E_END_TRANS))) { + //ets_printf("RMT Tx finishing %d!\n", ch); for (i = 0; i < half_tx_nr; i++) { RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0x000F000F; } RMTMEM.chan[ch].data32[half_tx_nr+i].val = 0; g_rmt_objects[ch].tx_state |= E_LAST_DATA; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[ch].tx_conti_mode = 0; +#else RMT.conf_ch[ch].conf1.tx_conti_mode = 0; +#endif } else { - log_d("RMT Tx finished %d!\n", ch); + //ets_printf("RMT Tx finished %d!\n", ch); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[ch].tx_conti_mode = 0; +#else RMT.conf_ch[ch].conf1.tx_conti_mode = 0; +#endif RMT.int_ena.val &= ~_INT_TX_END(ch); RMT.int_ena.val &= ~_INT_THR_EVNT(ch); g_rmt_objects[ch].intr_mode = E_NO_INTR; @@ -805,10 +977,15 @@ static void ARDUINO_ISR_ATTR _rmt_tx_mem_first(uint8_t ch) int half_tx_nr = MAX_DATA_PER_ITTERATION/2; int i; RMT.int_ena.val &= ~_INT_THR_EVNT(ch); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_lim[ch].limit = 0; +#else RMT.tx_lim_ch[ch].limit = 0; +#endif if (data) { int remaining_size = g_rmt_objects[ch].data_size; + //ets_printf("RMT TxF[%d] %d\n", ch, remaining_size); // will the remaining data occupy the entire halfbuffer if (remaining_size > half_tx_nr) { @@ -819,7 +996,11 @@ static void ARDUINO_ISR_ATTR _rmt_tx_mem_first(uint8_t ch) g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF; // turn off the treshold interrupt RMT.int_ena.val &= ~_INT_THR_EVNT(ch); +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_lim[ch].limit = 0; +#else RMT.tx_lim_ch[ch].limit = 0; +#endif g_rmt_objects[ch].data_size -= half_tx_nr; g_rmt_objects[ch].data_ptr += half_tx_nr; } else { @@ -836,23 +1017,37 @@ static void ARDUINO_ISR_ATTR _rmt_tx_mem_first(uint8_t ch) g_rmt_objects[ch].data_ptr = NULL; } } else { + //ets_printf("RMT TxF finished %d!\n", ch); for (i = 0; i < half_tx_nr; i++) { RMTMEM.chan[ch].data32[i].val = 0x000F000F; } RMTMEM.chan[ch].data32[i].val = 0; g_rmt_objects[ch].tx_state &= ~E_FIRST_HALF; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_lim[ch].limit = 0; +#else RMT.tx_lim_ch[ch].limit = 0; +#endif g_rmt_objects[ch].tx_state |= E_LAST_DATA; +#if CONFIG_IDF_TARGET_ESP32C3 + RMT.tx_conf[ch].tx_conti_mode = 0; +#else RMT.conf_ch[ch].conf1.tx_conti_mode = 0; +#endif } DEBUG_INTERRUPT_END(2); } static int ARDUINO_ISR_ATTR _rmt_get_mem_len(uint8_t channel) { +#if CONFIG_IDF_TARGET_ESP32C3 + int block_num = RMT.rx_conf[channel].conf0.mem_size; + int item_block_len = block_num * 48; +#else int block_num = RMT.conf_ch[channel].conf0.mem_size; int item_block_len = block_num * 64; +#endif volatile rmt_item32_t* data = RMTMEM.chan[channel].data32; int idx; for(idx = 0; idx < item_block_len; idx++) { diff --git a/cores/esp32/esp32-hal-sigmadelta.c b/cores/esp32/esp32-hal-sigmadelta.c index 41b9bc55..4aa778ee 100644 --- a/cores/esp32/esp32-hal-sigmadelta.c +++ b/cores/esp32/esp32-hal-sigmadelta.c @@ -26,6 +26,8 @@ #include "esp32/rom/ets_sys.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/ets_sys.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif diff --git a/cores/esp32/esp32-hal-spi.c b/cores/esp32/esp32-hal-spi.c index c9a7c128..c2671836 100644 --- a/cores/esp32/esp32-hal-spi.c +++ b/cores/esp32/esp32-hal-spi.c @@ -22,19 +22,25 @@ #include "soc/spi_struct.h" #include "soc/io_mux_reg.h" #include "soc/gpio_sig_map.h" -#include "soc/dport_reg.h" #include "soc/rtc.h" +#include "driver/periph_ctrl.h" #include "esp_system.h" #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 +#include "soc/dport_reg.h" #include "esp32/rom/ets_sys.h" #include "esp32/rom/gpio.h" #include "esp_intr_alloc.h" #elif CONFIG_IDF_TARGET_ESP32S2 +#include "soc/dport_reg.h" #include "esp32s2/rom/ets_sys.h" #include "esp32s2/rom/gpio.h" #include "esp_intr_alloc.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#include "esp32c3/rom/gpio.h" +#include "esp_intr_alloc.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -62,11 +68,24 @@ struct spi_struct_t { #define SPI_SPI_SS_IDX(n) ((n==0)?SPICS0_OUT_IDX:((n==1)?SPICS1_OUT_IDX:0)) #define SPI_HSPI_SS_IDX(n) ((n==0)?SPI3_CS0_OUT_IDX:((n==1)?SPI3_CS1_OUT_IDX:((n==2)?SPI3_CS2_OUT_IDX:SPI3_CS0_OUT_IDX))) -#define SPI_FSPI_SS_IDX(n) ((n==0)?FSPICS0_OUT_IDX:((n==1)?FSPICS1_OUT_IDX:((n==2)?FSPICS2_OUT_IDX:VSPICS0_OUT_IDX))) +#define SPI_FSPI_SS_IDX(n) ((n==0)?FSPICS0_OUT_IDX:((n==1)?FSPICS1_OUT_IDX:((n==2)?FSPICS2_OUT_IDX:FSPICS0_OUT_IDX))) #define SPI_SS_IDX(p, n) ((p==0)?SPI_SPI_SS_IDX(n):((p==1)?SPI_SPI_SS_IDX(n):((p==2)?SPI_HSPI_SS_IDX(n):0))) #define SPI_INTR_SOURCE(u) ((u==0)?ETS_SPI1_INTR_SOURCE:((u==1)?ETS_SPI2_INTR_SOURCE:((u==2)?ETS_SPI3_INTR_SOURCE:0))) +#elif CONFIG_IDF_TARGET_ESP32C3 +// ESP32S2 +#define SPI_COUNT (1) + +#define SPI_CLK_IDX(p) FSPICLK_OUT_IDX +#define SPI_MISO_IDX(p) FSPIQ_OUT_IDX +#define SPI_MOSI_IDX(p) FSPID_IN_IDX + +#define SPI_SPI_SS_IDX(n) ((n==0)?FSPICS0_OUT_IDX:((n==1)?FSPICS1_OUT_IDX:((n==2)?FSPICS2_OUT_IDX:FSPICS0_OUT_IDX))) +#define SPI_SS_IDX(p, n) SPI_SPI_SS_IDX(n) + +#define SPI_INTR_SOURCE(u) ETS_SPI2_INTR_SOURCE + #else // ESP32 #define SPI_COUNT (4) @@ -109,6 +128,8 @@ static spi_t _spi_bus_array[] = { {(volatile spi_dev_t *)(DR_REG_SPI1_BASE), NULL, 0}, {(volatile spi_dev_t *)(DR_REG_SPI2_BASE), NULL, 1}, {(volatile spi_dev_t *)(DR_REG_SPI3_BASE), NULL, 2} +#elif CONFIG_IDF_TARGET_ESP32C3 + {(volatile spi_dev_t *)(&GPSPI2), NULL, FSPI} #else {(volatile spi_dev_t *)(DR_REG_SPI0_BASE), NULL, 0}, {(volatile spi_dev_t *)(DR_REG_SPI1_BASE), NULL, 1}, @@ -131,7 +152,7 @@ void spiAttachSCK(spi_t * spi, int8_t sck) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { sck = 14; } else if(spi->num == VSPI) { @@ -139,6 +160,9 @@ void spiAttachSCK(spi_t * spi, int8_t sck) } else { sck = 6; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMode(sck, OUTPUT); @@ -158,7 +182,7 @@ void spiAttachMISO(spi_t * spi, int8_t miso) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { miso = 12; } else if(spi->num == VSPI) { @@ -166,6 +190,9 @@ void spiAttachMISO(spi_t * spi, int8_t miso) } else { miso = 7; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } SPI_MUTEX_LOCK(); @@ -187,7 +214,7 @@ void spiAttachMOSI(spi_t * spi, int8_t mosi) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { mosi = 13; } else if(spi->num == VSPI) { @@ -195,6 +222,9 @@ void spiAttachMOSI(spi_t * spi, int8_t mosi) } else { mosi = 8; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMode(mosi, OUTPUT); @@ -214,7 +244,7 @@ void spiDetachSCK(spi_t * spi, int8_t sck) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { sck = 14; } else if(spi->num == VSPI) { @@ -222,6 +252,9 @@ void spiDetachSCK(spi_t * spi, int8_t sck) } else { sck = 6; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMatrixOutDetach(sck, false, false); @@ -241,7 +274,7 @@ void spiDetachMISO(spi_t * spi, int8_t miso) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { miso = 12; } else if(spi->num == VSPI) { @@ -249,6 +282,9 @@ void spiDetachMISO(spi_t * spi, int8_t miso) } else { miso = 7; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMatrixInDetach(SPI_MISO_IDX(spi->num), false, false); @@ -268,7 +304,7 @@ void spiDetachMOSI(spi_t * spi, int8_t mosi) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { mosi = 13; } else if(spi->num == VSPI) { @@ -276,6 +312,9 @@ void spiDetachMOSI(spi_t * spi, int8_t mosi) } else { mosi = 8; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMatrixOutDetach(mosi, false, false); @@ -299,7 +338,7 @@ void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { ss = 15; } else if(spi->num == VSPI) { @@ -307,6 +346,9 @@ void spiAttachSS(spi_t * spi, uint8_t cs_num, int8_t ss) } else { ss = 11; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMode(ss, OUTPUT); @@ -327,7 +369,7 @@ void spiDetachSS(spi_t * spi, int8_t ss) log_e("HSPI Does not have default pins on ESP32S2!"); return; } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi->num == HSPI) { ss = 15; } else if(spi->num == VSPI) { @@ -335,6 +377,9 @@ void spiDetachSS(spi_t * spi, int8_t ss) } else { ss = 11; } +#elif CONFIG_IDF_TARGET_ESP32C3 + log_e("SPI Does not have default pins on ESP32C3!"); + return; #endif } pinMatrixOutDetach(ss, false, false); @@ -347,7 +392,7 @@ void spiEnableSSPins(spi_t * spi, uint8_t cs_mask) return; } SPI_MUTEX_LOCK(); -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.val &= ~(cs_mask & SPI_CS_MASK_ALL); #else spi->dev->pin.val &= ~(cs_mask & SPI_CS_MASK_ALL); @@ -361,7 +406,7 @@ void spiDisableSSPins(spi_t * spi, uint8_t cs_mask) return; } SPI_MUTEX_LOCK(); -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.val |= (cs_mask & SPI_CS_MASK_ALL); #else spi->dev->pin.val |= (cs_mask & SPI_CS_MASK_ALL); @@ -397,7 +442,7 @@ void spiSSSet(spi_t * spi) return; } SPI_MUTEX_LOCK(); -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.cs_keep_active = 1; #else spi->dev->pin.cs_keep_active = 1; @@ -411,7 +456,7 @@ void spiSSClear(spi_t * spi) return; } SPI_MUTEX_LOCK(); -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.cs_keep_active = 0; #else spi->dev->pin.cs_keep_active = 0; @@ -442,7 +487,7 @@ uint8_t spiGetDataMode(spi_t * spi) if(!spi) { return 0; } -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 bool idleEdge = spi->dev->misc.ck_idle_edge; #else bool idleEdge = spi->dev->pin.ck_idle_edge; @@ -468,7 +513,7 @@ void spiSetDataMode(spi_t * spi, uint8_t dataMode) SPI_MUTEX_LOCK(); switch (dataMode) { case SPI_MODE1: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 0; #else spi->dev->pin.ck_idle_edge = 0; @@ -476,7 +521,7 @@ void spiSetDataMode(spi_t * spi, uint8_t dataMode) spi->dev->user.ck_out_edge = 1; break; case SPI_MODE2: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 1; #else spi->dev->pin.ck_idle_edge = 1; @@ -484,7 +529,7 @@ void spiSetDataMode(spi_t * spi, uint8_t dataMode) spi->dev->user.ck_out_edge = 1; break; case SPI_MODE3: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 1; #else spi->dev->pin.ck_idle_edge = 1; @@ -493,7 +538,7 @@ void spiSetDataMode(spi_t * spi, uint8_t dataMode) break; case SPI_MODE0: default: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 0; #else spi->dev->pin.ck_idle_edge = 0; @@ -542,9 +587,11 @@ static void _on_apb_change(void * arg, apb_change_ev_t ev_type, uint32_t old_apb static void spiInitBus(spi_t * spi) { +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->slave.trans_done = 0; - spi->dev->slave.slave_mode = 0; -#if CONFIG_IDF_TARGET_ESP32S2 +#endif + spi->dev->slave.val = 0; +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.val = 0; #else spi->dev->pin.val = 0; @@ -552,8 +599,15 @@ static void spiInitBus(spi_t * spi) spi->dev->user.val = 0; spi->dev->user1.val = 0; spi->dev->ctrl.val = 0; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->ctrl1.val = 0; spi->dev->ctrl2.val = 0; +#else + spi->dev->clk_gate.val = 0; + spi->dev->dma_conf.val = 0; + spi->dev->dma_conf.rx_afifo_rst = 1; + spi->dev->dma_conf.buf_afifo_rst = 1; +#endif spi->dev->clock.val = 0; } @@ -598,7 +652,7 @@ spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_ DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI01_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI01_RST); } -#else +#elif CONFIG_IDF_TARGET_ESP32 if(spi_num == HSPI) { DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI2_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI2_RST); @@ -609,14 +663,24 @@ spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_ DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_SPI01_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_SPI01_RST); } +#elif CONFIG_IDF_TARGET_ESP32C3 + periph_module_reset( PERIPH_SPI2_MODULE ); + periph_module_enable( PERIPH_SPI2_MODULE ); #endif SPI_MUTEX_LOCK(); spiInitBus(spi); +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->clk_gate.clk_en = 1; + spi->dev->clk_gate.mst_clk_sel = 1; + spi->dev->clk_gate.mst_clk_active = 1; + spi->dev->dma_conf.tx_seg_trans_clr_en = 1; + spi->dev->dma_conf.rx_seg_trans_clr_en = 1; + spi->dev->dma_conf.dma_seg_trans_en = 0; +#endif spi->dev->user.usr_mosi = 1; spi->dev->user.usr_miso = 1; spi->dev->user.doutdin = 1; - int i; for(i=0; i<16; i++) { spi->dev->data_buf[i] = 0x00000000; @@ -628,6 +692,7 @@ spi_t * spiStartBus(uint8_t spi_num, uint32_t clockDiv, uint8_t dataMode, uint8_ spiSetClockDiv(spi, clockDiv); addApbChangeCallback(spi, _on_apb_change); + return spi; } @@ -642,6 +707,11 @@ void spiWaitReady(spi_t * spi) #if CONFIG_IDF_TARGET_ESP32S2 #define usr_mosi_dbitlen usr_mosi_bit_len #define usr_miso_dbitlen usr_miso_bit_len +#elif CONFIG_IDF_TARGET_ESP32C3 +#define usr_mosi_dbitlen ms_data_bitlen +#define usr_miso_dbitlen ms_data_bitlen +#define mosi_dlen ms_dlen +#define miso_dlen ms_dlen #endif void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len) @@ -655,10 +725,16 @@ void spiWrite(spi_t * spi, const uint32_t *data, uint8_t len) } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = (len * 32) - 1; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif for(i=0; idev->data_buf[i] = data[i]; } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); SPI_MUTEX_UNLOCK(); @@ -679,6 +755,10 @@ void spiTransfer(spi_t * spi, uint32_t *data, uint8_t len) for(i=0; idev->data_buf[i] = data[i]; } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); for(i=0; idev->mosi_dlen.usr_mosi_dbitlen = 7; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); SPI_MUTEX_UNLOCK(); @@ -710,6 +796,10 @@ uint8_t spiTransferByte(spi_t * spi, uint8_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 7; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0] & 0xFF; @@ -737,8 +827,14 @@ void spiWriteWord(spi_t * spi, uint16_t data) } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); SPI_MUTEX_UNLOCK(); @@ -756,6 +852,10 @@ uint16_t spiTransferWord(spi_t * spi, uint16_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 15; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0]; @@ -776,8 +876,14 @@ void spiWriteLong(spi_t * spi, uint32_t data) } SPI_MUTEX_LOCK(); spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); SPI_MUTEX_UNLOCK(); @@ -795,6 +901,10 @@ uint32_t spiTransferLong(spi_t * spi, uint32_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 31; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0]; @@ -834,6 +944,10 @@ static void __spiTransferBytes(spi_t * spi, const uint8_t * data, uint8_t * out, spi->dev->data_buf[i] = wordsBuf[i]; //copy buffer to spi fifo } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); @@ -898,7 +1012,7 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi spi->dev->clock.val = clockDiv; switch (dataMode) { case SPI_MODE1: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 0; #else spi->dev->pin.ck_idle_edge = 0; @@ -906,7 +1020,7 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi spi->dev->user.ck_out_edge = 1; break; case SPI_MODE2: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 1; #else spi->dev->pin.ck_idle_edge = 1; @@ -914,7 +1028,7 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi spi->dev->user.ck_out_edge = 1; break; case SPI_MODE3: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 1; #else spi->dev->pin.ck_idle_edge = 1; @@ -923,7 +1037,7 @@ void spiTransaction(spi_t * spi, uint32_t clockDiv, uint8_t dataMode, uint8_t bi break; case SPI_MODE0: default: -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 spi->dev->misc.ck_idle_edge = 0; #else spi->dev->pin.ck_idle_edge = 0; @@ -962,8 +1076,14 @@ void ARDUINO_ISR_ATTR spiWriteByteNL(spi_t * spi, uint8_t data) return; } spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); } @@ -976,6 +1096,10 @@ uint8_t spiTransferByteNL(spi_t * spi, uint8_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 7; spi->dev->miso_dlen.usr_miso_dbitlen = 7; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0] & 0xFF; @@ -991,8 +1115,14 @@ void ARDUINO_ISR_ATTR spiWriteShortNL(spi_t * spi, uint16_t data) MSB_16_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); } @@ -1008,6 +1138,10 @@ uint16_t spiTransferShortNL(spi_t * spi, uint16_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 15; spi->dev->miso_dlen.usr_miso_dbitlen = 15; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0] & 0xFFFF; @@ -1026,8 +1160,14 @@ void ARDUINO_ISR_ATTR spiWriteLongNL(spi_t * spi, uint32_t data) MSB_32_SET(data, data); } spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; +#ifndef CONFIG_IDF_TARGET_ESP32C3 spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); } @@ -1043,6 +1183,10 @@ uint32_t spiTransferLongNL(spi_t * spi, uint32_t data) spi->dev->mosi_dlen.usr_mosi_dbitlen = 31; spi->dev->miso_dlen.usr_miso_dbitlen = 31; spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0]; @@ -1053,6 +1197,9 @@ uint32_t spiTransferLongNL(spi_t * spi, uint32_t data) } void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len){ + if(!spi) { + return; + } size_t longs = len >> 2; if(len & 3){ longs++; @@ -1065,10 +1212,16 @@ void spiWriteNL(spi_t * spi, const void * data_in, uint32_t len){ c_longs = (longs > 16)?16:longs; spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1; - spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#ifndef CONFIG_IDF_TARGET_ESP32C3 + spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif for (int i=0; idev->data_buf[i] = data[i]; } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); @@ -1105,6 +1258,10 @@ void spiTransferBytesNL(spi_t * spi, const void * data_in, uint8_t * data_out, u spi->dev->data_buf[i] = 0xFFFFFFFF; } } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); if(result){ @@ -1160,6 +1317,10 @@ void spiTransferBitsNL(spi_t * spi, uint32_t data, uint32_t * out, uint8_t bits) spi->dev->mosi_dlen.usr_mosi_dbitlen = (bits - 1); spi->dev->miso_dlen.usr_miso_dbitlen = (bits - 1); spi->dev->data_buf[0] = data; +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); data = spi->dev->data_buf[0]; @@ -1192,7 +1353,9 @@ void ARDUINO_ISR_ATTR spiWritePixelsNL(spi_t * spi, const void * data_in, uint32 l_bytes = (c_len & 3); spi->dev->mosi_dlen.usr_mosi_dbitlen = (c_len*8)-1; - spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#ifndef CONFIG_IDF_TARGET_ESP32C3 + spi->dev->miso_dlen.usr_miso_dbitlen = 0; +#endif for (int i=0; idev->data_buf[i] = data[i]; } } +#if CONFIG_IDF_TARGET_ESP32C3 + spi->dev->cmd.update = 1; + while (spi->dev->cmd.update); +#endif spi->dev->cmd.usr = 1; while(spi->dev->cmd.usr); @@ -1230,7 +1397,12 @@ typedef union { uint32_t clkcnt_l: 6; /*it must be equal to spi_clkcnt_N.*/ uint32_t clkcnt_h: 6; /*it must be floor((spi_clkcnt_N+1)/2-1).*/ uint32_t clkcnt_n: 6; /*it is the divider of spi_clk. So spi_clk frequency is system/(spi_clkdiv_pre+1)/(spi_clkcnt_N+1)*/ +#if CONFIG_IDF_TARGET_ESP32C3 + uint32_t clkdiv_pre: 4; /*it is pre-divider of spi_clk.*/ + uint32_t reserved: 9; /*reserved*/ +#else uint32_t clkdiv_pre: 13; /*it is pre-divider of spi_clk.*/ +#endif uint32_t clk_equ_sysclk: 1; /*1: spi_clk is eqaul to system 0: spi_clk is divided from system clock.*/ }; } spiClk_t; @@ -1272,8 +1444,13 @@ uint32_t spiFrequencyToClockDiv(uint32_t freq) while(calPreVari++ <= 1) { calPre = (((apb_freq / (reg.clkcnt_n + 1)) / freq) - 1) + calPreVari; +#if CONFIG_IDF_TARGET_ESP32C3 + if(calPre > 0xF) { + reg.clkdiv_pre = 0xF; +#else if(calPre > 0x1FFF) { reg.clkdiv_pre = 0x1FFF; +#endif } else if(calPre <= 0) { reg.clkdiv_pre = 0; } else { diff --git a/cores/esp32/esp32-hal-spi.h b/cores/esp32/esp32-hal-spi.h index 835e5faf..6fbb7b3d 100644 --- a/cores/esp32/esp32-hal-spi.h +++ b/cores/esp32/esp32-hal-spi.h @@ -25,11 +25,16 @@ extern "C" { #define SPI_HAS_TRANSACTION +#if CONFIG_IDF_TARGET_ESP32C3 +#define FSPI 0 +#define HSPI 1 +#else #define FSPI 1 //SPI bus attached to the flash (can use the same data lines but different SS) #define HSPI 2 //SPI bus normally mapped to pins 12 - 15, but can be matrixed to any pins #if CONFIG_IDF_TARGET_ESP32 #define VSPI 3 //SPI bus normally attached to pins 5, 18, 19 and 23, but can be matrixed to any pins #endif +#endif // This defines are not representing the real Divider of the ESP32 // the Defines match to an AVR Arduino on 16MHz for better compatibility diff --git a/cores/esp32/esp32-hal-timer.c b/cores/esp32/esp32-hal-timer.c index cc80741f..d6570383 100644 --- a/cores/esp32/esp32-hal-timer.c +++ b/cores/esp32/esp32-hal-timer.c @@ -14,10 +14,12 @@ #include "esp32-hal-timer.h" #include "freertos/FreeRTOS.h" +#ifndef CONFIG_IDF_TARGET_ESP32C3 #include "freertos/xtensa_api.h" +#include "soc/dport_reg.h" +#endif #include "freertos/task.h" #include "soc/timer_group_struct.h" -#include "soc/dport_reg.h" #include "esp_attr.h" #include "driver/periph_ctrl.h" @@ -30,6 +32,10 @@ #include "esp32s2/rom/ets_sys.h" #include "esp_intr_alloc.h" #include "soc/periph_defs.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#include "esp_intr_alloc.h" +#include "soc/periph_defs.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -296,12 +302,15 @@ void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){ timer->dev->config.level_int_en = edge?0:1;//When set, an alarm will generate a level type interrupt. timer->dev->config.edge_int_en = edge?1:0;//When set, an alarm will generate an edge type interrupt. int intr_source = 0; +#ifndef CONFIG_IDF_TARGET_ESP32C3 if(!edge){ +#endif if(timer->group){ intr_source = ETS_TG1_T0_LEVEL_INTR_SOURCE + timer->timer; } else { intr_source = ETS_TG0_T0_LEVEL_INTR_SOURCE + timer->timer; } +#ifndef CONFIG_IDF_TARGET_ESP32C3 } else { if(timer->group){ intr_source = ETS_TG1_T0_EDGE_INTR_SOURCE + timer->timer; @@ -309,6 +318,7 @@ void timerAttachInterrupt(hw_timer_t *timer, void (*fn)(void), bool edge){ intr_source = ETS_TG0_T0_EDGE_INTR_SOURCE + timer->timer; } } +#endif if(!initialized){ initialized = true; esp_intr_alloc(intr_source, (int)(ARDUINO_ISR_FLAG|ESP_INTR_FLAG_LOWMED), __timerISR, NULL, &intr_handle); diff --git a/cores/esp32/esp32-hal-touch.c b/cores/esp32/esp32-hal-touch.c index e22cec76..dd45e480 100644 --- a/cores/esp32/esp32-hal-touch.c +++ b/cores/esp32/esp32-hal-touch.c @@ -13,13 +13,14 @@ // limitations under the License. #include "esp32-hal-touch.h" +#ifndef CONFIG_IDF_TARGET_ESP32C3 #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_attr.h" #include "soc/rtc_io_reg.h" -#include "soc/rtc_cntl_reg.h" #include "soc/sens_reg.h" #include "soc/sens_struct.h" +#include "soc/rtc_cntl_reg.h" #include "driver/touch_sensor.h" #include "esp_system.h" @@ -225,3 +226,4 @@ void __touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t thresh extern uint16_t touchRead(uint8_t pin) __attribute__ ((weak, alias("__touchRead"))); extern void touchAttachInterrupt(uint8_t pin, void (*userFunc)(void), uint16_t threshold) __attribute__ ((weak, alias("__touchAttachInterrupt"))); extern void touchSetCycles(uint16_t measure, uint16_t sleep) __attribute__ ((weak, alias("__touchSetCycles"))); +#endif diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c index 4634aa1d..ad01710a 100644 --- a/cores/esp32/esp32-hal-uart.c +++ b/cores/esp32/esp32-hal-uart.c @@ -23,19 +23,25 @@ #include "soc/uart_struct.h" #include "soc/io_mux_reg.h" #include "soc/gpio_sig_map.h" -#include "soc/dport_reg.h" #include "soc/rtc.h" +#include "hal/uart_ll.h" #include "esp_intr_alloc.h" #include "esp_system.h" #ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ #if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 +#include "soc/dport_reg.h" #include "esp32/rom/ets_sys.h" #include "esp32/rom/uart.h" #elif CONFIG_IDF_TARGET_ESP32S2 +#include "soc/dport_reg.h" #include "esp32s2/rom/ets_sys.h" #include "esp32s2/rom/uart.h" #include "soc/periph_defs.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#include "esp32c3/rom/uart.h" +#include "soc/periph_defs.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif @@ -45,18 +51,24 @@ #include "esp_intr.h" #endif -#if CONFIG_IDF_TARGET_ESP32S2 +#if CONFIG_IDF_TARGET_ESP32 +#define UART_PORTS_NUM 3 +#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:( (u==2)?DR_REG_UART2_BASE:0))) +#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:( (u==2)?U2RXD_IN_IDX:0))) +#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:( (u==2)?U2TXD_OUT_IDX:0))) +#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:((u==2)?ETS_UART2_INTR_SOURCE:0))) +#elif CONFIG_IDF_TARGET_ESP32S2 #define UART_PORTS_NUM 2 #define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:0)) #define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:0)) #define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:0)) #define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:0)) #else -#define UART_PORTS_NUM 3 -#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:( (u==2)?DR_REG_UART2_BASE:0))) -#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:( (u==2)?U2RXD_IN_IDX:0))) -#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:( (u==2)?U2TXD_OUT_IDX:0))) -#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:((u==2)?ETS_UART2_INTR_SOURCE:0))) +#define UART_PORTS_NUM 2 +#define UART_REG_BASE(u) ((u==0)?DR_REG_UART_BASE:( (u==1)?DR_REG_UART1_BASE:0)) +#define UART_RXD_IDX(u) ((u==0)?U0RXD_IN_IDX:( (u==1)?U1RXD_IN_IDX:0)) +#define UART_TXD_IDX(u) ((u==0)?U0TXD_OUT_IDX:( (u==1)?U1TXD_OUT_IDX:0)) +#define UART_INTR_SOURCE(u) ((u==0)?ETS_UART0_INTR_SOURCE:( (u==1)?ETS_UART1_INTR_SOURCE:0)) #endif static int s_uart_debug_nr = 0; @@ -225,6 +237,9 @@ uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rx return NULL; } } +#if CONFIG_IDF_TARGET_ESP32C3 + +#else if(uart_nr == 1){ DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_UART1_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_UART1_RST); @@ -237,6 +252,7 @@ uart_t* uartBegin(uint8_t uart_nr, uint32_t baudrate, uint32_t config, int8_t rx DPORT_SET_PERI_REG_MASK(DPORT_PERIP_CLK_EN_REG, DPORT_UART_CLK_EN); DPORT_CLEAR_PERI_REG_MASK(DPORT_PERIP_RST_EN_REG, DPORT_UART_RST); } +#endif uartFlush(uart); uartSetBaudRate(uart, baudrate); UART_MUTEX_LOCK(); @@ -477,9 +493,7 @@ void uartSetBaudRate(uart_t* uart, uint32_t baud_rate) return; } UART_MUTEX_LOCK(); - uint32_t clk_div = ((getApbFrequency()<<4)/baud_rate); - uart->dev->clk_div.div_int = clk_div>>4 ; - uart->dev->clk_div.div_frag = clk_div & 0xf; + uart_ll_set_baudrate(uart->dev, baud_rate); UART_MUTEX_UNLOCK(); } @@ -676,15 +690,17 @@ unsigned long uartBaudrateDetect(uart_t *uart, bool flg) */ void uartStartDetectBaudrate(uart_t *uart) { if(!uart) return; - +#ifndef CONFIG_IDF_TARGET_ESP32C3 uart->dev->auto_baud.glitch_filt = 0x08; uart->dev->auto_baud.en = 0; uart->dev->auto_baud.en = 1; +#endif } unsigned long uartDetectBaudrate(uart_t *uart) { +#ifndef CONFIG_IDF_TARGET_ESP32C3 static bool uartStateDetectingBaudrate = false; if(!uartStateDetectingBaudrate) { @@ -719,6 +735,9 @@ uartDetectBaudrate(uart_t *uart) } return default_rates[i]; +#else + return 0; +#endif } /* diff --git a/libraries/BLE/examples/BLE_Beacon_Scanner/.skip.esp32c3 b/libraries/BLE/examples/BLE_Beacon_Scanner/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/.skip.esp32c3 b/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/.skip.esp32c3 b/libraries/BLE/examples/BLE_EddystoneURL_Beacon/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_client/.skip.esp32c3 b/libraries/BLE/examples/BLE_client/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_iBeacon/.skip.esp32c3 b/libraries/BLE/examples/BLE_iBeacon/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_notify/.skip.esp32c3 b/libraries/BLE/examples/BLE_notify/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_scan/.skip.esp32c3 b/libraries/BLE/examples/BLE_scan/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_server/.skip.esp32c3 b/libraries/BLE/examples/BLE_server/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_server_multiconnect/.skip.esp32c3 b/libraries/BLE/examples/BLE_server_multiconnect/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_uart/.skip.esp32c3 b/libraries/BLE/examples/BLE_uart/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BLE/examples/BLE_write/.skip.esp32c3 b/libraries/BLE/examples/BLE_write/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBT/.skip.esp32c3 b/libraries/BluetoothSerial/examples/SerialToSerialBT/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBTM/.skip.esp32c3 b/libraries/BluetoothSerial/examples/SerialToSerialBTM/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBT_SSP_pairing/.skip.esp32c3 b/libraries/BluetoothSerial/examples/SerialToSerialBT_SSP_pairing/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/BluetoothSerial/examples/bt_remove_paired_devices/.skip.esp32c3 b/libraries/BluetoothSerial/examples/bt_remove_paired_devices/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/AnalogOut/ledcWrite_RGB/ledcWrite_RGB.ino b/libraries/ESP32/examples/AnalogOut/ledcWrite_RGB/ledcWrite_RGB.ino index 633d1c08..c2697bc9 100644 --- a/libraries/ESP32/examples/AnalogOut/ledcWrite_RGB/ledcWrite_RGB.ino +++ b/libraries/ESP32/examples/AnalogOut/ledcWrite_RGB/ledcWrite_RGB.ino @@ -9,9 +9,9 @@ */ // Set up the rgb led names -uint8_t ledR = A4; -uint8_t ledG = A5; -uint8_t ledB = A18; +uint8_t ledR = 2; +uint8_t ledG = 4; +uint8_t ledB = 5; uint8_t ledArray[3] = {1, 2, 3}; // three led channels diff --git a/libraries/ESP32/examples/Camera/CameraWebServer/.skip.esp32c3 b/libraries/ESP32/examples/Camera/CameraWebServer/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/.skip.esp32c3 b/libraries/ESP32/examples/DeepSleep/ExternalWakeUp/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/DeepSleep/TouchWakeUp/.skip.esp32c3 b/libraries/ESP32/examples/DeepSleep/TouchWakeUp/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/HallSensor/.skip.esp32c3 b/libraries/ESP32/examples/HallSensor/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/I2S/HiFreq_ADC/.skip.esp32c3 b/libraries/ESP32/examples/I2S/HiFreq_ADC/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/ResetReason/ResetReason.ino b/libraries/ESP32/examples/ResetReason/ResetReason.ino index a3fbd65b..62889587 100644 --- a/libraries/ESP32/examples/ResetReason/ResetReason.ino +++ b/libraries/ESP32/examples/ResetReason/ResetReason.ino @@ -17,6 +17,8 @@ #include "esp32/rom/rtc.h" #elif CONFIG_IDF_TARGET_ESP32S2 #include "esp32s2/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/rtc.h" #else #error Target CONFIG_IDF_TARGET is not supported #endif diff --git a/libraries/ESP32/examples/Touch/TouchInterrupt/.skip.esp32c3 b/libraries/ESP32/examples/Touch/TouchInterrupt/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/ESP32/examples/Touch/TouchRead/.skip.esp32c3 b/libraries/ESP32/examples/Touch/TouchRead/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/LITTLEFS/examples/LITTLEFS_test/.skip.esp32c3 b/libraries/LITTLEFS/examples/LITTLEFS_test/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/LITTLEFS/examples/LITTLEFS_time/.skip.esp32c3 b/libraries/LITTLEFS/examples/LITTLEFS_time/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/RainMaker/examples/RMakerDevice/.skip.esp32c3 b/libraries/RainMaker/examples/RMakerDevice/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/SD/src/sd_diskio.cpp b/libraries/SD/src/sd_diskio.cpp index 87253cf1..88542a95 100644 --- a/libraries/SD/src/sd_diskio.cpp +++ b/libraries/SD/src/sd_diskio.cpp @@ -124,6 +124,8 @@ bool sdSelectCard(uint8_t pdrv) bool s = sdWait(pdrv, 300); if (!s) { log_e("Select Failed"); + digitalWrite(card->ssPin, HIGH); + return false; } return true; } diff --git a/libraries/SD_MMC/examples/SDMMC_Test/.skip.esp32c3 b/libraries/SD_MMC/examples/SDMMC_Test/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/SD_MMC/examples/SDMMC_time/.skip.esp32c3 b/libraries/SD_MMC/examples/SDMMC_time/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/SD_MMC/src/SD_MMC.cpp b/libraries/SD_MMC/src/SD_MMC.cpp index 0f26583a..16da3c8e 100644 --- a/libraries/SD_MMC/src/SD_MMC.cpp +++ b/libraries/SD_MMC/src/SD_MMC.cpp @@ -13,7 +13,7 @@ // limitations under the License. #include "SD_MMC.h" -#ifndef CONFIG_IDF_TARGET_ESP32S2 //SDMMC does not work on ESP32S2 +#if !defined(CONFIG_IDF_TARGET_ESP32S2) && !defined(CONFIG_IDF_TARGET_ESP32C3) //SDMMC does not work on ESP32S2 #include "vfs_api.h" extern "C" { diff --git a/libraries/SPI/examples/SPI_Multiple_Buses/.skip.esp32c3 b/libraries/SPI/examples/SPI_Multiple_Buses/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/SPI/src/SPI.cpp b/libraries/SPI/src/SPI.cpp index b9225f4f..5e938f02 100644 --- a/libraries/SPI/src/SPI.cpp +++ b/libraries/SPI/src/SPI.cpp @@ -55,6 +55,11 @@ void SPIClass::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss) _miso = (_spi_num == FSPI) ? MISO : -1; _mosi = (_spi_num == FSPI) ? MOSI : -1; _ss = (_spi_num == FSPI) ? SS : -1; +#elif CONFIG_IDF_TARGET_ESP32C3 + _sck = SCK; + _miso = MISO; + _mosi = MOSI; + _ss = SS; #else _sck = (_spi_num == VSPI) ? SCK : 14; _miso = (_spi_num == VSPI) ? MISO : 12; diff --git a/libraries/SimpleBLE/examples/SimpleBleDevice/.skip.esp32c3 b/libraries/SimpleBLE/examples/SimpleBleDevice/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/USB/examples/USBSerial/.skip.esp32c3 b/libraries/USB/examples/USBSerial/.skip.esp32c3 new file mode 100644 index 00000000..e69de29b diff --git a/libraries/WiFi/src/WiFiClient.cpp b/libraries/WiFi/src/WiFiClient.cpp index 5ea339ac..8a2e607d 100644 --- a/libraries/WiFi/src/WiFiClient.cpp +++ b/libraries/WiFi/src/WiFiClient.cpp @@ -321,7 +321,7 @@ int WiFiClient::setOption(int option, int *value) int WiFiClient::getOption(int option, int *value) { - size_t size = sizeof(int); + socklen_t size = sizeof(int); int res = getsockopt(fd(), IPPROTO_TCP, option, (char *)value, &size); if(res < 0) { log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno)); diff --git a/libraries/WiFiProv/src/WiFiProv.cpp b/libraries/WiFiProv/src/WiFiProv.cpp index 789bb5f7..e5a7dc21 100644 --- a/libraries/WiFiProv/src/WiFiProv.cpp +++ b/libraries/WiFiProv/src/WiFiProv.cpp @@ -41,7 +41,7 @@ bool wifiLowLevelInit(bool persistent); -#if CONFIG_IDF_TARGET_ESP32 +#if CONFIG_BLUEDROID_ENABLED static const uint8_t custom_service_uuid[16] = { 0xb4, 0xdf, 0x5a, 0x1c, 0x3f, 0x6b, 0xf4, 0xbf, 0xea, 0x4a, 0x82, 0x03, 0x04, 0x90, 0x1a, 0x02, }; #endif diff --git a/package/package_esp32_index.template.json b/package/package_esp32_index.template.json index 825ad13b..e6e362fb 100644 --- a/package/package_esp32_index.template.json +++ b/package/package_esp32_index.template.json @@ -43,6 +43,11 @@ "name": "xtensa-esp32s2-elf-gcc", "version": "gcc8_4_0-esp-2020r3" }, + { + "packager": "esp32", + "name": "riscv32-esp-elf-gcc", + "version": "gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff" + }, { "packager": "esp32", "name": "esptool_py", @@ -149,51 +154,85 @@ } ] }, + { + "name": "riscv32-esp-elf-gcc", + "version": "gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff", + "systems": [ + { + "host": "i686-mingw32", + "url": "https://dl.espressif.com/dl/toolchains/preview/riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-win32.zip", + "archiveFileName": "riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-win32.zip", + "checksum": "SHA-256:4f576b08620f57c270ac677cc94dce2767fff72d27a539e348d448f63b480d1f", + "size": "190014086" + }, + { + "host": "x86_64-apple-darwin", + "url": "https://dl.espressif.com/dl/toolchains/preview/riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-macos.tar.gz", + "archiveFileName": "riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-macos.tar.gz", + "checksum": "SHA-256:35b1aef85b7e6b4268774f627e8e835d087bcf8b9972cfb6436614aa2e40d4a9", + "size": "158594401" + }, + { + "host": "x86_64-pc-linux-gnu", + "url": "https://dl.espressif.com/dl/toolchains/preview/riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-linux-amd64.tar.gz", + "archiveFileName": "riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-linux-amd64.tar.gz", + "checksum": "SHA-256:425454c5c4e2cde5dd2dd3a1d398befc70addf71547840fb6d0ec4b307b08894", + "size": "152042971" + }, + { + "host": "arm-linux-gnueabihf", + "url": "https://dl.espressif.com/dl/toolchains/preview/riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-linux-armel.tar.gz", + "archiveFileName": "riscv32-esp-elf-gcc8_4_0-crosstool-ng-1.24.0-123-g64eb9ff-linux-armel.tar.gz", + "checksum": "SHA-256:8ae098751b5196ca8a80d832cc9930bc4d639762a6cb22be3cfe0a8d71b2f230", + "size": "150801079" + } + ] + }, { "name": "esptool_py", "version": "3.0.0", "systems": [ { "host": "i686-mingw32", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-windows.zip", - "archiveFileName": "esptool-3.0.0.2-windows.zip", - "checksum": "SHA-256:b192bfc1545a3c92658ce586b4edcc2aca3f0ad4b3fa8417d658bc8a48f1387e", - "size": "3434736" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-windows.zip", + "archiveFileName": "esptool-3.0.0.3-windows.zip", + "checksum": "SHA-256:3c99b3b9bbad1f416988973b536b9f02fae852a145c4c0b7c1e3200d25ef9551", + "size": "3450498" }, { "host": "x86_64-apple-darwin", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-macos.tar.gz", - "archiveFileName": "esptool-3.0.0.2-macos.tar.gz", - "checksum": "SHA-256:2cafab7f1ebce89475b84c115548eaace40b6366d7b3f9862cdb2fc64f806643", - "size": "3859642" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-macos.tar.gz", + "archiveFileName": "esptool-3.0.0.3-macos.tar.gz", + "checksum": "SHA-256:9f956e4c49c0c37ad95752adea7f8b3338e6f33c4726d6dc20239827d3f8a096", + "size": "3866415" }, { "host": "x86_64-pc-linux-gnu", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-linux.tar.gz", - "archiveFileName": "esptool-3.0.0.2-linux.tar.gz", - "checksum": "SHA-256:d5cb51da1c74ff69f81b820470d2ecccb5c7c3a2dec7776483d4c89588b00020", - "size": "57526" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-linux.tar.gz", + "archiveFileName": "esptool-3.0.0.3-linux.tar.gz", + "checksum": "SHA-256:2ec3041d508b1393d4e4bfa833dec8d7f5a74561c939c071748f89293a515f26", + "size": "73901" }, { "host": "i686-pc-linux-gnu", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-linux.tar.gz", - "archiveFileName": "esptool-3.0.0.2-linux.tar.gz", - "checksum": "SHA-256:d5cb51da1c74ff69f81b820470d2ecccb5c7c3a2dec7776483d4c89588b00020", - "size": "57526" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-linux.tar.gz", + "archiveFileName": "esptool-3.0.0.3-linux.tar.gz", + "checksum": "SHA-256:2ec3041d508b1393d4e4bfa833dec8d7f5a74561c939c071748f89293a515f26", + "size": "73901" }, { "host": "arm-linux-gnueabihf", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-linux.tar.gz", - "archiveFileName": "esptool-3.0.0.2-linux.tar.gz", - "checksum": "SHA-256:d5cb51da1c74ff69f81b820470d2ecccb5c7c3a2dec7776483d4c89588b00020", - "size": "57526" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-linux.tar.gz", + "archiveFileName": "esptool-3.0.0.3-linux.tar.gz", + "checksum": "SHA-256:2ec3041d508b1393d4e4bfa833dec8d7f5a74561c939c071748f89293a515f26", + "size": "73901" }, { "host": "aarch64-linux-gnu", - "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.5-rc5/esptool-3.0.0.2-linux.tar.gz", - "archiveFileName": "esptool-3.0.0.2-linux.tar.gz", - "checksum": "SHA-256:d5cb51da1c74ff69f81b820470d2ecccb5c7c3a2dec7776483d4c89588b00020", - "size": "57526" + "url": "https://github.com/espressif/arduino-esp32/releases/download/1.0.6/esptool-3.0.0.3-linux.tar.gz", + "archiveFileName": "esptool-3.0.0.3-linux.tar.gz", + "checksum": "SHA-256:2ec3041d508b1393d4e4bfa833dec8d7f5a74561c939c071748f89293a515f26", + "size": "73901" } ] }, diff --git a/platform.txt b/platform.txt index 5fd435eb..1e529068 100644 --- a/platform.txt +++ b/platform.txt @@ -3,6 +3,7 @@ version=2.0.0 runtime.tools.xtensa-esp32-elf-gcc.path={runtime.platform.path}/tools/xtensa-esp32-elf runtime.tools.xtensa-esp32s2-elf-gcc.path={runtime.platform.path}/tools/xtensa-esp32s2-elf +runtime.tools.riscv32-esp-elf-gcc.path={runtime.platform.path}/tools/riscv32-esp-elf tools.esptool_py.path={runtime.platform.path}/tools/esptool tools.esptool_py.cmd=esptool @@ -15,9 +16,9 @@ tools.esptool_py.network_cmd.windows="{runtime.platform.path}/tools/espota.exe" tools.gen_esp32part.cmd=python "{runtime.platform.path}/tools/gen_esp32part.py" tools.gen_esp32part.cmd.windows="{runtime.platform.path}/tools/gen_esp32part.exe" -compiler.path={runtime.tools.xtensa-{build.mcu}-elf-gcc.path}/bin/ +compiler.path={runtime.tools.{build.tarch}-{build.target}-elf-gcc.path}/bin/ compiler.sdk.path={runtime.platform.path}/tools/sdk/{build.mcu} -compiler.prefix=xtensa-{build.mcu}-elf- +compiler.prefix={build.tarch}-{build.target}-elf- # # ESP32 Support Start @@ -49,6 +50,21 @@ build.extra_flags.esp32s2=-DARDUINO_SERIAL_PORT={build.serial} # ESP32S2 Support End # +# +# ESP32C3 Support Start +# +compiler.cpreprocessor.flags.esp32c3=-DHAVE_CONFIG_H -DMBEDTLS_CONFIG_FILE="mbedtls/esp_config.h" -DUNITY_INCLUDE_CONFIG_H -DWITH_POSIX -D_GNU_SOURCE -DIDF_VER="v4.4-dev-744-g1cb31e509" -DESP_PLATFORM "-I{compiler.sdk.path}/include/config" "-I{compiler.sdk.path}/include/newlib/platform_include" "-I{compiler.sdk.path}/include/freertos/include" "-I{compiler.sdk.path}/include/freertos/port/riscv/include" "-I{compiler.sdk.path}/include/esp_hw_support/include" "-I{compiler.sdk.path}/include/esp_hw_support/port/esp32c3" "-I{compiler.sdk.path}/include/esp_hw_support/port/esp32c3/private_include" "-I{compiler.sdk.path}/include/heap/include" "-I{compiler.sdk.path}/include/log/include" "-I{compiler.sdk.path}/include/lwip/include/apps" "-I{compiler.sdk.path}/include/lwip/include/apps/sntp" "-I{compiler.sdk.path}/include/lwip/lwip/src/include" "-I{compiler.sdk.path}/include/lwip/port/esp32/include" "-I{compiler.sdk.path}/include/lwip/port/esp32/include/arch" "-I{compiler.sdk.path}/include/soc/include" "-I{compiler.sdk.path}/include/soc/esp32c3" "-I{compiler.sdk.path}/include/soc/esp32c3/include" "-I{compiler.sdk.path}/include/hal/esp32c3/include" "-I{compiler.sdk.path}/include/hal/include" "-I{compiler.sdk.path}/include/esp_rom/include" "-I{compiler.sdk.path}/include/esp_rom/esp32c3" "-I{compiler.sdk.path}/include/esp_common/include" "-I{compiler.sdk.path}/include/esp_system/include" "-I{compiler.sdk.path}/include/esp32c3/include" "-I{compiler.sdk.path}/include/driver/include" "-I{compiler.sdk.path}/include/driver/esp32c3/include" "-I{compiler.sdk.path}/include/esp_pm/include" "-I{compiler.sdk.path}/include/esp_ringbuf/include" "-I{compiler.sdk.path}/include/efuse/include" "-I{compiler.sdk.path}/include/efuse/esp32c3/include" "-I{compiler.sdk.path}/include/riscv/include" "-I{compiler.sdk.path}/include/vfs/include" "-I{compiler.sdk.path}/include/esp_wifi/include" "-I{compiler.sdk.path}/include/esp_wifi/esp32c3/include" "-I{compiler.sdk.path}/include/esp_event/include" "-I{compiler.sdk.path}/include/esp_netif/include" "-I{compiler.sdk.path}/include/esp_eth/include" "-I{compiler.sdk.path}/include/tcpip_adapter/include" "-I{compiler.sdk.path}/include/esp_timer/include" "-I{compiler.sdk.path}/include/mbedtls/port/include" "-I{compiler.sdk.path}/include/mbedtls/mbedtls/include" "-I{compiler.sdk.path}/include/mbedtls/esp_crt_bundle/include" "-I{compiler.sdk.path}/include/app_update/include" "-I{compiler.sdk.path}/include/spi_flash/include" "-I{compiler.sdk.path}/include/bootloader_support/include" "-I{compiler.sdk.path}/include/esp_ipc/include" "-I{compiler.sdk.path}/include/nvs_flash/include" "-I{compiler.sdk.path}/include/pthread/include" "-I{compiler.sdk.path}/include/esp_gdbstub/include" "-I{compiler.sdk.path}/include/esp_gdbstub/riscv" "-I{compiler.sdk.path}/include/esp_gdbstub/esp32c3" "-I{compiler.sdk.path}/include/espcoredump/include" "-I{compiler.sdk.path}/include/wpa_supplicant/include" "-I{compiler.sdk.path}/include/wpa_supplicant/port/include" "-I{compiler.sdk.path}/include/wpa_supplicant/include/esp_supplicant" "-I{compiler.sdk.path}/include/app_trace/include" "-I{compiler.sdk.path}/include/asio/asio/asio/include" "-I{compiler.sdk.path}/include/asio/port/include" "-I{compiler.sdk.path}/include/bt/common/osi/include" "-I{compiler.sdk.path}/include/bt/include/esp32c3/include" "-I{compiler.sdk.path}/include/bt/host/bluedroid/api/include/api" "-I{compiler.sdk.path}/include/cbor/port/include" "-I{compiler.sdk.path}/include/unity/include" "-I{compiler.sdk.path}/include/unity/unity/src" "-I{compiler.sdk.path}/include/cmock/CMock/src" "-I{compiler.sdk.path}/include/coap/port/include" "-I{compiler.sdk.path}/include/coap/port/include/coap" "-I{compiler.sdk.path}/include/coap/libcoap/include" "-I{compiler.sdk.path}/include/coap/libcoap/include/coap2" "-I{compiler.sdk.path}/include/console" "-I{compiler.sdk.path}/include/nghttp/port/include" "-I{compiler.sdk.path}/include/nghttp/nghttp2/lib/includes" "-I{compiler.sdk.path}/include/esp-tls" "-I{compiler.sdk.path}/include/esp-tls/esp-tls-crypto" "-I{compiler.sdk.path}/include/esp_adc_cal/include" "-I{compiler.sdk.path}/include/esp_hid/include" "-I{compiler.sdk.path}/include/tcp_transport/include" "-I{compiler.sdk.path}/include/esp_http_client/include" "-I{compiler.sdk.path}/include/esp_http_server/include" "-I{compiler.sdk.path}/include/esp_https_ota/include" "-I{compiler.sdk.path}/include/esp_https_server/include" "-I{compiler.sdk.path}/include/protobuf-c/protobuf-c" "-I{compiler.sdk.path}/include/protocomm/include/common" "-I{compiler.sdk.path}/include/protocomm/include/security" "-I{compiler.sdk.path}/include/protocomm/include/transports" "-I{compiler.sdk.path}/include/mdns/include" "-I{compiler.sdk.path}/include/esp_local_ctrl/include" "-I{compiler.sdk.path}/include/sdmmc/include" "-I{compiler.sdk.path}/include/esp_serial_slave_link/include" "-I{compiler.sdk.path}/include/esp_websocket_client/include" "-I{compiler.sdk.path}/include/expat/expat/expat/lib" "-I{compiler.sdk.path}/include/expat/port/include" "-I{compiler.sdk.path}/include/wear_levelling/include" "-I{compiler.sdk.path}/include/fatfs/diskio" "-I{compiler.sdk.path}/include/fatfs/vfs" "-I{compiler.sdk.path}/include/fatfs/src" "-I{compiler.sdk.path}/include/freemodbus/common/include" "-I{compiler.sdk.path}/include/idf_test/include" "-I{compiler.sdk.path}/include/idf_test/include/esp32c3" "-I{compiler.sdk.path}/include/jsmn/include" "-I{compiler.sdk.path}/include/json/cJSON" "-I{compiler.sdk.path}/include/libsodium/libsodium/src/libsodium/include" "-I{compiler.sdk.path}/include/libsodium/port_include" "-I{compiler.sdk.path}/include/mqtt/esp-mqtt/include" "-I{compiler.sdk.path}/include/openssl/include" "-I{compiler.sdk.path}/include/spiffs/include" "-I{compiler.sdk.path}/include/wifi_provisioning/include" "-I{compiler.sdk.path}/include/esp_littlefs/src" "-I{compiler.sdk.path}/include/esp_littlefs/include" "-I{compiler.sdk.path}/include/fb_gfx/include" +compiler.c.elf.libs.esp32c3=-lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lasio -lbt -lcbor -lunity -lcmock -lcoap -lconsole -lnghttp -lesp-tls -lesp_adc_cal -lesp_hid -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lesp_https_server -lprotobuf-c -lprotocomm -lmdns -lesp_local_ctrl -lsdmmc -lesp_serial_slave_link -lesp_websocket_client -lexpat -lwear_levelling -lfatfs -lfreemodbus -ljsmn -ljson -llibsodium -lmqtt -lopenssl -lspiffs -lwifi_provisioning -lesp_littlefs -lfb_gfx -lasio -lcbor -lcmock -lunity -lcoap -lesp_hid -lesp_local_ctrl -lesp_https_server -lesp_websocket_client -lexpat -lfreemodbus -ljsmn -llibsodium -lmqtt -lwifi_provisioning -lprotocomm -lprotobuf-c -ljson -lfb_gfx -lbt -lbtdm_app -lbtbb -lesp_adc_cal -lmdns -lconsole -lfatfs -lwear_levelling -lopenssl -lspiffs -lesp_littlefs -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lmbedtls -lefuse -lapp_update -lbootloader_support -lesp_ipc -lspi_flash -lnvs_flash -lpthread -lesp_gdbstub -lespcoredump -lesp_system -lesp_rom -lhal -lvfs -lesp_eth -ltcpip_adapter -lesp_netif -lesp_event -lwpa_supplicant -lesp_wifi -llwip -llog -lheap -lsoc -lesp_hw_support -lesp_pm -lesp_ringbuf -ldriver -lriscv -lesp32c3 -lesp_common -lesp_timer -lfreertos -lnewlib -lcxx -lapp_trace -lnghttp -lesp-tls -ltcp_transport -lesp_http_client -lesp_http_server -lesp_https_ota -lsdmmc -lesp_serial_slave_link -lmbedtls -lmbedcrypto -lmbedx509 -lcoexist -lcore -lespnow -lmesh -lnet80211 -lpp -lsmartconfig -lwapi -lphy -lm -lnewlib -lgcc -lstdc++ -lpthread -lapp_trace -lgcov -lapp_trace -lgcov -lc +compiler.c.flags.esp32c3=-march=rv32imc -ffunction-sections -fdata-sections -Wno-error=unused-function -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -ggdb -Wno-error=format= -nostartfiles -Wno-format -Og -fstrict-volatile-bitfields -Wno-error=unused-but-set-variable -std=gnu99 -Wno-old-style-declaration -MMD -c +compiler.cpp.flags.esp32c3=-march=rv32imc -ffunction-sections -fdata-sections -Wno-error=unused-function -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -ggdb -Wno-error=format= -nostartfiles -Wno-format -Og -fstrict-volatile-bitfields -Wno-error=unused-but-set-variable -std=gnu++11 -fno-exceptions -fno-rtti -MMD -c +compiler.S.flags.esp32c3=-ffunction-sections -fdata-sections -Wno-error=unused-function -Wno-error=unused-variable -Wno-error=deprecated-declarations -Wno-unused-parameter -Wno-sign-compare -ggdb -Wno-error=format= -nostartfiles -Wno-format -Og -fstrict-volatile-bitfields -Wno-error=unused-but-set-variable -x assembler-with-cpp -MMD -c +compiler.c.elf.flags.esp32c3=-T esp32c3.rom.ld -T esp32c3.rom.api.ld -T esp32c3.rom.libgcc.ld -T esp32c3.rom.newlib.ld -T esp32c3.rom.version.ld -T esp32c3_out.ld -T esp32c3.project.ld -T esp32c3.peripherals.ld -nostartfiles -march=rv32imc --specs=nosys.specs -Wl,--cref -Wl,--gc-sections -fno-rtti -fno-lto -Wl,--wrap=mbedtls_mpi_exp_mod -u esp_app_desc -u pthread_include_pthread_impl -u pthread_include_pthread_cond_impl -u pthread_include_pthread_local_storage_impl -u start_app -u vfs_include_syscalls_impl -u call_user_start_cpu0 -Wl,--undefined=uxTopUsedPriority -u app_main -u newlib_include_heap_impl -u newlib_include_syscalls_impl -u newlib_include_pthread_impl -u __cxa_guard_dummy -u __cxx_fatal_exception +compiler.ar.flags.esp32c3=cr +build.extra_flags.esp32c3=-DARDUINO_SERIAL_PORT=0 +# +# ESP32C3 Support End +# + # Compile Flags compiler.cpreprocessor.flags={compiler.cpreprocessor.flags.{build.mcu}} compiler.c.flags={compiler.c.flags.{build.mcu}} @@ -88,6 +104,7 @@ compiler.libraries.ldflags= build.flash_size=4MB build.flash_mode=dio build.boot=bootloader +build.bootloader_addr=0x1000 build.code_debug=0 build.defines= build.loop_core= @@ -136,6 +153,6 @@ recipe.size.regex.data=^(?:\.dram0\.data|\.dram0\.bss|\.noinit)\s+([0-9]+).* tools.esptool_py.upload.protocol=esp32 tools.esptool_py.upload.params.verbose= tools.esptool_py.upload.params.quiet= -tools.esptool_py.upload.pattern="{path}/{cmd}" --chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash -z --flash_mode {build.flash_mode} --flash_freq {build.flash_freq} --flash_size detect 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x1000 "{runtime.platform.path}/tools/sdk/{build.mcu}/bin/bootloader_{build.boot}_{build.flash_freq}.bin" 0x10000 "{build.path}/{build.project_name}.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" -tools.esptool_py.upload.pattern.linux=python "{path}/{cmd}" --chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash -z --flash_mode {build.flash_mode} --flash_freq {build.flash_freq} --flash_size detect 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" 0x1000 "{runtime.platform.path}/tools/sdk/{build.mcu}/bin/bootloader_{build.boot}_{build.flash_freq}.bin" 0x10000 "{build.path}/{build.project_name}.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" +tools.esptool_py.upload.pattern="{path}/{cmd}" --chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash -z --flash_mode {build.flash_mode} --flash_freq {build.flash_freq} --flash_size detect 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" {build.bootloader_addr} "{runtime.platform.path}/tools/sdk/{build.mcu}/bin/bootloader_{build.boot}_{build.flash_freq}.bin" 0x10000 "{build.path}/{build.project_name}.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" +tools.esptool_py.upload.pattern.linux=python "{path}/{cmd}" --chip {build.mcu} --port "{serial.port}" --baud {upload.speed} {upload.flags} --before default_reset --after hard_reset write_flash -z --flash_mode {build.flash_mode} --flash_freq {build.flash_freq} --flash_size detect 0xe000 "{runtime.platform.path}/tools/partitions/boot_app0.bin" {build.bootloader_addr} "{runtime.platform.path}/tools/sdk/{build.mcu}/bin/bootloader_{build.boot}_{build.flash_freq}.bin" 0x10000 "{build.path}/{build.project_name}.bin" 0x8000 "{build.path}/{build.project_name}.partitions.bin" tools.esptool_py.upload.network_pattern={network_cmd} -i "{serial.port}" -p "{network.port}" "--auth={network.password}" -f "{build.path}/{build.project_name}.bin" diff --git a/tools/platformio-build-esp32c3.py b/tools/platformio-build-esp32c3.py new file mode 100644 index 00000000..8f3beb34 --- /dev/null +++ b/tools/platformio-build-esp32c3.py @@ -0,0 +1,306 @@ +# Copyright 2014-present PlatformIO +# +# 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. + +""" +Arduino + +Arduino Wiring-based Framework allows writing cross-platform software to +control devices attached to a wide range of Arduino boards to create all +kinds of creative coding, interactive objects, spaces or physical experiences. + +http://arduino.cc/en/Reference/HomePage +""" + +# Extends: https://github.com/platformio/platform-espressif32/blob/develop/builder/main.py + +from os.path import abspath, isdir, isfile, join, basename + +from SCons.Script import DefaultEnvironment + +env = DefaultEnvironment() +platform = env.PioPlatform() + +FRAMEWORK_DIR = platform.get_package_dir("framework-arduinoespressif32") +assert isdir(FRAMEWORK_DIR) + +env.Append( + ASFLAGS=[ + "-x", "assembler-with-cpp" + ], + + CFLAGS=[ + "-march=rv32imc", + "-std=gnu99", + "-Wno-old-style-declaration" + ], + + CXXFLAGS=[ + "-march=rv32imc", + "-std=gnu++11", + "-fno-exceptions", + "-fno-rtti" + ], + + CCFLAGS=[ + "-ffunction-sections", + "-fdata-sections", + "-Wno-error=unused-function", + "-Wno-error=unused-variable", + "-Wno-error=deprecated-declarations", + "-Wno-unused-parameter", + "-Wno-sign-compare", + "-ggdb", + "-Wno-error=format=", + "-nostartfiles", + "-Wno-format", + "-Og", + "-fstrict-volatile-bitfields", + "-Wno-error=unused-but-set-variable", + "-MMD" + ], + + LINKFLAGS=[ + "-mlongcalls", + "-nostartfiles", + "-march=rv32imc", + "--specs=nosys.specs", + "-Wl,--cref", + "-Wl,--gc-sections", + "-fno-rtti", + "-fno-lto", + "-Wl,--wrap=mbedtls_mpi_exp_mod", + "-Wl,--undefined=uxTopUsedPriority", + "-T", "esp32c3.rom.ld", + "-T", "esp32c3.rom.api.ld", + "-T", "esp32c3.rom.libgcc.ld", + "-T", "esp32c3.rom.newlib.ld", + "-T", "esp32c3.rom.version.ld", + "-T", "esp32c3_out.ld", + "-T", "esp32c3.project.ld", + "-T", "esp32c3.peripherals.ld", + "-u", "esp_app_desc", + "-u", "pthread_include_pthread_impl", + "-u", "pthread_include_pthread_cond_impl", + "-u", "pthread_include_pthread_local_storage_impl", + "-u", "start_app", + "-u", "vfs_include_syscalls_impl", + "-u", "call_user_start_cpu0", + "-u", "app_main", + "-u", "newlib_include_heap_impl", + "-u", "newlib_include_syscalls_impl", + "-u", "newlib_include_pthread_impl", + "-u", "__cxa_guard_dummy", + "-u", "__cxx_fatal_exception", + '-Wl,-Map="%s"' % join("$BUILD_DIR", basename(env.subst("${PROJECT_DIR}.map"))) + ], + + CPPPATH=[ + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "config"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "newlib", "platform_include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "freertos", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "freertos", "port", "riscv", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_hw_support", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_hw_support", "port", "esp32c3"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_hw_support", "port", "esp32c3", "private_include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "heap", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "log", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "lwip", "include", "apps"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "lwip", "include", "apps", "sntp"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "lwip", "lwip", "src", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "lwip", "port", "esp32", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "lwip", "port", "esp32", "include", "arch"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "soc", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "soc", "esp32c3"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "soc", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "hal", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "hal", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_rom", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_rom", "esp32c3"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_common", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_system", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "driver", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "driver", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_pm", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_ringbuf", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "efuse", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "efuse", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "riscv", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "vfs", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_wifi", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_wifi", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_event", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_netif", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_eth", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "tcpip_adapter", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_timer", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "mbedtls", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "mbedtls", "mbedtls", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "mbedtls", "esp_crt_bundle", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "app_update", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "spi_flash", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "bootloader_support", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_ipc", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "nvs_flash", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "pthread", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_gdbstub", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_gdbstub", "riscv"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_gdbstub", "esp32c3"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "espcoredump", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "wpa_supplicant", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "wpa_supplicant", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "wpa_supplicant", "include", "esp_supplicant"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "app_trace", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "asio", "asio", "asio", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "asio", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "bt", "common", "osi", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "bt", "include", "esp32c3", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "bt", "host", "bluedroid", "api", "include", "api"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "cbor", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "unity", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "unity", "unity", "src"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "cmock", "CMock", "src"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "coap", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "coap", "port", "include", "coap"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "coap", "libcoap", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "coap", "libcoap", "include", "coap2"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "console"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "nghttp", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "nghttp", "nghttp2", "lib", "includes"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp-tls"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp-tls", "esp-tls-crypto"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_adc_cal", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_hid", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "tcp_transport", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_http_client", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_http_server", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_https_ota", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_https_server", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "protobuf-c", "protobuf-c"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "protocomm", "include", "common"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "protocomm", "include", "security"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "protocomm", "include", "transports"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "mdns", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_local_ctrl", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "sdmmc", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_serial_slave_link", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_websocket_client", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "expat", "expat", "expat", "lib"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "expat", "port", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "wear_levelling", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "fatfs", "diskio"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "fatfs", "vfs"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "fatfs", "src"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "freemodbus", "common", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "idf_test", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "idf_test", "include", "esp32c3"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "jsmn", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "json", "cJSON"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "libsodium", "libsodium", "src", "libsodium", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "libsodium", "port_include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "mqtt", "esp-mqtt", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "openssl", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "spiffs", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "wifi_provisioning", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_littlefs", "src"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "esp_littlefs", "include"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "include", "fb_gfx", "include"), + join(FRAMEWORK_DIR, "cores", env.BoardConfig().get("build.core")) + ], + + LIBPATH=[ + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "lib"), + join(FRAMEWORK_DIR, "tools", "sdk", "esp32c3", "ld") + ], + + LIBS=[ + "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lasio", "-lbt", "-lcbor", "-lunity", "-lcmock", "-lcoap", "-lconsole", "-lnghttp", "-lesp-tls", "-lesp_adc_cal", "-lesp_hid", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lesp_https_server", "-lprotobuf-c", "-lprotocomm", "-lmdns", "-lesp_local_ctrl", "-lsdmmc", "-lesp_serial_slave_link", "-lesp_websocket_client", "-lexpat", "-lwear_levelling", "-lfatfs", "-lfreemodbus", "-ljsmn", "-ljson", "-llibsodium", "-lmqtt", "-lopenssl", "-lspiffs", "-lwifi_provisioning", "-lesp_littlefs", "-lfb_gfx", "-lasio", "-lcbor", "-lcmock", "-lunity", "-lcoap", "-lesp_hid", "-lesp_local_ctrl", "-lesp_https_server", "-lesp_websocket_client", "-lexpat", "-lfreemodbus", "-ljsmn", "-llibsodium", "-lmqtt", "-lwifi_provisioning", "-lprotocomm", "-lprotobuf-c", "-ljson", "-lfb_gfx", "-lbt", "-lbtdm_app", "-lbtbb", "-lesp_adc_cal", "-lmdns", "-lconsole", "-lfatfs", "-lwear_levelling", "-lopenssl", "-lspiffs", "-lesp_littlefs", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lmbedtls", "-lefuse", "-lapp_update", "-lbootloader_support", "-lesp_ipc", "-lspi_flash", "-lnvs_flash", "-lpthread", "-lesp_gdbstub", "-lespcoredump", "-lesp_system", "-lesp_rom", "-lhal", "-lvfs", "-lesp_eth", "-ltcpip_adapter", "-lesp_netif", "-lesp_event", "-lwpa_supplicant", "-lesp_wifi", "-llwip", "-llog", "-lheap", "-lsoc", "-lesp_hw_support", "-lesp_pm", "-lesp_ringbuf", "-ldriver", "-lriscv", "-lesp32c3", "-lesp_common", "-lesp_timer", "-lfreertos", "-lnewlib", "-lcxx", "-lapp_trace", "-lnghttp", "-lesp-tls", "-ltcp_transport", "-lesp_http_client", "-lesp_http_server", "-lesp_https_ota", "-lsdmmc", "-lesp_serial_slave_link", "-lmbedtls", "-lmbedcrypto", "-lmbedx509", "-lcoexist", "-lcore", "-lespnow", "-lmesh", "-lnet80211", "-lpp", "-lsmartconfig", "-lwapi", "-lphy", "-lm", "-lnewlib", "-lgcc", "-lstdc++", "-lpthread", "-lapp_trace", "-lgcov", "-lapp_trace", "-lgcov", "-lc" + ], + + CPPDEFINES=[ + "HAVE_CONFIG_H", + ("MBEDTLS_CONFIG_FILE", '\\"mbedtls/esp_config.h\\"'), + "UNITY_INCLUDE_CONFIG_H", + "WITH_POSIX", + "_GNU_SOURCE", + ("IDF_VER", '\\"v4.4-dev-744-g1cb31e509\\"'), + "ESP_PLATFORM", + "ARDUINO_ARCH_ESP32", + "ESP32", + ("F_CPU", "$BOARD_F_CPU"), + ("ARDUINO", 10812), + ("ARDUINO_VARIANT", '\\"%s\\"' % env.BoardConfig().get("build.variant").replace('"', "")), + ("ARDUINO_BOARD", '\\"%s\\"' % env.BoardConfig().get("name").replace('"', "")) + ], + + LIBSOURCE_DIRS=[ + join(FRAMEWORK_DIR, "libraries") + ], + + FLASH_EXTRA_IMAGES=[ + ("0x1000", join(FRAMEWORK_DIR, "tools", "sdk", "esp32s2", "bin", "bootloader_${BOARD_FLASH_MODE}_${__get_board_f_flash(__env__)}.bin")), + ("0x8000", join(env.subst("$BUILD_DIR"), "partitions.bin")), + ("0xe000", join(FRAMEWORK_DIR, "tools", "partitions", "boot_app0.bin")) + ] +) + +# +# Target: Build Core Library +# + +libs = [] + +variants_dir = join(FRAMEWORK_DIR, "variants") + +if "build.variants_dir" in env.BoardConfig(): + variants_dir = join("$PROJECT_DIR", env.BoardConfig().get("build.variants_dir")) + +if "build.variant" in env.BoardConfig(): + env.Append( + CPPPATH=[ + join(variants_dir, env.BoardConfig().get("build.variant")) + ] + ) + libs.append(env.BuildLibrary( + join("$BUILD_DIR", "FrameworkArduinoVariant"), + join(variants_dir, env.BoardConfig().get("build.variant")) + )) + +envsafe = env.Clone() + +libs.append(envsafe.BuildLibrary( + join("$BUILD_DIR", "FrameworkArduino"), + join(FRAMEWORK_DIR, "cores", env.BoardConfig().get("build.core")) +)) + +env.Prepend(LIBS=libs) + +# +# Generate partition table +# + +fwpartitions_dir = join(FRAMEWORK_DIR, "tools", "partitions") +partitions_csv = env.BoardConfig().get("build.partitions", "default.csv") +env.Replace( + PARTITIONS_TABLE_CSV=abspath( + join(fwpartitions_dir, partitions_csv) if isfile( + join(fwpartitions_dir, partitions_csv)) else partitions_csv)) + +partition_table = env.Command( + join("$BUILD_DIR", "partitions.bin"), + "$PARTITIONS_TABLE_CSV", + env.VerboseAction('"$PYTHONEXE" "%s" -q $SOURCE $TARGET' % join( + FRAMEWORK_DIR, "tools", "gen_esp32part.py"), + "Generating partitions $TARGET")) +env.Depends("$BUILD_DIR/$PROGNAME$PROGSUFFIX", partition_table) diff --git a/tools/sdk/esp32/bin/bootloader_dout_40m.bin b/tools/sdk/esp32/bin/bootloader_dout_40m.bin index 2cb23573..d17f6c90 100644 Binary files a/tools/sdk/esp32/bin/bootloader_dout_40m.bin and b/tools/sdk/esp32/bin/bootloader_dout_40m.bin differ diff --git a/tools/sdk/esp32/bin/bootloader_dout_80m.bin b/tools/sdk/esp32/bin/bootloader_dout_80m.bin index a89aafb8..0269cd8a 100644 Binary files a/tools/sdk/esp32/bin/bootloader_dout_80m.bin and b/tools/sdk/esp32/bin/bootloader_dout_80m.bin differ diff --git a/tools/sdk/esp32/bin/bootloader_qio_40m.bin b/tools/sdk/esp32/bin/bootloader_qio_40m.bin index 2cb23573..74eee42f 100644 Binary files a/tools/sdk/esp32/bin/bootloader_qio_40m.bin and b/tools/sdk/esp32/bin/bootloader_qio_40m.bin differ diff --git a/tools/sdk/esp32/bin/bootloader_qio_80m.bin b/tools/sdk/esp32/bin/bootloader_qio_80m.bin index a89aafb8..d035e67a 100644 Binary files a/tools/sdk/esp32/bin/bootloader_qio_80m.bin and b/tools/sdk/esp32/bin/bootloader_qio_80m.bin differ diff --git a/tools/sdk/esp32/bin/bootloader_qout_40m.bin b/tools/sdk/esp32/bin/bootloader_qout_40m.bin index 2cb23573..a27e14bb 100644 Binary files a/tools/sdk/esp32/bin/bootloader_qout_40m.bin and b/tools/sdk/esp32/bin/bootloader_qout_40m.bin differ diff --git a/tools/sdk/esp32/bin/bootloader_qout_80m.bin b/tools/sdk/esp32/bin/bootloader_qout_80m.bin index a89aafb8..2d690db8 100644 Binary files a/tools/sdk/esp32/bin/bootloader_qout_80m.bin and b/tools/sdk/esp32/bin/bootloader_qout_80m.bin differ diff --git a/tools/sdk/esp32/lib/libapp_trace.a b/tools/sdk/esp32/lib/libapp_trace.a index a01455d7..46061945 100644 Binary files a/tools/sdk/esp32/lib/libapp_trace.a and b/tools/sdk/esp32/lib/libapp_trace.a differ diff --git a/tools/sdk/esp32/lib/libapp_update.a b/tools/sdk/esp32/lib/libapp_update.a index 4dc5e327..3170b568 100644 Binary files a/tools/sdk/esp32/lib/libapp_update.a and b/tools/sdk/esp32/lib/libapp_update.a differ diff --git a/tools/sdk/esp32/lib/libasio.a b/tools/sdk/esp32/lib/libasio.a index f8934d7b..68fc0f79 100644 Binary files a/tools/sdk/esp32/lib/libasio.a and b/tools/sdk/esp32/lib/libasio.a differ diff --git a/tools/sdk/esp32/lib/libbootloader_support.a b/tools/sdk/esp32/lib/libbootloader_support.a index be19da6a..1b73a653 100644 Binary files a/tools/sdk/esp32/lib/libbootloader_support.a and b/tools/sdk/esp32/lib/libbootloader_support.a differ diff --git a/tools/sdk/esp32/lib/libbt.a b/tools/sdk/esp32/lib/libbt.a index 4776ff63..2adc4ed3 100644 Binary files a/tools/sdk/esp32/lib/libbt.a and b/tools/sdk/esp32/lib/libbt.a differ diff --git a/tools/sdk/esp32/lib/libbutton.a b/tools/sdk/esp32/lib/libbutton.a index afab275d..7ecc2b1a 100644 Binary files a/tools/sdk/esp32/lib/libbutton.a and b/tools/sdk/esp32/lib/libbutton.a differ diff --git a/tools/sdk/esp32/lib/libcbor.a b/tools/sdk/esp32/lib/libcbor.a index 95496ed8..47e741d5 100644 Binary files a/tools/sdk/esp32/lib/libcbor.a and b/tools/sdk/esp32/lib/libcbor.a differ diff --git a/tools/sdk/esp32/lib/libcmock.a b/tools/sdk/esp32/lib/libcmock.a index a50dca94..15bb2661 100644 Binary files a/tools/sdk/esp32/lib/libcmock.a and b/tools/sdk/esp32/lib/libcmock.a differ diff --git a/tools/sdk/esp32/lib/libcoap.a b/tools/sdk/esp32/lib/libcoap.a index 7df5a3ee..4fdca8ec 100644 Binary files a/tools/sdk/esp32/lib/libcoap.a and b/tools/sdk/esp32/lib/libcoap.a differ diff --git a/tools/sdk/esp32/lib/libconsole.a b/tools/sdk/esp32/lib/libconsole.a index 0fe5e070..7fec2e83 100644 Binary files a/tools/sdk/esp32/lib/libconsole.a and b/tools/sdk/esp32/lib/libconsole.a differ diff --git a/tools/sdk/esp32/lib/libcxx.a b/tools/sdk/esp32/lib/libcxx.a index c09cd341..6a8e4406 100644 Binary files a/tools/sdk/esp32/lib/libcxx.a and b/tools/sdk/esp32/lib/libcxx.a differ diff --git a/tools/sdk/esp32/lib/libdriver.a b/tools/sdk/esp32/lib/libdriver.a index 7ef279a0..f1c23bcc 100644 Binary files a/tools/sdk/esp32/lib/libdriver.a and b/tools/sdk/esp32/lib/libdriver.a differ diff --git a/tools/sdk/esp32/lib/libefuse.a b/tools/sdk/esp32/lib/libefuse.a index 1d771580..ae9259ea 100644 Binary files a/tools/sdk/esp32/lib/libefuse.a and b/tools/sdk/esp32/lib/libefuse.a differ diff --git a/tools/sdk/esp32/lib/libesp-dsp.a b/tools/sdk/esp32/lib/libesp-dsp.a index e0bd2346..9224a4d9 100644 Binary files a/tools/sdk/esp32/lib/libesp-dsp.a and b/tools/sdk/esp32/lib/libesp-dsp.a differ diff --git a/tools/sdk/esp32/lib/libesp-face.a b/tools/sdk/esp32/lib/libesp-face.a index 0c7749ff..e7d0f46a 100644 Binary files a/tools/sdk/esp32/lib/libesp-face.a and b/tools/sdk/esp32/lib/libesp-face.a differ diff --git a/tools/sdk/esp32/lib/libesp-tls.a b/tools/sdk/esp32/lib/libesp-tls.a index 599423fc..517c2f09 100644 Binary files a/tools/sdk/esp32/lib/libesp-tls.a and b/tools/sdk/esp32/lib/libesp-tls.a differ diff --git a/tools/sdk/esp32/lib/libesp32-camera.a b/tools/sdk/esp32/lib/libesp32-camera.a index 31dbc1fc..b8e4a797 100644 Binary files a/tools/sdk/esp32/lib/libesp32-camera.a and b/tools/sdk/esp32/lib/libesp32-camera.a differ diff --git a/tools/sdk/esp32/lib/libesp32.a b/tools/sdk/esp32/lib/libesp32.a index f4c6da10..9a9ac2b7 100644 Binary files a/tools/sdk/esp32/lib/libesp32.a and b/tools/sdk/esp32/lib/libesp32.a differ diff --git a/tools/sdk/esp32/lib/libesp_adc_cal.a b/tools/sdk/esp32/lib/libesp_adc_cal.a index 8b13bd2f..bcccef9e 100644 Binary files a/tools/sdk/esp32/lib/libesp_adc_cal.a and b/tools/sdk/esp32/lib/libesp_adc_cal.a differ diff --git a/tools/sdk/esp32/lib/libesp_common.a b/tools/sdk/esp32/lib/libesp_common.a index b65e0c9c..3141ceca 100644 Binary files a/tools/sdk/esp32/lib/libesp_common.a and b/tools/sdk/esp32/lib/libesp_common.a differ diff --git a/tools/sdk/esp32/lib/libesp_eth.a b/tools/sdk/esp32/lib/libesp_eth.a index 754b4af2..530d6ecf 100644 Binary files a/tools/sdk/esp32/lib/libesp_eth.a and b/tools/sdk/esp32/lib/libesp_eth.a differ diff --git a/tools/sdk/esp32/lib/libesp_event.a b/tools/sdk/esp32/lib/libesp_event.a index 0d498a8d..90486fdf 100644 Binary files a/tools/sdk/esp32/lib/libesp_event.a and b/tools/sdk/esp32/lib/libesp_event.a differ diff --git a/tools/sdk/esp32/lib/libesp_gdbstub.a b/tools/sdk/esp32/lib/libesp_gdbstub.a index d7b2be0c..1ee86f1e 100644 Binary files a/tools/sdk/esp32/lib/libesp_gdbstub.a and b/tools/sdk/esp32/lib/libesp_gdbstub.a differ diff --git a/tools/sdk/esp32/lib/libesp_hid.a b/tools/sdk/esp32/lib/libesp_hid.a index 29159d2f..722f0eaa 100644 Binary files a/tools/sdk/esp32/lib/libesp_hid.a and b/tools/sdk/esp32/lib/libesp_hid.a differ diff --git a/tools/sdk/esp32/lib/libesp_http_client.a b/tools/sdk/esp32/lib/libesp_http_client.a index 6c8e8286..43842c27 100644 Binary files a/tools/sdk/esp32/lib/libesp_http_client.a and b/tools/sdk/esp32/lib/libesp_http_client.a differ diff --git a/tools/sdk/esp32/lib/libesp_http_server.a b/tools/sdk/esp32/lib/libesp_http_server.a index de453fc2..d3bb40ef 100644 Binary files a/tools/sdk/esp32/lib/libesp_http_server.a and b/tools/sdk/esp32/lib/libesp_http_server.a differ diff --git a/tools/sdk/esp32/lib/libesp_https_ota.a b/tools/sdk/esp32/lib/libesp_https_ota.a index e42dfa79..346f2ab4 100644 Binary files a/tools/sdk/esp32/lib/libesp_https_ota.a and b/tools/sdk/esp32/lib/libesp_https_ota.a differ diff --git a/tools/sdk/esp32/lib/libesp_hw_support.a b/tools/sdk/esp32/lib/libesp_hw_support.a index 1e7d131b..fda5838d 100644 Binary files a/tools/sdk/esp32/lib/libesp_hw_support.a and b/tools/sdk/esp32/lib/libesp_hw_support.a differ diff --git a/tools/sdk/esp32/lib/libesp_ipc.a b/tools/sdk/esp32/lib/libesp_ipc.a index 4d52677a..90849d81 100644 Binary files a/tools/sdk/esp32/lib/libesp_ipc.a and b/tools/sdk/esp32/lib/libesp_ipc.a differ diff --git a/tools/sdk/esp32/lib/libesp_littlefs.a b/tools/sdk/esp32/lib/libesp_littlefs.a index 5ec6eba1..ac97874c 100644 Binary files a/tools/sdk/esp32/lib/libesp_littlefs.a and b/tools/sdk/esp32/lib/libesp_littlefs.a differ diff --git a/tools/sdk/esp32/lib/libesp_local_ctrl.a b/tools/sdk/esp32/lib/libesp_local_ctrl.a index 9634c0ad..6daf6f3f 100644 Binary files a/tools/sdk/esp32/lib/libesp_local_ctrl.a and b/tools/sdk/esp32/lib/libesp_local_ctrl.a differ diff --git a/tools/sdk/esp32/lib/libesp_netif.a b/tools/sdk/esp32/lib/libesp_netif.a index fd2b6f43..d4fa48dd 100644 Binary files a/tools/sdk/esp32/lib/libesp_netif.a and b/tools/sdk/esp32/lib/libesp_netif.a differ diff --git a/tools/sdk/esp32/lib/libesp_pm.a b/tools/sdk/esp32/lib/libesp_pm.a index 2e7c3e4c..101010ff 100644 Binary files a/tools/sdk/esp32/lib/libesp_pm.a and b/tools/sdk/esp32/lib/libesp_pm.a differ diff --git a/tools/sdk/esp32/lib/libesp_rainmaker.a b/tools/sdk/esp32/lib/libesp_rainmaker.a index c47a512d..5ac410d5 100644 Binary files a/tools/sdk/esp32/lib/libesp_rainmaker.a and b/tools/sdk/esp32/lib/libesp_rainmaker.a differ diff --git a/tools/sdk/esp32/lib/libesp_ringbuf.a b/tools/sdk/esp32/lib/libesp_ringbuf.a index a4e12734..2e630fdc 100644 Binary files a/tools/sdk/esp32/lib/libesp_ringbuf.a and b/tools/sdk/esp32/lib/libesp_ringbuf.a differ diff --git a/tools/sdk/esp32/lib/libesp_rom.a b/tools/sdk/esp32/lib/libesp_rom.a index bda730e3..8e9e2d56 100644 Binary files a/tools/sdk/esp32/lib/libesp_rom.a and b/tools/sdk/esp32/lib/libesp_rom.a differ diff --git a/tools/sdk/esp32/lib/libesp_schedule.a b/tools/sdk/esp32/lib/libesp_schedule.a index f897855a..de341d7e 100644 Binary files a/tools/sdk/esp32/lib/libesp_schedule.a and b/tools/sdk/esp32/lib/libesp_schedule.a differ diff --git a/tools/sdk/esp32/lib/libesp_serial_slave_link.a b/tools/sdk/esp32/lib/libesp_serial_slave_link.a index ac8ff75a..a743c938 100644 Binary files a/tools/sdk/esp32/lib/libesp_serial_slave_link.a and b/tools/sdk/esp32/lib/libesp_serial_slave_link.a differ diff --git a/tools/sdk/esp32/lib/libesp_system.a b/tools/sdk/esp32/lib/libesp_system.a index 9fe940b3..742b6c64 100644 Binary files a/tools/sdk/esp32/lib/libesp_system.a and b/tools/sdk/esp32/lib/libesp_system.a differ diff --git a/tools/sdk/esp32/lib/libesp_timer.a b/tools/sdk/esp32/lib/libesp_timer.a index 1ba7594a..09f3158c 100644 Binary files a/tools/sdk/esp32/lib/libesp_timer.a and b/tools/sdk/esp32/lib/libesp_timer.a differ diff --git a/tools/sdk/esp32/lib/libesp_websocket_client.a b/tools/sdk/esp32/lib/libesp_websocket_client.a index 20564c98..a0ad70a7 100644 Binary files a/tools/sdk/esp32/lib/libesp_websocket_client.a and b/tools/sdk/esp32/lib/libesp_websocket_client.a differ diff --git a/tools/sdk/esp32/lib/libesp_wifi.a b/tools/sdk/esp32/lib/libesp_wifi.a index a4411cd8..b502f1b8 100644 Binary files a/tools/sdk/esp32/lib/libesp_wifi.a and b/tools/sdk/esp32/lib/libesp_wifi.a differ diff --git a/tools/sdk/esp32/lib/libespcoredump.a b/tools/sdk/esp32/lib/libespcoredump.a index 16d92dfb..203be705 100644 Binary files a/tools/sdk/esp32/lib/libespcoredump.a and b/tools/sdk/esp32/lib/libespcoredump.a differ diff --git a/tools/sdk/esp32/lib/libexpat.a b/tools/sdk/esp32/lib/libexpat.a index 4f7ea4c8..bace4b91 100644 Binary files a/tools/sdk/esp32/lib/libexpat.a and b/tools/sdk/esp32/lib/libexpat.a differ diff --git a/tools/sdk/esp32/lib/libfatfs.a b/tools/sdk/esp32/lib/libfatfs.a index c17936d6..b864dde2 100644 Binary files a/tools/sdk/esp32/lib/libfatfs.a and b/tools/sdk/esp32/lib/libfatfs.a differ diff --git a/tools/sdk/esp32/lib/libfb_gfx.a b/tools/sdk/esp32/lib/libfb_gfx.a index cdd3626e..e7b4fc8f 100644 Binary files a/tools/sdk/esp32/lib/libfb_gfx.a and b/tools/sdk/esp32/lib/libfb_gfx.a differ diff --git a/tools/sdk/esp32/lib/libfreemodbus.a b/tools/sdk/esp32/lib/libfreemodbus.a index ea0ec085..1928f6d3 100644 Binary files a/tools/sdk/esp32/lib/libfreemodbus.a and b/tools/sdk/esp32/lib/libfreemodbus.a differ diff --git a/tools/sdk/esp32/lib/libfreertos.a b/tools/sdk/esp32/lib/libfreertos.a index b4fb6b15..5f236821 100644 Binary files a/tools/sdk/esp32/lib/libfreertos.a and b/tools/sdk/esp32/lib/libfreertos.a differ diff --git a/tools/sdk/esp32/lib/libhal.a b/tools/sdk/esp32/lib/libhal.a index 210ea1cd..ff89d23d 100644 Binary files a/tools/sdk/esp32/lib/libhal.a and b/tools/sdk/esp32/lib/libhal.a differ diff --git a/tools/sdk/esp32/lib/libheap.a b/tools/sdk/esp32/lib/libheap.a index e9ee0cd8..28e5d074 100644 Binary files a/tools/sdk/esp32/lib/libheap.a and b/tools/sdk/esp32/lib/libheap.a differ diff --git a/tools/sdk/esp32/lib/libjsmn.a b/tools/sdk/esp32/lib/libjsmn.a index afa99531..5d84cdcd 100644 Binary files a/tools/sdk/esp32/lib/libjsmn.a and b/tools/sdk/esp32/lib/libjsmn.a differ diff --git a/tools/sdk/esp32/lib/libjson.a b/tools/sdk/esp32/lib/libjson.a index e40e2ae8..29dcd704 100644 Binary files a/tools/sdk/esp32/lib/libjson.a and b/tools/sdk/esp32/lib/libjson.a differ diff --git a/tools/sdk/esp32/lib/libjson_generator.a b/tools/sdk/esp32/lib/libjson_generator.a index 43cefe39..64ff333d 100644 Binary files a/tools/sdk/esp32/lib/libjson_generator.a and b/tools/sdk/esp32/lib/libjson_generator.a differ diff --git a/tools/sdk/esp32/lib/libjson_parser.a b/tools/sdk/esp32/lib/libjson_parser.a index 90bafcad..5109a218 100644 Binary files a/tools/sdk/esp32/lib/libjson_parser.a and b/tools/sdk/esp32/lib/libjson_parser.a differ diff --git a/tools/sdk/esp32/lib/liblibsodium.a b/tools/sdk/esp32/lib/liblibsodium.a index 7709091b..f1917e6f 100644 Binary files a/tools/sdk/esp32/lib/liblibsodium.a and b/tools/sdk/esp32/lib/liblibsodium.a differ diff --git a/tools/sdk/esp32/lib/liblog.a b/tools/sdk/esp32/lib/liblog.a index 62269b21..7bb12ee9 100644 Binary files a/tools/sdk/esp32/lib/liblog.a and b/tools/sdk/esp32/lib/liblog.a differ diff --git a/tools/sdk/esp32/lib/liblwip.a b/tools/sdk/esp32/lib/liblwip.a index e8e00c51..d7981359 100644 Binary files a/tools/sdk/esp32/lib/liblwip.a and b/tools/sdk/esp32/lib/liblwip.a differ diff --git a/tools/sdk/esp32/lib/libmbedcrypto.a b/tools/sdk/esp32/lib/libmbedcrypto.a index 5ad8e236..485399bd 100644 Binary files a/tools/sdk/esp32/lib/libmbedcrypto.a and b/tools/sdk/esp32/lib/libmbedcrypto.a differ diff --git a/tools/sdk/esp32/lib/libmbedtls.a b/tools/sdk/esp32/lib/libmbedtls.a index 8b510395..4cd5867c 100644 Binary files a/tools/sdk/esp32/lib/libmbedtls.a and b/tools/sdk/esp32/lib/libmbedtls.a differ diff --git a/tools/sdk/esp32/lib/libmbedx509.a b/tools/sdk/esp32/lib/libmbedx509.a index b4eb0b0e..7d25a435 100644 Binary files a/tools/sdk/esp32/lib/libmbedx509.a and b/tools/sdk/esp32/lib/libmbedx509.a differ diff --git a/tools/sdk/esp32/lib/libmdns.a b/tools/sdk/esp32/lib/libmdns.a index bc1f8fd8..4d37adc2 100644 Binary files a/tools/sdk/esp32/lib/libmdns.a and b/tools/sdk/esp32/lib/libmdns.a differ diff --git a/tools/sdk/esp32/lib/libmqtt.a b/tools/sdk/esp32/lib/libmqtt.a index a8cd6775..54780744 100644 Binary files a/tools/sdk/esp32/lib/libmqtt.a and b/tools/sdk/esp32/lib/libmqtt.a differ diff --git a/tools/sdk/esp32/lib/libnewlib.a b/tools/sdk/esp32/lib/libnewlib.a index 0073dbe3..56221595 100644 Binary files a/tools/sdk/esp32/lib/libnewlib.a and b/tools/sdk/esp32/lib/libnewlib.a differ diff --git a/tools/sdk/esp32/lib/libnghttp.a b/tools/sdk/esp32/lib/libnghttp.a index 7e69d7e9..545bb77b 100644 Binary files a/tools/sdk/esp32/lib/libnghttp.a and b/tools/sdk/esp32/lib/libnghttp.a differ diff --git a/tools/sdk/esp32/lib/libnvs_flash.a b/tools/sdk/esp32/lib/libnvs_flash.a index f7f070f9..c501bd99 100644 Binary files a/tools/sdk/esp32/lib/libnvs_flash.a and b/tools/sdk/esp32/lib/libnvs_flash.a differ diff --git a/tools/sdk/esp32/lib/libopenssl.a b/tools/sdk/esp32/lib/libopenssl.a index 04f65fa7..6c1833ec 100644 Binary files a/tools/sdk/esp32/lib/libopenssl.a and b/tools/sdk/esp32/lib/libopenssl.a differ diff --git a/tools/sdk/esp32/lib/libperfmon.a b/tools/sdk/esp32/lib/libperfmon.a index 334de9fe..7487b02a 100644 Binary files a/tools/sdk/esp32/lib/libperfmon.a and b/tools/sdk/esp32/lib/libperfmon.a differ diff --git a/tools/sdk/esp32/lib/libprotobuf-c.a b/tools/sdk/esp32/lib/libprotobuf-c.a index a59c410b..23dcb799 100644 Binary files a/tools/sdk/esp32/lib/libprotobuf-c.a and b/tools/sdk/esp32/lib/libprotobuf-c.a differ diff --git a/tools/sdk/esp32/lib/libprotocomm.a b/tools/sdk/esp32/lib/libprotocomm.a index c85549cc..d1a0fa3b 100644 Binary files a/tools/sdk/esp32/lib/libprotocomm.a and b/tools/sdk/esp32/lib/libprotocomm.a differ diff --git a/tools/sdk/esp32/lib/libpthread.a b/tools/sdk/esp32/lib/libpthread.a index 996e2684..847a09db 100644 Binary files a/tools/sdk/esp32/lib/libpthread.a and b/tools/sdk/esp32/lib/libpthread.a differ diff --git a/tools/sdk/esp32/lib/libqrcode.a b/tools/sdk/esp32/lib/libqrcode.a index 40bc0286..0737aac1 100644 Binary files a/tools/sdk/esp32/lib/libqrcode.a and b/tools/sdk/esp32/lib/libqrcode.a differ diff --git a/tools/sdk/esp32/lib/libsdmmc.a b/tools/sdk/esp32/lib/libsdmmc.a index 9b1dacc8..e31baa46 100644 Binary files a/tools/sdk/esp32/lib/libsdmmc.a and b/tools/sdk/esp32/lib/libsdmmc.a differ diff --git a/tools/sdk/esp32/lib/libsoc.a b/tools/sdk/esp32/lib/libsoc.a index 0f477798..8603e691 100644 Binary files a/tools/sdk/esp32/lib/libsoc.a and b/tools/sdk/esp32/lib/libsoc.a differ diff --git a/tools/sdk/esp32/lib/libspi_flash.a b/tools/sdk/esp32/lib/libspi_flash.a index 7986337c..c5d6f4fe 100644 Binary files a/tools/sdk/esp32/lib/libspi_flash.a and b/tools/sdk/esp32/lib/libspi_flash.a differ diff --git a/tools/sdk/esp32/lib/libspiffs.a b/tools/sdk/esp32/lib/libspiffs.a index cbcd31bc..7cbd700c 100644 Binary files a/tools/sdk/esp32/lib/libspiffs.a and b/tools/sdk/esp32/lib/libspiffs.a differ diff --git a/tools/sdk/esp32/lib/libtcp_transport.a b/tools/sdk/esp32/lib/libtcp_transport.a index 325693fb..57f40bdb 100644 Binary files a/tools/sdk/esp32/lib/libtcp_transport.a and b/tools/sdk/esp32/lib/libtcp_transport.a differ diff --git a/tools/sdk/esp32/lib/libtcpip_adapter.a b/tools/sdk/esp32/lib/libtcpip_adapter.a index 97750a47..19ffbc6e 100644 Binary files a/tools/sdk/esp32/lib/libtcpip_adapter.a and b/tools/sdk/esp32/lib/libtcpip_adapter.a differ diff --git a/tools/sdk/esp32/lib/libulp.a b/tools/sdk/esp32/lib/libulp.a index fad1d47f..05d5018f 100644 Binary files a/tools/sdk/esp32/lib/libulp.a and b/tools/sdk/esp32/lib/libulp.a differ diff --git a/tools/sdk/esp32/lib/libunity.a b/tools/sdk/esp32/lib/libunity.a index 2b8eb0f7..35e35260 100644 Binary files a/tools/sdk/esp32/lib/libunity.a and b/tools/sdk/esp32/lib/libunity.a differ diff --git a/tools/sdk/esp32/lib/libvfs.a b/tools/sdk/esp32/lib/libvfs.a index 97056f04..82b0229a 100644 Binary files a/tools/sdk/esp32/lib/libvfs.a and b/tools/sdk/esp32/lib/libvfs.a differ diff --git a/tools/sdk/esp32/lib/libwear_levelling.a b/tools/sdk/esp32/lib/libwear_levelling.a index a1c4da93..5ac8c272 100644 Binary files a/tools/sdk/esp32/lib/libwear_levelling.a and b/tools/sdk/esp32/lib/libwear_levelling.a differ diff --git a/tools/sdk/esp32/lib/libwifi_provisioning.a b/tools/sdk/esp32/lib/libwifi_provisioning.a index f2a25864..efa00536 100644 Binary files a/tools/sdk/esp32/lib/libwifi_provisioning.a and b/tools/sdk/esp32/lib/libwifi_provisioning.a differ diff --git a/tools/sdk/esp32/lib/libwpa_supplicant.a b/tools/sdk/esp32/lib/libwpa_supplicant.a index 473af31c..9ad335f9 100644 Binary files a/tools/sdk/esp32/lib/libwpa_supplicant.a and b/tools/sdk/esp32/lib/libwpa_supplicant.a differ diff --git a/tools/sdk/esp32/lib/libws2812_led.a b/tools/sdk/esp32/lib/libws2812_led.a index 1d779131..4d8f16cf 100644 Binary files a/tools/sdk/esp32/lib/libws2812_led.a and b/tools/sdk/esp32/lib/libws2812_led.a differ diff --git a/tools/sdk/esp32/lib/libxtensa.a b/tools/sdk/esp32/lib/libxtensa.a index 800496ad..e6881f05 100644 Binary files a/tools/sdk/esp32/lib/libxtensa.a and b/tools/sdk/esp32/lib/libxtensa.a differ diff --git a/tools/sdk/esp32c3/bin/bootloader_dio_40m.bin b/tools/sdk/esp32c3/bin/bootloader_dio_40m.bin new file mode 100644 index 00000000..9cdc475a Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_dio_40m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_dio_80m.bin b/tools/sdk/esp32c3/bin/bootloader_dio_80m.bin new file mode 100644 index 00000000..1e8218dd Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_dio_80m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_dout_40m.bin b/tools/sdk/esp32c3/bin/bootloader_dout_40m.bin new file mode 100644 index 00000000..5bc2c800 Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_dout_40m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_dout_80m.bin b/tools/sdk/esp32c3/bin/bootloader_dout_80m.bin new file mode 100644 index 00000000..8b2b6b8f Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_dout_80m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_qio_40m.bin b/tools/sdk/esp32c3/bin/bootloader_qio_40m.bin new file mode 100644 index 00000000..07d8c76d Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_qio_40m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_qio_80m.bin b/tools/sdk/esp32c3/bin/bootloader_qio_80m.bin new file mode 100644 index 00000000..5cc9a78f Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_qio_80m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_qout_40m.bin b/tools/sdk/esp32c3/bin/bootloader_qout_40m.bin new file mode 100644 index 00000000..65e965a3 Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_qout_40m.bin differ diff --git a/tools/sdk/esp32c3/bin/bootloader_qout_80m.bin b/tools/sdk/esp32c3/bin/bootloader_qout_80m.bin new file mode 100644 index 00000000..5d4e6f33 Binary files /dev/null and b/tools/sdk/esp32c3/bin/bootloader_qout_80m.bin differ diff --git a/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace.h b/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace.h new file mode 100644 index 00000000..b8374ae0 --- /dev/null +++ b/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace.h @@ -0,0 +1,273 @@ +// Copyright 2017 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. +#ifndef ESP_APP_TRACE_H_ +#define ESP_APP_TRACE_H_ + +#include +#include "esp_err.h" +#include "esp_app_trace_util.h" // ESP_APPTRACE_TMO_INFINITE + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Application trace data destinations bits. + */ +typedef enum { + ESP_APPTRACE_DEST_TRAX = 0x1, ///< JTAG destination + ESP_APPTRACE_DEST_UART0 = 0x2, ///< UART destination +} esp_apptrace_dest_t; + +/** + * @brief Initializes application tracing module. + * + * @note Should be called before any esp_apptrace_xxx call. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_init(void); + +/** + * @brief Configures down buffer. + * @note Needs to be called before initiating any data transfer using esp_apptrace_buffer_get and esp_apptrace_write. + * This function does not protect internal data by lock. + * + * @param buf Address of buffer to use for down channel (host to target) data. + * @param size Size of the buffer. + */ +void esp_apptrace_down_buffer_config(uint8_t *buf, uint32_t size); + +/** + * @brief Allocates buffer for trace data. + * After data in buffer are ready to be sent off esp_apptrace_buffer_put must be called to indicate it. + * + * @param dest Indicates HW interface to send data. + * @param size Size of data to write to trace buffer. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return non-NULL on success, otherwise NULL. + */ +uint8_t *esp_apptrace_buffer_get(esp_apptrace_dest_t dest, uint32_t size, uint32_t tmo); + +/** + * @brief Indicates that the data in buffer are ready to be sent off. + * This function is a counterpart of and must be preceeded by esp_apptrace_buffer_get. + * + * @param dest Indicates HW interface to send data. Should be identical to the same parameter in call to esp_apptrace_buffer_get. + * @param ptr Address of trace buffer to release. Should be the value returned by call to esp_apptrace_buffer_get. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo); + +/** + * @brief Writes data to trace buffer. + * + * @param dest Indicates HW interface to send data. + * @param data Address of data to write to trace buffer. + * @param size Size of data to write to trace buffer. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_write(esp_apptrace_dest_t dest, const void *data, uint32_t size, uint32_t tmo); + +/** + * @brief vprintf-like function to sent log messages to host via specified HW interface. + * + * @param dest Indicates HW interface to send data. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * @param fmt Address of format string. + * @param ap List of arguments. + * + * @return Number of bytes written. + */ +int esp_apptrace_vprintf_to(esp_apptrace_dest_t dest, uint32_t tmo, const char *fmt, va_list ap); + +/** + * @brief vprintf-like function to sent log messages to host. + * + * @param fmt Address of format string. + * @param ap List of arguments. + * + * @return Number of bytes written. + */ +int esp_apptrace_vprintf(const char *fmt, va_list ap); + +/** + * @brief Flushes remaining data in trace buffer to host. + * + * @param dest Indicates HW interface to flush data on. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_flush(esp_apptrace_dest_t dest, uint32_t tmo); + +/** + * @brief Flushes remaining data in trace buffer to host without locking internal data. + * This is special version of esp_apptrace_flush which should be called from panic handler. + * + * @param dest Indicates HW interface to flush data on. + * @param min_sz Threshold for flushing data. If current filling level is above this value, data will be flushed. TRAX destinations only. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_flush_nolock(esp_apptrace_dest_t dest, uint32_t min_sz, uint32_t tmo); + +/** + * @brief Reads host data from trace buffer. + * + * @param dest Indicates HW interface to read the data on. + * @param data Address of buffer to put data from trace buffer. + * @param size Pointer to store size of read data. Before call to this function pointed memory must hold requested size of data + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_read(esp_apptrace_dest_t dest, void *data, uint32_t *size, uint32_t tmo); + +/** + * @brief Retrieves incoming data buffer if any. + * After data in buffer are processed esp_apptrace_down_buffer_put must be called to indicate it. + * + * @param dest Indicates HW interface to receive data. + * @param size Address to store size of available data in down buffer. Must be initialized with requested value. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return non-NULL on success, otherwise NULL. + */ +uint8_t *esp_apptrace_down_buffer_get(esp_apptrace_dest_t dest, uint32_t *size, uint32_t tmo); + +/** + * @brief Indicates that the data in down buffer are processed. + * This function is a counterpart of and must be preceeded by esp_apptrace_down_buffer_get. + * + * @param dest Indicates HW interface to receive data. Should be identical to the same parameter in call to esp_apptrace_down_buffer_get. + * @param ptr Address of trace buffer to release. Should be the value returned by call to esp_apptrace_down_buffer_get. + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinitely. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_apptrace_down_buffer_put(esp_apptrace_dest_t dest, uint8_t *ptr, uint32_t tmo); + +/** + * @brief Checks whether host is connected. + * + * @param dest Indicates HW interface to use. + * + * @return true if host is connected, otherwise false + */ +bool esp_apptrace_host_is_connected(esp_apptrace_dest_t dest); + +/** + * @brief Opens file on host. + * This function has the same semantic as 'fopen' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param path Path to file. + * @param mode Mode string. See fopen for details. + * + * @return non zero file handle on success, otherwise 0 + */ +void *esp_apptrace_fopen(esp_apptrace_dest_t dest, const char *path, const char *mode); + +/** + * @brief Closes file on host. + * This function has the same semantic as 'fclose' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param stream File handle returned by esp_apptrace_fopen. + * + * @return Zero on success, otherwise non-zero. See fclose for details. + */ +int esp_apptrace_fclose(esp_apptrace_dest_t dest, void *stream); + +/** + * @brief Writes to file on host. + * This function has the same semantic as 'fwrite' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param ptr Address of data to write. + * @param size Size of an item. + * @param nmemb Number of items to write. + * @param stream File handle returned by esp_apptrace_fopen. + * + * @return Number of written items. See fwrite for details. + */ +size_t esp_apptrace_fwrite(esp_apptrace_dest_t dest, const void *ptr, size_t size, size_t nmemb, void *stream); + +/** + * @brief Read file on host. + * This function has the same semantic as 'fread' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param ptr Address to store read data. + * @param size Size of an item. + * @param nmemb Number of items to read. + * @param stream File handle returned by esp_apptrace_fopen. + * + * @return Number of read items. See fread for details. + */ +size_t esp_apptrace_fread(esp_apptrace_dest_t dest, void *ptr, size_t size, size_t nmemb, void *stream); + +/** + * @brief Set position indicator in file on host. + * This function has the same semantic as 'fseek' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param stream File handle returned by esp_apptrace_fopen. + * @param offset Offset. See fseek for details. + * @param whence Position in file. See fseek for details. + * + * @return Zero on success, otherwise non-zero. See fseek for details. + */ +int esp_apptrace_fseek(esp_apptrace_dest_t dest, void *stream, long offset, int whence); + +/** + * @brief Get current position indicator for file on host. + * This function has the same semantic as 'ftell' except for the first argument. + * + * @param dest Indicates HW interface to use. + * @param stream File handle returned by esp_apptrace_fopen. + * + * @return Current position in file. See ftell for details. + */ +int esp_apptrace_ftell(esp_apptrace_dest_t dest, void *stream); + +/** + * @brief Indicates to the host that all file operations are completed. + * This function should be called after all file operations are finished and + * indicate to the host that it can perform cleanup operations (close open files etc.). + * + * @param dest Indicates HW interface to use. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +int esp_apptrace_fstop(esp_apptrace_dest_t dest); + +/** + * @brief Triggers gcov info dump. + * This function waits for the host to connect to target before dumping data. + */ +void esp_gcov_dump(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace_util.h b/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace_util.h new file mode 100644 index 00000000..57c4f94f --- /dev/null +++ b/tools/sdk/esp32c3/include/app_trace/include/esp_app_trace_util.h @@ -0,0 +1,175 @@ +// Copyright 2017 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. +#ifndef ESP_APP_TRACE_UTIL_H_ +#define ESP_APP_TRACE_UTIL_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "freertos/FreeRTOS.h" +#include "esp_err.h" + +/** Infinite waiting timeout */ +#define ESP_APPTRACE_TMO_INFINITE ((uint32_t)-1) + +/** Structure which holds data necessary for measuring time intervals. + * + * After initialization via esp_apptrace_tmo_init() user needs to call esp_apptrace_tmo_check() + * periodically to check timeout for expiration. + */ +typedef struct { + uint32_t start; ///< time interval start (in CPU ticks) + uint32_t tmo; ///< timeout value (in us) + uint32_t elapsed; ///< elapsed time (in us) +} esp_apptrace_tmo_t; + +/** + * @brief Initializes timeout structure. + * + * @param tmo Pointer to timeout structure to be initialized. + * @param user_tmo Timeout value (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. +*/ +static inline void esp_apptrace_tmo_init(esp_apptrace_tmo_t *tmo, uint32_t user_tmo) +{ + tmo->start = portGET_RUN_TIME_COUNTER_VALUE(); + tmo->tmo = user_tmo; + tmo->elapsed = 0; +} + +/** + * @brief Checks timeout for expiration. + * + * @param tmo Pointer to timeout structure to be initialized. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_tmo_check(esp_apptrace_tmo_t *tmo); + +static inline uint32_t esp_apptrace_tmo_remaining_us(esp_apptrace_tmo_t *tmo) +{ + return tmo->tmo != ESP_APPTRACE_TMO_INFINITE ? (tmo->elapsed - tmo->tmo) : ESP_APPTRACE_TMO_INFINITE; +} + +/** Tracing module synchronization lock */ +typedef struct { + portMUX_TYPE mux; + unsigned int_state; +} esp_apptrace_lock_t; + +/** + * @brief Initializes lock structure. + * + * @param lock Pointer to lock structure to be initialized. + */ +static inline void esp_apptrace_lock_init(esp_apptrace_lock_t *lock) +{ + vPortCPUInitializeMutex(&lock->mux); + lock->int_state = 0; +} + +/** + * @brief Tries to acquire lock in specified time period. + * + * @param lock Pointer to lock structure. + * @param tmo Pointer to timeout struct. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_lock_take(esp_apptrace_lock_t *lock, esp_apptrace_tmo_t *tmo); + +/** + * @brief Releases lock. + * + * @param lock Pointer to lock structure. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_apptrace_lock_give(esp_apptrace_lock_t *lock); + +/** Ring buffer control structure. + * + * @note For purposes of application tracing module if there is no enough space for user data and write pointer can be wrapped + * current ring buffer size can be temporarily shrinked in order to provide buffer with requested size. + */ +typedef struct { + uint8_t *data; ///< pointer to data storage + volatile uint32_t size; ///< size of data storage + volatile uint32_t cur_size; ///< current size of data storage + volatile uint32_t rd; ///< read pointer + volatile uint32_t wr; ///< write pointer +} esp_apptrace_rb_t; + +/** + * @brief Initializes ring buffer control structure. + * + * @param rb Pointer to ring buffer structure to be initialized. + * @param data Pointer to buffer to be used as ring buffer's data storage. + * @param size Size of buffer to be used as ring buffer's data storage. + */ +static inline void esp_apptrace_rb_init(esp_apptrace_rb_t *rb, uint8_t *data, uint32_t size) +{ + rb->data = data; + rb->size = rb->cur_size = size; + rb->rd = 0; + rb->wr = 0; +} + +/** + * @brief Allocates memory chunk in ring buffer. + * + * @param rb Pointer to ring buffer structure. + * @param size Size of the memory to allocate. + * + * @return Pointer to the allocated memory or NULL in case of failure. + */ +uint8_t *esp_apptrace_rb_produce(esp_apptrace_rb_t *rb, uint32_t size); + +/** + * @brief Consumes memory chunk in ring buffer. + * + * @param rb Pointer to ring buffer structure. + * @param size Size of the memory to consume. + * + * @return Pointer to consumed memory chunk or NULL in case of failure. + */ +uint8_t *esp_apptrace_rb_consume(esp_apptrace_rb_t *rb, uint32_t size); + +/** + * @brief Gets size of memory which can consumed with single call to esp_apptrace_rb_consume(). + * + * @param rb Pointer to ring buffer structure. + * + * @return Size of memory which can consumed. + * + * @note Due to read pointer wrapping returned size can be less then the total size of available data. + */ +uint32_t esp_apptrace_rb_read_size_get(esp_apptrace_rb_t *rb); + +/** + * @brief Gets size of memory which can produced with single call to esp_apptrace_rb_produce(). + * + * @param rb Pointer to ring buffer structure. + * + * @return Size of memory which can produced. + * + * @note Due to write pointer wrapping returned size can be less then the total size of available data. + */ +uint32_t esp_apptrace_rb_write_size_get(esp_apptrace_rb_t *rb); + +#ifdef __cplusplus +} +#endif + +#endif //ESP_APP_TRACE_UTIL_H_ diff --git a/tools/sdk/esp32c3/include/app_trace/include/esp_sysview_trace.h b/tools/sdk/esp32c3/include/app_trace/include/esp_sysview_trace.h new file mode 100644 index 00000000..7a1bd5fd --- /dev/null +++ b/tools/sdk/esp32c3/include/app_trace/include/esp_sysview_trace.h @@ -0,0 +1,88 @@ +// Copyright 2018 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. +#ifndef ESP_SYSVIEW_TRACE_H_ +#define ESP_SYSVIEW_TRACE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "esp_err.h" +#include "SEGGER_RTT.h" // SEGGER_RTT_ESP32_Flush +#include "esp_app_trace_util.h" // ESP_APPTRACE_TMO_INFINITE + +/** + * @brief Flushes remaining data in SystemView trace buffer to host. + * + * @param tmo Timeout for operation (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly. + * + * @return ESP_OK. + */ +static inline esp_err_t esp_sysview_flush(uint32_t tmo) +{ + SEGGER_RTT_ESP32_Flush(0, tmo); + return ESP_OK; +} + +/** + * @brief vprintf-like function to sent log messages to the host. + * + * @param format Address of format string. + * @param args List of arguments. + * + * @return Number of bytes written. + */ +int esp_sysview_vprintf(const char * format, va_list args); + +/** + * @brief Starts SystemView heap tracing. + * + * @param tmo Timeout (in us) to wait for the host to be connected. Use -1 to wait forever. + * + * @return ESP_OK on success, ESP_ERR_TIMEOUT if operation has been timed out. + */ +esp_err_t esp_sysview_heap_trace_start(uint32_t tmo); + +/** + * @brief Stops SystemView heap tracing. + * + * @return ESP_OK. + */ +esp_err_t esp_sysview_heap_trace_stop(void); + +/** + * @brief Sends heap allocation event to the host. + * + * @param addr Address of allocated block. + * @param size Size of allocated block. + * @param callers Pointer to array with callstack addresses. + * Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. + */ +void esp_sysview_heap_trace_alloc(void *addr, uint32_t size, const void *callers); + +/** + * @brief Sends heap de-allocation event to the host. + * + * @param addr Address of de-allocated block. + * @param callers Pointer to array with callstack addresses. + * Array size must be CONFIG_HEAP_TRACING_STACK_DEPTH. + */ +void esp_sysview_heap_trace_free(void *addr, const void *callers); + +#ifdef __cplusplus +} +#endif + +#endif //ESP_SYSVIEW_TRACE_H_ diff --git a/tools/sdk/esp32c3/include/app_update/include/esp_ota_ops.h b/tools/sdk/esp32c3/include/app_update/include/esp_ota_ops.h new file mode 100644 index 00000000..4d8053a6 --- /dev/null +++ b/tools/sdk/esp32c3/include/app_update/include/esp_ota_ops.h @@ -0,0 +1,347 @@ +// Copyright 2015-2016 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. + +#ifndef _OTA_OPS_H +#define _OTA_OPS_H + +#include +#include +#include +#include "esp_err.h" +#include "esp_partition.h" +#include "esp_image_format.h" +#include "esp_flash_partitions.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#define OTA_SIZE_UNKNOWN 0xffffffff /*!< Used for esp_ota_begin() if new image size is unknown */ +#define OTA_WITH_SEQUENTIAL_WRITES 0xfffffffe /*!< Used for esp_ota_begin() if new image size is unknown and erase can be done in incremental manner (assuming write operation is in continuous sequence) */ + +#define ESP_ERR_OTA_BASE 0x1500 /*!< Base error code for ota_ops api */ +#define ESP_ERR_OTA_PARTITION_CONFLICT (ESP_ERR_OTA_BASE + 0x01) /*!< Error if request was to write or erase the current running partition */ +#define ESP_ERR_OTA_SELECT_INFO_INVALID (ESP_ERR_OTA_BASE + 0x02) /*!< Error if OTA data partition contains invalid content */ +#define ESP_ERR_OTA_VALIDATE_FAILED (ESP_ERR_OTA_BASE + 0x03) /*!< Error if OTA app image is invalid */ +#define ESP_ERR_OTA_SMALL_SEC_VER (ESP_ERR_OTA_BASE + 0x04) /*!< Error if the firmware has a secure version less than the running firmware. */ +#define ESP_ERR_OTA_ROLLBACK_FAILED (ESP_ERR_OTA_BASE + 0x05) /*!< Error if flash does not have valid firmware in passive partition and hence rollback is not possible */ +#define ESP_ERR_OTA_ROLLBACK_INVALID_STATE (ESP_ERR_OTA_BASE + 0x06) /*!< Error if current active firmware is still marked in pending validation state (ESP_OTA_IMG_PENDING_VERIFY), essentially first boot of firmware image post upgrade and hence firmware upgrade is not possible */ + + +/** + * @brief Opaque handle for an application OTA update + * + * esp_ota_begin() returns a handle which is then used for subsequent + * calls to esp_ota_write() and esp_ota_end(). + */ +typedef uint32_t esp_ota_handle_t; + +/** + * @brief Return esp_app_desc structure. This structure includes app version. + * + * Return description for running app. + * @return Pointer to esp_app_desc structure. + */ +const esp_app_desc_t *esp_ota_get_app_description(void); + +/** + * @brief Fill the provided buffer with SHA256 of the ELF file, formatted as hexadecimal, null-terminated. + * If the buffer size is not sufficient to fit the entire SHA256 in hex plus a null terminator, + * the largest possible number of bytes will be written followed by a null. + * @param dst Destination buffer + * @param size Size of the buffer + * @return Number of bytes written to dst (including null terminator) + */ +int esp_ota_get_app_elf_sha256(char* dst, size_t size); + +/** + * @brief Commence an OTA update writing to the specified partition. + + * The specified partition is erased to the specified image size. + * + * If image size is not yet known, pass OTA_SIZE_UNKNOWN which will + * cause the entire partition to be erased. + * + * On success, this function allocates memory that remains in use + * until esp_ota_end() is called with the returned handle. + * + * Note: If the rollback option is enabled and the running application has the ESP_OTA_IMG_PENDING_VERIFY state then + * it will lead to the ESP_ERR_OTA_ROLLBACK_INVALID_STATE error. Confirm the running app before to run download a new app, + * use esp_ota_mark_app_valid_cancel_rollback() function for it (this should be done as early as possible when you first download a new application). + * + * @param partition Pointer to info for partition which will receive the OTA update. Required. + * @param image_size Size of new OTA app image. Partition will be erased in order to receive this size of image. If 0 or OTA_SIZE_UNKNOWN, the entire partition is erased. + * @param out_handle On success, returns a handle which should be used for subsequent esp_ota_write() and esp_ota_end() calls. + + * @return + * - ESP_OK: OTA operation commenced successfully. + * - ESP_ERR_INVALID_ARG: partition or out_handle arguments were NULL, or partition doesn't point to an OTA app partition. + * - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. + * - ESP_ERR_OTA_PARTITION_CONFLICT: Partition holds the currently running firmware, cannot update in place. + * - ESP_ERR_NOT_FOUND: Partition argument not found in partition table. + * - ESP_ERR_OTA_SELECT_INFO_INVALID: The OTA data partition contains invalid data. + * - ESP_ERR_INVALID_SIZE: Partition doesn't fit in configured flash size. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - ESP_ERR_OTA_ROLLBACK_INVALID_STATE: If the running app has not confirmed state. Before performing an update, the application must be valid. + */ +esp_err_t esp_ota_begin(const esp_partition_t* partition, size_t image_size, esp_ota_handle_t* out_handle); + +/** + * @brief Write OTA update data to partition + * + * This function can be called multiple times as + * data is received during the OTA operation. Data is written + * sequentially to the partition. + * + * @param handle Handle obtained from esp_ota_begin + * @param data Data buffer to write + * @param size Size of data buffer in bytes. + * + * @return + * - ESP_OK: Data was written to flash successfully. + * - ESP_ERR_INVALID_ARG: handle is invalid. + * - ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents + */ +esp_err_t esp_ota_write(esp_ota_handle_t handle, const void* data, size_t size); + +/** + * @brief Write OTA update data to partition + * + * This function can write data in non contiguous manner. + * If flash encryption is enabled, data should be 16 byte aligned. + * + * @param handle Handle obtained from esp_ota_begin + * @param data Data buffer to write + * @param size Size of data buffer in bytes + * @param offset Offset in flash partition + * + * @note While performing OTA, if the packets arrive out of order, esp_ota_write_with_offset() can be used to write data in non contiguous manner. + * Use of esp_ota_write_with_offset() in combination with esp_ota_write() is not recommended. + * + * @return + * - ESP_OK: Data was written to flash successfully. + * - ESP_ERR_INVALID_ARG: handle is invalid. + * - ESP_ERR_OTA_VALIDATE_FAILED: First byte of image contains invalid app image magic byte. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - ESP_ERR_OTA_SELECT_INFO_INVALID: OTA data partition has invalid contents + */ +esp_err_t esp_ota_write_with_offset(esp_ota_handle_t handle, const void *data, size_t size, uint32_t offset); + +/** + * @brief Finish OTA update and validate newly written app image. + * + * @param handle Handle obtained from esp_ota_begin(). + * + * @note After calling esp_ota_end(), the handle is no longer valid and any memory associated with it is freed (regardless of result). + * + * @return + * - ESP_OK: Newly written OTA app image is valid. + * - ESP_ERR_NOT_FOUND: OTA handle was not found. + * - ESP_ERR_INVALID_ARG: Handle was never written to. + * - ESP_ERR_OTA_VALIDATE_FAILED: OTA image is invalid (either not a valid app image, or - if secure boot is enabled - signature failed to verify.) + * - ESP_ERR_INVALID_STATE: If flash encryption is enabled, this result indicates an internal error writing the final encrypted bytes to flash. + */ +esp_err_t esp_ota_end(esp_ota_handle_t handle); + +/** + * @brief Abort OTA update, free the handle and memory associated with it. + * + * @param handle obtained from esp_ota_begin(). + * + * @return + * - ESP_OK: Handle and its associated memory is freed successfully. + * - ESP_ERR_NOT_FOUND: OTA handle was not found. + */ +esp_err_t esp_ota_abort(esp_ota_handle_t handle); + + +/** + * @brief Configure OTA data for a new boot partition + * + * @note If this function returns ESP_OK, calling esp_restart() will boot the newly configured app partition. + * + * @param partition Pointer to info for partition containing app image to boot. + * + * @return + * - ESP_OK: OTA data updated, next reboot will use specified partition. + * - ESP_ERR_INVALID_ARG: partition argument was NULL or didn't point to a valid OTA partition of type "app". + * - ESP_ERR_OTA_VALIDATE_FAILED: Partition contained invalid app image. Also returned if secure boot is enabled and signature validation failed. + * - ESP_ERR_NOT_FOUND: OTA data partition not found. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash erase or write failed. + */ +esp_err_t esp_ota_set_boot_partition(const esp_partition_t* partition); + +/** + * @brief Get partition info of currently configured boot app + * + * If esp_ota_set_boot_partition() has been called, the partition which was set by that function will be returned. + * + * If esp_ota_set_boot_partition() has not been called, the result is usually the same as esp_ota_get_running_partition(). + * The two results are not equal if the configured boot partition does not contain a valid app (meaning that the running partition + * will be an app that the bootloader chose via fallback). + * + * If the OTA data partition is not present or not valid then the result is the first app partition found in the + * partition table. In priority order, this means: the factory app, the first OTA app slot, or the test app partition. + * + * Note that there is no guarantee the returned partition is a valid app. Use esp_image_verify(ESP_IMAGE_VERIFY, ...) to verify if the + * returned partition contains a bootable image. + * + * @return Pointer to info for partition structure, or NULL if partition table is invalid or a flash read operation failed. Any returned pointer is valid for the lifetime of the application. + */ +const esp_partition_t* esp_ota_get_boot_partition(void); + + +/** + * @brief Get partition info of currently running app + * + * This function is different to esp_ota_get_boot_partition() in that + * it ignores any change of selected boot partition caused by + * esp_ota_set_boot_partition(). Only the app whose code is currently + * running will have its partition information returned. + * + * The partition returned by this function may also differ from esp_ota_get_boot_partition() if the configured boot + * partition is somehow invalid, and the bootloader fell back to a different app partition at boot. + * + * @return Pointer to info for partition structure, or NULL if no partition is found or flash read operation failed. Returned pointer is valid for the lifetime of the application. + */ +const esp_partition_t* esp_ota_get_running_partition(void); + + +/** + * @brief Return the next OTA app partition which should be written with a new firmware. + * + * Call this function to find an OTA app partition which can be passed to esp_ota_begin(). + * + * Finds next partition round-robin, starting from the current running partition. + * + * @param start_from If set, treat this partition info as describing the current running partition. Can be NULL, in which case esp_ota_get_running_partition() is used to find the currently running partition. The result of this function is never the same as this argument. + * + * @return Pointer to info for partition which should be updated next. NULL result indicates invalid OTA data partition, or that no eligible OTA app slot partition was found. + * + */ +const esp_partition_t* esp_ota_get_next_update_partition(const esp_partition_t *start_from); + +/** + * @brief Returns esp_app_desc structure for app partition. This structure includes app version. + * + * Returns a description for the requested app partition. + * @param[in] partition Pointer to app partition. (only app partition) + * @param[out] app_desc Structure of info about app. + * @return + * - ESP_OK Successful. + * - ESP_ERR_NOT_FOUND app_desc structure is not found. Magic word is incorrect. + * - ESP_ERR_NOT_SUPPORTED Partition is not application. + * - ESP_ERR_INVALID_ARG Arguments is NULL or if partition's offset exceeds partition size. + * - ESP_ERR_INVALID_SIZE Read would go out of bounds of the partition. + * - or one of error codes from lower-level flash driver. + */ +esp_err_t esp_ota_get_partition_description(const esp_partition_t *partition, esp_app_desc_t *app_desc); + +/** + * @brief This function is called to indicate that the running app is working well. + * + * @return + * - ESP_OK: if successful. + */ +esp_err_t esp_ota_mark_app_valid_cancel_rollback(void); + +/** + * @brief This function is called to roll back to the previously workable app with reboot. + * + * If rollback is successful then device will reset else API will return with error code. + * Checks applications on a flash drive that can be booted in case of rollback. + * If the flash does not have at least one app (except the running app) then rollback is not possible. + * @return + * - ESP_FAIL: if not successful. + * - ESP_ERR_OTA_ROLLBACK_FAILED: The rollback is not possible due to flash does not have any apps. + */ +esp_err_t esp_ota_mark_app_invalid_rollback_and_reboot(void); + +/** + * @brief Returns last partition with invalid state (ESP_OTA_IMG_INVALID or ESP_OTA_IMG_ABORTED). + * + * @return partition. + */ +const esp_partition_t* esp_ota_get_last_invalid_partition(void); + +/** + * @brief Returns state for given partition. + * + * @param[in] partition Pointer to partition. + * @param[out] ota_state state of partition (if this partition has a record in otadata). + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: partition or ota_state arguments were NULL. + * - ESP_ERR_NOT_SUPPORTED: partition is not ota. + * - ESP_ERR_NOT_FOUND: Partition table does not have otadata or state was not found for given partition. + */ +esp_err_t esp_ota_get_state_partition(const esp_partition_t *partition, esp_ota_img_states_t *ota_state); + +/** + * @brief Erase previous boot app partition and corresponding otadata select for this partition. + * + * When current app is marked to as valid then you can erase previous app partition. + * @return + * - ESP_OK: Successful, otherwise ESP_ERR. + */ +esp_err_t esp_ota_erase_last_boot_app_partition(void); + +/** + * @brief Checks applications on the slots which can be booted in case of rollback. + * + * These applications should be valid (marked in otadata as not UNDEFINED, INVALID or ABORTED and crc is good) and be able booted, + * and secure_version of app >= secure_version of efuse (if anti-rollback is enabled). + * + * @return + * - True: Returns true if the slots have at least one app (except the running app). + * - False: The rollback is not possible. + */ +bool esp_ota_check_rollback_is_possible(void); + +#if SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 && (CONFIG_SECURE_BOOT_V2_ENABLED || __DOXYGEN__) + +/** + * Secure Boot V2 public key indexes. + */ +typedef enum { + SECURE_BOOT_PUBLIC_KEY_INDEX_0, /*!< Points to the 0th index of the Secure Boot v2 public key */ + SECURE_BOOT_PUBLIC_KEY_INDEX_1, /*!< Points to the 1st index of the Secure Boot v2 public key */ + SECURE_BOOT_PUBLIC_KEY_INDEX_2 /*!< Points to the 2nd index of the Secure Boot v2 public key */ +} esp_ota_secure_boot_public_key_index_t; + +/** + * @brief Revokes the old signature digest. To be called in the application after the rollback logic. + * + * Relevant for Secure boot v2 on ESP32-S2 where upto 3 key digests can be stored (Key #N-1, Key #N, Key #N+1). + * When key #N-1 used to sign an app is invalidated, an OTA update is to be sent with an app signed with key #N-1 & Key #N. + * After successfully booting the OTA app should call this function to revoke Key #N-1. + * + * @param index - The index of the signature block to be revoked + * + * @return + * - ESP_OK: If revocation is successful. + * - ESP_ERR_INVALID_ARG: If the index of the public key to be revoked is incorrect. + * - ESP_FAIL: If secure boot v2 has not been enabled. + */ +esp_err_t esp_ota_revoke_secure_boot_public_key(esp_ota_secure_boot_public_key_index_t index); +#endif /* SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS > 1 */ + +#ifdef __cplusplus +} +#endif + +#endif /* OTA_OPS_H */ diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio.hpp new file mode 100644 index 00000000..4d0ea107 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio.hpp @@ -0,0 +1,151 @@ +// +// asio.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_HPP +#define ASIO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if defined(ESP_PLATFORM) +# include "esp_asio_config.h" +#endif // defined(ESP_PLATFORM) + +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/async_result.hpp" +#include "asio/awaitable.hpp" +#include "asio/basic_datagram_socket.hpp" +#include "asio/basic_deadline_timer.hpp" +#include "asio/basic_io_object.hpp" +#include "asio/basic_raw_socket.hpp" +#include "asio/basic_seq_packet_socket.hpp" +#include "asio/basic_serial_port.hpp" +#include "asio/basic_signal_set.hpp" +#include "asio/basic_socket.hpp" +#include "asio/basic_socket_acceptor.hpp" +#include "asio/basic_socket_iostream.hpp" +#include "asio/basic_socket_streambuf.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/basic_streambuf.hpp" +#include "asio/basic_waitable_timer.hpp" +#include "asio/bind_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/buffered_read_stream_fwd.hpp" +#include "asio/buffered_read_stream.hpp" +#include "asio/buffered_stream_fwd.hpp" +#include "asio/buffered_stream.hpp" +#include "asio/buffered_write_stream_fwd.hpp" +#include "asio/buffered_write_stream.hpp" +#include "asio/buffers_iterator.hpp" +#include "asio/co_spawn.hpp" +#include "asio/completion_condition.hpp" +#include "asio/compose.hpp" +#include "asio/connect.hpp" +#include "asio/coroutine.hpp" +#include "asio/deadline_timer.hpp" +#include "asio/defer.hpp" +#include "asio/detached.hpp" +#include "asio/dispatch.hpp" +#include "asio/error.hpp" +#include "asio/error_code.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/executor_work_guard.hpp" +#include "asio/generic/basic_endpoint.hpp" +#include "asio/generic/datagram_protocol.hpp" +#include "asio/generic/raw_protocol.hpp" +#include "asio/generic/seq_packet_protocol.hpp" +#include "asio/generic/stream_protocol.hpp" +#include "asio/handler_alloc_hook.hpp" +#include "asio/handler_continuation_hook.hpp" +#include "asio/handler_invoke_hook.hpp" +#include "asio/high_resolution_timer.hpp" +#include "asio/io_context.hpp" +#include "asio/io_context_strand.hpp" +#include "asio/io_service.hpp" +#include "asio/io_service_strand.hpp" +#include "asio/ip/address.hpp" +#include "asio/ip/address_v4.hpp" +#include "asio/ip/address_v4_iterator.hpp" +#include "asio/ip/address_v4_range.hpp" +#include "asio/ip/address_v6.hpp" +#include "asio/ip/address_v6_iterator.hpp" +#include "asio/ip/address_v6_range.hpp" +#include "asio/ip/network_v4.hpp" +#include "asio/ip/network_v6.hpp" +#include "asio/ip/bad_address_cast.hpp" +#include "asio/ip/basic_endpoint.hpp" +#include "asio/ip/basic_resolver.hpp" +#include "asio/ip/basic_resolver_entry.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/host_name.hpp" +#include "asio/ip/icmp.hpp" +#include "asio/ip/multicast.hpp" +#include "asio/ip/resolver_base.hpp" +#include "asio/ip/resolver_query_base.hpp" +#include "asio/ip/tcp.hpp" +#include "asio/ip/udp.hpp" +#include "asio/ip/unicast.hpp" +#include "asio/ip/v6_only.hpp" +#include "asio/is_executor.hpp" +#include "asio/is_read_buffered.hpp" +#include "asio/is_write_buffered.hpp" +#include "asio/local/basic_endpoint.hpp" +#include "asio/local/connect_pair.hpp" +#include "asio/local/datagram_protocol.hpp" +#include "asio/local/stream_protocol.hpp" +#include "asio/packaged_task.hpp" +#include "asio/placeholders.hpp" +#include "asio/posix/basic_descriptor.hpp" +#include "asio/posix/basic_stream_descriptor.hpp" +#include "asio/posix/descriptor.hpp" +#include "asio/posix/descriptor_base.hpp" +#include "asio/posix/stream_descriptor.hpp" +#include "asio/post.hpp" +#include "asio/read.hpp" +#include "asio/read_at.hpp" +#include "asio/read_until.hpp" +#include "asio/redirect_error.hpp" +#include "asio/serial_port.hpp" +#include "asio/serial_port_base.hpp" +#include "asio/signal_set.hpp" +#include "asio/socket_base.hpp" +#include "asio/steady_timer.hpp" +#include "asio/strand.hpp" +#include "asio/streambuf.hpp" +#include "asio/system_context.hpp" +#include "asio/system_error.hpp" +#include "asio/system_executor.hpp" +#include "asio/system_timer.hpp" +#include "asio/this_coro.hpp" +#include "asio/thread.hpp" +#include "asio/thread_pool.hpp" +#include "asio/time_traits.hpp" +#include "asio/use_awaitable.hpp" +#include "asio/use_future.hpp" +#include "asio/uses_executor.hpp" +#include "asio/version.hpp" +#include "asio/wait_traits.hpp" +#include "asio/windows/basic_object_handle.hpp" +#include "asio/windows/basic_overlapped_handle.hpp" +#include "asio/windows/basic_random_access_handle.hpp" +#include "asio/windows/basic_stream_handle.hpp" +#include "asio/windows/object_handle.hpp" +#include "asio/windows/overlapped_handle.hpp" +#include "asio/windows/overlapped_ptr.hpp" +#include "asio/windows/random_access_handle.hpp" +#include "asio/windows/stream_handle.hpp" +#include "asio/write.hpp" +#include "asio/write_at.hpp" + +#endif // ASIO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_allocator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_allocator.hpp new file mode 100644 index 00000000..02d6538e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_allocator.hpp @@ -0,0 +1,131 @@ +// +// associated_allocator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_ASSOCIATED_ALLOCATOR_HPP +#define ASIO_ASSOCIATED_ALLOCATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct associated_allocator_check +{ + typedef void type; +}; + +template +struct associated_allocator_impl +{ + typedef E type; + + static type get(const T&, const E& e) ASIO_NOEXCEPT + { + return e; + } +}; + +template +struct associated_allocator_impl::type> +{ + typedef typename T::allocator_type type; + + static type get(const T& t, const E&) ASIO_NOEXCEPT + { + return t.get_allocator(); + } +}; + +} // namespace detail + +/// Traits type used to obtain the allocator associated with an object. +/** + * A program may specialise this traits type if the @c T template parameter in + * the specialisation is a user-defined type. The template parameter @c + * Allocator shall be a type meeting the Allocator requirements. + * + * Specialisations shall meet the following requirements, where @c t is a const + * reference to an object of type @c T, and @c a is an object of type @c + * Allocator. + * + * @li Provide a nested typedef @c type that identifies a type meeting the + * Allocator requirements. + * + * @li Provide a noexcept static member function named @c get, callable as @c + * get(t) and with return type @c type. + * + * @li Provide a noexcept static member function named @c get, callable as @c + * get(t,a) and with return type @c type. + */ +template > +struct associated_allocator +{ + /// If @c T has a nested type @c allocator_type, T::allocator_type. + /// Otherwise @c Allocator. +#if defined(GENERATING_DOCUMENTATION) + typedef see_below type; +#else // defined(GENERATING_DOCUMENTATION) + typedef typename detail::associated_allocator_impl::type type; +#endif // defined(GENERATING_DOCUMENTATION) + + /// If @c T has a nested type @c allocator_type, returns + /// t.get_allocator(). Otherwise returns @c a. + static type get(const T& t, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return detail::associated_allocator_impl::get(t, a); + } +}; + +/// Helper function to obtain an object's associated allocator. +/** + * @returns associated_allocator::get(t) + */ +template +inline typename associated_allocator::type +get_associated_allocator(const T& t) ASIO_NOEXCEPT +{ + return associated_allocator::get(t); +} + +/// Helper function to obtain an object's associated allocator. +/** + * @returns associated_allocator::get(t, a) + */ +template +inline typename associated_allocator::type +get_associated_allocator(const T& t, const Allocator& a) ASIO_NOEXCEPT +{ + return associated_allocator::get(t, a); +} + +#if defined(ASIO_HAS_ALIAS_TEMPLATES) + +template > +using associated_allocator_t + = typename associated_allocator::type; + +#endif // defined(ASIO_HAS_ALIAS_TEMPLATES) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_ASSOCIATED_ALLOCATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_executor.hpp new file mode 100644 index 00000000..7fe6af5b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/associated_executor.hpp @@ -0,0 +1,149 @@ +// +// associated_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_ASSOCIATED_EXECUTOR_HPP +#define ASIO_ASSOCIATED_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/is_executor.hpp" +#include "asio/system_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct associated_executor_check +{ + typedef void type; +}; + +template +struct associated_executor_impl +{ + typedef E type; + + static type get(const T&, const E& e) ASIO_NOEXCEPT + { + return e; + } +}; + +template +struct associated_executor_impl::type> +{ + typedef typename T::executor_type type; + + static type get(const T& t, const E&) ASIO_NOEXCEPT + { + return t.get_executor(); + } +}; + +} // namespace detail + +/// Traits type used to obtain the executor associated with an object. +/** + * A program may specialise this traits type if the @c T template parameter in + * the specialisation is a user-defined type. The template parameter @c + * Executor shall be a type meeting the Executor requirements. + * + * Specialisations shall meet the following requirements, where @c t is a const + * reference to an object of type @c T, and @c e is an object of type @c + * Executor. + * + * @li Provide a nested typedef @c type that identifies a type meeting the + * Executor requirements. + * + * @li Provide a noexcept static member function named @c get, callable as @c + * get(t) and with return type @c type. + * + * @li Provide a noexcept static member function named @c get, callable as @c + * get(t,e) and with return type @c type. + */ +template +struct associated_executor +{ + /// If @c T has a nested type @c executor_type, T::executor_type. + /// Otherwise @c Executor. +#if defined(GENERATING_DOCUMENTATION) + typedef see_below type; +#else // defined(GENERATING_DOCUMENTATION) + typedef typename detail::associated_executor_impl::type type; +#endif // defined(GENERATING_DOCUMENTATION) + + /// If @c T has a nested type @c executor_type, returns + /// t.get_executor(). Otherwise returns @c ex. + static type get(const T& t, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return detail::associated_executor_impl::get(t, ex); + } +}; + +/// Helper function to obtain an object's associated executor. +/** + * @returns associated_executor::get(t) + */ +template +inline typename associated_executor::type +get_associated_executor(const T& t) ASIO_NOEXCEPT +{ + return associated_executor::get(t); +} + +/// Helper function to obtain an object's associated executor. +/** + * @returns associated_executor::get(t, ex) + */ +template +inline typename associated_executor::type +get_associated_executor(const T& t, const Executor& ex, + typename enable_if::value>::type* = 0) ASIO_NOEXCEPT +{ + return associated_executor::get(t, ex); +} + +/// Helper function to obtain an object's associated executor. +/** + * @returns associated_executor::get(t, ctx.get_executor()) + */ +template +inline typename associated_executor::type +get_associated_executor(const T& t, ExecutionContext& ctx, + typename enable_if::value>::type* = 0) ASIO_NOEXCEPT +{ + return associated_executor::get(t, ctx.get_executor()); +} + +#if defined(ASIO_HAS_ALIAS_TEMPLATES) + +template +using associated_executor_t = typename associated_executor::type; + +#endif // defined(ASIO_HAS_ALIAS_TEMPLATES) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_ASSOCIATED_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/async_result.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/async_result.hpp new file mode 100644 index 00000000..a75f9e4a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/async_result.hpp @@ -0,0 +1,585 @@ +// +// async_result.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_ASYNC_RESULT_HPP +#define ASIO_ASYNC_RESULT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/variadic_templates.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_CONCEPTS) \ + && defined(ASIO_HAS_VARIADIC_TEMPLATES) \ + && defined(ASIO_HAS_DECLTYPE) + +namespace detail { + +template +struct is_completion_signature : false_type +{ +}; + +template +struct is_completion_signature : true_type +{ +}; + +template +ASIO_CONCEPT callable_with = requires(T t, Args&&... args) +{ + t(static_cast(args)...); +}; + +template +struct is_completion_handler_for : false_type +{ +}; + +template +struct is_completion_handler_for + : integral_constant)> +{ +}; + +} // namespace detail + +template +ASIO_CONCEPT completion_signature = + detail::is_completion_signature::value; + +#define ASIO_COMPLETION_SIGNATURE \ + ::asio::completion_signature + +template +ASIO_CONCEPT completion_handler_for = + detail::is_completion_handler_for::value; + +#define ASIO_COMPLETION_HANDLER_FOR(s) \ + ::asio::completion_handler_for + +#else // defined(ASIO_HAS_CONCEPTS) + // && defined(ASIO_HAS_VARIADIC_TEMPLATES) + // && defined(ASIO_HAS_DECLTYPE) + +#define ASIO_COMPLETION_SIGNATURE typename +#define ASIO_COMPLETION_HANDLER_FOR(s) typename + +#endif // defined(ASIO_HAS_CONCEPTS) + // && defined(ASIO_HAS_VARIADIC_TEMPLATES) + // && defined(ASIO_HAS_DECLTYPE) + +/// An interface for customising the behaviour of an initiating function. +/** + * The async_result traits class is used for determining: + * + * @li the concrete completion handler type to be called at the end of the + * asynchronous operation; + * + * @li the initiating function return type; and + * + * @li how the return value of the initiating function is obtained. + * + * The trait allows the handler and return types to be determined at the point + * where the specific completion handler signature is known. + * + * This template may be specialised for user-defined completion token types. + * The primary template assumes that the CompletionToken is the completion + * handler. + */ +template +class async_result +{ +public: + /// The concrete completion handler type for the specific signature. + typedef CompletionToken completion_handler_type; + + /// The return type of the initiating function. + typedef void return_type; + + /// Construct an async result from a given handler. + /** + * When using a specalised async_result, the constructor has an opportunity + * to initialise some state associated with the completion handler, which is + * then returned from the initiating function. + */ + explicit async_result(completion_handler_type& h) + { + (void)h; + } + + /// Obtain the value to be returned from the initiating function. + return_type get() + { + } + +#if defined(GENERATING_DOCUMENTATION) + + /// Initiate the asynchronous operation that will produce the result, and + /// obtain the value to be returned from the initiating function. + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken) token, + ASIO_MOVE_ARG(Args)... args); + +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken) token, + ASIO_MOVE_ARG(Args)... args) + { + ASIO_MOVE_CAST(Initiation)(initiation)( + ASIO_MOVE_CAST(RawCompletionToken)(token), + ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken) token) + { + ASIO_MOVE_CAST(Initiation)(initiation)( + ASIO_MOVE_CAST(RawCompletionToken)(token)); + } + +#define ASIO_PRIVATE_INITIATE_DEF(n) \ + template \ + static return_type initiate( \ + ASIO_MOVE_ARG(Initiation) initiation, \ + ASIO_MOVE_ARG(RawCompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + ASIO_MOVE_CAST(Initiation)(initiation)( \ + ASIO_MOVE_CAST(RawCompletionToken)(token), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INITIATE_DEF) +#undef ASIO_PRIVATE_INITIATE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +private: + async_result(const async_result&) ASIO_DELETED; + async_result& operator=(const async_result&) ASIO_DELETED; +}; + +#if !defined(GENERATING_DOCUMENTATION) + +template +class async_result +{ + // Empty. +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +/// Helper template to deduce the handler type from a CompletionToken, capture +/// a local copy of the handler, and then create an async_result for the +/// handler. +template +struct async_completion +{ + /// The real handler type to be used for the asynchronous operation. + typedef typename asio::async_result< + typename decay::type, + Signature>::completion_handler_type completion_handler_type; + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Constructor. + /** + * The constructor creates the concrete completion handler and makes the link + * between the handler and the asynchronous result. + */ + explicit async_completion(CompletionToken& token) + : completion_handler(static_cast::value, + completion_handler_type&, CompletionToken&&>::type>(token)), + result(completion_handler) + { + } +#else // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + explicit async_completion(typename decay::type& token) + : completion_handler(token), + result(completion_handler) + { + } + + explicit async_completion(const typename decay::type& token) + : completion_handler(token), + result(completion_handler) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// A copy of, or reference to, a real handler object. +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + typename conditional< + is_same::value, + completion_handler_type&, completion_handler_type>::type completion_handler; +#else // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + completion_handler_type completion_handler; +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// The result of the asynchronous operation's initiating function. + async_result::type, Signature> result; +}; + +namespace detail { + +template +struct async_result_helper + : async_result::type, Signature> +{ +}; + +struct async_result_memfns_base +{ + void initiate(); +}; + +template +struct async_result_memfns_derived + : T, async_result_memfns_base +{ +}; + +template +struct async_result_memfns_check +{ +}; + +template +char (&async_result_initiate_memfn_helper(...))[2]; + +template +char async_result_initiate_memfn_helper( + async_result_memfns_check< + void (async_result_memfns_base::*)(), + &async_result_memfns_derived::initiate>*); + +template +struct async_result_has_initiate_memfn + : integral_constant::type, Signature> + >(0)) != 1> +{ +}; + +} // namespace detail + +#if defined(GENERATING_DOCUMENTATION) +# define ASIO_INITFN_RESULT_TYPE(ct, sig) \ + void_or_deduced +#elif defined(_MSC_VER) && (_MSC_VER < 1500) +# define ASIO_INITFN_RESULT_TYPE(ct, sig) \ + typename ::asio::detail::async_result_helper< \ + ct, sig>::return_type +#define ASIO_HANDLER_TYPE(ct, sig) \ + typename ::asio::detail::async_result_helper< \ + ct, sig>::completion_handler_type +#else +# define ASIO_INITFN_RESULT_TYPE(ct, sig) \ + typename ::asio::async_result< \ + typename ::asio::decay::type, sig>::return_type +#define ASIO_HANDLER_TYPE(ct, sig) \ + typename ::asio::async_result< \ + typename ::asio::decay::type, sig>::completion_handler_type +#endif + +#if defined(GENERATION_DOCUMENTATION) +# define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ + auto +#elif defined(ASIO_HAS_RETURN_TYPE_DEDUCTION) +# define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ + auto +#else +# define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ + ASIO_INITFN_RESULT_TYPE(ct, sig) +#endif + +#if defined(GENERATION_DOCUMENTATION) +# define ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ + void_or_deduced +#elif defined(ASIO_HAS_DECLTYPE) +# define ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ + decltype expr +#else +# define ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ + ASIO_INITFN_RESULT_TYPE(ct, sig) +#endif + +#if defined(GENERATING_DOCUMENTATION) + +template +void_or_deduced async_initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken), + ASIO_MOVE_ARG(Args)... args); + +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +inline typename enable_if< + detail::async_result_has_initiate_memfn::value, + ASIO_INITFN_DEDUCED_RESULT_TYPE(CompletionToken, Signature, + (async_result::type, + Signature>::initiate(declval(), + declval(), + declval()...)))>::type +async_initiate(ASIO_MOVE_ARG(Initiation) initiation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, + ASIO_MOVE_ARG(Args)... args) +{ + return async_result::type, + Signature>::initiate(ASIO_MOVE_CAST(Initiation)(initiation), + ASIO_MOVE_CAST(CompletionToken)(token), + ASIO_MOVE_CAST(Args)(args)...); +} + +template +inline typename enable_if< + !detail::async_result_has_initiate_memfn::value, + ASIO_INITFN_RESULT_TYPE(CompletionToken, Signature)>::type +async_initiate(ASIO_MOVE_ARG(Initiation) initiation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, + ASIO_MOVE_ARG(Args)... args) +{ + async_completion completion(token); + + ASIO_MOVE_CAST(Initiation)(initiation)( + ASIO_MOVE_CAST(ASIO_HANDLER_TYPE(CompletionToken, + Signature))(completion.completion_handler), + ASIO_MOVE_CAST(Args)(args)...); + + return completion.result.get(); +} + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +inline typename enable_if< + detail::async_result_has_initiate_memfn::value, + ASIO_INITFN_DEDUCED_RESULT_TYPE(CompletionToken, Signature, + (async_result::type, + Signature>::initiate(declval(), + declval())))>::type +async_initiate(ASIO_MOVE_ARG(Initiation) initiation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token) +{ + return async_result::type, + Signature>::initiate(ASIO_MOVE_CAST(Initiation)(initiation), + ASIO_MOVE_CAST(CompletionToken)(token)); +} + +template +inline typename enable_if< + !detail::async_result_has_initiate_memfn::value, + ASIO_INITFN_RESULT_TYPE(CompletionToken, Signature)>::type +async_initiate(ASIO_MOVE_ARG(Initiation) initiation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token) +{ + async_completion completion(token); + + ASIO_MOVE_CAST(Initiation)(initiation)( + ASIO_MOVE_CAST(ASIO_HANDLER_TYPE(CompletionToken, + Signature))(completion.completion_handler)); + + return completion.result.get(); +} + +#define ASIO_PRIVATE_INITIATE_DEF(n) \ + template \ + inline typename enable_if< \ + detail::async_result_has_initiate_memfn< \ + CompletionToken, Signature>::value, \ + ASIO_INITFN_DEDUCED_RESULT_TYPE(CompletionToken, Signature, \ + (async_result::type, \ + Signature>::initiate(declval(), \ + declval(), \ + ASIO_VARIADIC_MOVE_DECLVAL(n))))>::type \ + async_initiate(ASIO_MOVE_ARG(Initiation) initiation, \ + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + return async_result::type, \ + Signature>::initiate(ASIO_MOVE_CAST(Initiation)(initiation), \ + ASIO_MOVE_CAST(CompletionToken)(token), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + \ + template \ + inline typename enable_if< \ + !detail::async_result_has_initiate_memfn< \ + CompletionToken, Signature>::value, \ + ASIO_INITFN_RESULT_TYPE(CompletionToken, Signature)>::type \ + async_initiate(ASIO_MOVE_ARG(Initiation) initiation, \ + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + async_completion completion(token); \ + \ + ASIO_MOVE_CAST(Initiation)(initiation)( \ + ASIO_MOVE_CAST(ASIO_HANDLER_TYPE(CompletionToken, \ + Signature))(completion.completion_handler), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + \ + return completion.result.get(); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INITIATE_DEF) +#undef ASIO_PRIVATE_INITIATE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#if defined(ASIO_HAS_CONCEPTS) \ + && defined(ASIO_HAS_VARIADIC_TEMPLATES) \ + && defined(ASIO_HAS_DECLTYPE) + +namespace detail { + +template +struct initiation_archetype +{ + template CompletionHandler> + void operator()(CompletionHandler&&) const + { + } +}; + +} // namespace detail + +template +ASIO_CONCEPT completion_token_for = requires(T&& t) +{ + async_initiate(detail::initiation_archetype{}, t); +}; + +#define ASIO_COMPLETION_TOKEN_FOR(s) \ + ::asio::completion_token_for + +#else // defined(ASIO_HAS_CONCEPTS) + // && defined(ASIO_HAS_VARIADIC_TEMPLATES) + // && defined(ASIO_HAS_DECLTYPE) + +#define ASIO_COMPLETION_TOKEN_FOR(s) typename + +#endif // defined(ASIO_HAS_CONCEPTS) + // && defined(ASIO_HAS_VARIADIC_TEMPLATES) + // && defined(ASIO_HAS_DECLTYPE) + +namespace detail { + +template +struct default_completion_token_check +{ + typedef void type; +}; + +template +struct default_completion_token_impl +{ + typedef void type; +}; + +template +struct default_completion_token_impl::type> +{ + typedef typename T::default_completion_token_type type; +}; + +} // namespace detail + +#if defined(GENERATING_DOCUMENTATION) + +/// Traits type used to determine the default completion token type associated +/// with a type (such as an executor). +/** + * A program may specialise this traits type if the @c T template parameter in + * the specialisation is a user-defined type. + * + * Specialisations of this trait may provide a nested typedef @c type, which is + * a default-constructible completion token type. + */ +template +struct default_completion_token +{ + /// If @c T has a nested type @c default_completion_token_type, + /// T::default_completion_token_type. Otherwise the typedef @c type + /// is not defined. + typedef see_below type; +}; +#else +template +struct default_completion_token + : detail::default_completion_token_impl +{ +}; +#endif + +#if defined(ASIO_HAS_ALIAS_TEMPLATES) + +template +using default_completion_token_t = typename default_completion_token::type; + +#endif // defined(ASIO_HAS_ALIAS_TEMPLATES) + +#if defined(ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) + +#define ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(e) \ + = typename ::asio::default_completion_token::type +#define ASIO_DEFAULT_COMPLETION_TOKEN(e) \ + = typename ::asio::default_completion_token::type() + +#else // defined(ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) + +#define ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(e) +#define ASIO_DEFAULT_COMPLETION_TOKEN(e) + +#endif // defined(ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_ASYNC_RESULT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/awaitable.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/awaitable.hpp new file mode 100644 index 00000000..890fb67e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/awaitable.hpp @@ -0,0 +1,123 @@ +// +// awaitable.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_AWAITABLE_HPP +#define ASIO_AWAITABLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +using std::experimental::coroutine_handle; +using std::experimental::suspend_always; + +template class awaitable_thread; +template class awaitable_frame; + +} // namespace detail + +/// The return type of a coroutine or asynchronous operation. +template +class awaitable +{ +public: + /// The type of the awaited value. + typedef T value_type; + + /// The executor type that will be used for the coroutine. + typedef Executor executor_type; + + /// Default constructor. + constexpr awaitable() noexcept + : frame_(nullptr) + { + } + + /// Move constructor. + awaitable(awaitable&& other) noexcept + : frame_(std::exchange(other.frame_, nullptr)) + { + } + + /// Destructor + ~awaitable() + { + if (frame_) + frame_->destroy(); + } + + /// Checks if the awaitable refers to a future result. + bool valid() const noexcept + { + return !!frame_; + } + +#if !defined(GENERATING_DOCUMENTATION) + + // Support for co_await keyword. + bool await_ready() const noexcept + { + return false; + } + + // Support for co_await keyword. + template + void await_suspend( + detail::coroutine_handle> h) + { + frame_->push_frame(&h.promise()); + } + + // Support for co_await keyword. + T await_resume() + { + return frame_->get(); + } + +#endif // !defined(GENERATING_DOCUMENTATION) + +private: + template friend class detail::awaitable_thread; + template friend class detail::awaitable_frame; + + // Not copy constructible or copy assignable. + awaitable(const awaitable&) = delete; + awaitable& operator=(const awaitable&) = delete; + + // Construct the awaitable from a coroutine's frame object. + explicit awaitable(detail::awaitable_frame* a) + : frame_(a) + { + } + + detail::awaitable_frame* frame_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/awaitable.hpp" + +#endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_AWAITABLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_datagram_socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_datagram_socket.hpp new file mode 100644 index 00000000..2d5cba39 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_datagram_socket.hpp @@ -0,0 +1,1210 @@ +// +// basic_datagram_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_DATAGRAM_SOCKET_HPP +#define ASIO_BASIC_DATAGRAM_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) +#define ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_datagram_socket; + +#endif // !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) + +/// Provides datagram-oriented socket functionality. +/** + * The basic_datagram_socket class template provides asynchronous and blocking + * datagram-oriented socket functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_datagram_socket + : public basic_socket +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the socket type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_datagram_socket other; + }; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// Construct a basic_datagram_socket without opening it. + /** + * This constructor creates a datagram socket without opening it. The open() + * function must be called before data can be sent or received on the socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_datagram_socket(const executor_type& ex) + : basic_socket(ex) + { + } + + /// Construct a basic_datagram_socket without opening it. + /** + * This constructor creates a datagram socket without opening it. The open() + * function must be called before data can be sent or received on the socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + */ + template + explicit basic_datagram_socket(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context) + { + } + + /// Construct and open a basic_datagram_socket. + /** + * This constructor creates and opens a datagram socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_datagram_socket(const executor_type& ex, const protocol_type& protocol) + : basic_socket(ex, protocol) + { + } + + /// Construct and open a basic_datagram_socket. + /** + * This constructor creates and opens a datagram socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_datagram_socket(ExecutionContext& context, + const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol) + { + } + + /// Construct a basic_datagram_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a datagram socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the datagram + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + basic_datagram_socket(const executor_type& ex, const endpoint_type& endpoint) + : basic_socket(ex, endpoint) + { + } + + /// Construct a basic_datagram_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a datagram socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the datagram + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_datagram_socket(ExecutionContext& context, + const endpoint_type& endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, endpoint) + { + } + + /// Construct a basic_datagram_socket on an existing native socket. + /** + * This constructor creates a datagram socket object to hold an existing + * native socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_datagram_socket(const executor_type& ex, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket(ex, protocol, native_socket) + { + } + + /// Construct a basic_datagram_socket on an existing native socket. + /** + * This constructor creates a datagram socket object to hold an existing + * native socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_datagram_socket(ExecutionContext& context, + const protocol_type& protocol, const native_handle_type& native_socket, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol, native_socket) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_datagram_socket from another. + /** + * This constructor moves a datagram socket from one object to another. + * + * @param other The other basic_datagram_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_datagram_socket(const executor_type&) + * constructor. + */ + basic_datagram_socket(basic_datagram_socket&& other) ASIO_NOEXCEPT + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_datagram_socket from another. + /** + * This assignment operator moves a datagram socket from one object to + * another. + * + * @param other The other basic_datagram_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_datagram_socket(const executor_type&) + * constructor. + */ + basic_datagram_socket& operator=(basic_datagram_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } + + /// Move-construct a basic_datagram_socket from a socket of another protocol + /// type. + /** + * This constructor moves a datagram socket from one object to another. + * + * @param other The other basic_datagram_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_datagram_socket(const executor_type&) + * constructor. + */ + template + basic_datagram_socket(basic_datagram_socket&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_datagram_socket from a socket of another protocol + /// type. + /** + * This assignment operator moves a datagram socket from one object to + * another. + * + * @param other The other basic_datagram_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_datagram_socket(const executor_type&) + * constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_datagram_socket& + >::type operator=(basic_datagram_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the socket. + /** + * This function destroys the socket, cancelling any outstanding asynchronous + * operations associated with the socket as if by calling @c cancel. + */ + ~basic_datagram_socket() + { + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the datagram socket. The function + * call will block until the data has been sent successfully or an error + * occurs. + * + * @param buffers One ore more data buffers to be sent on the socket. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected datagram socket. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code socket.send(asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the datagram socket. The function + * call will block until the data has been sent successfully or an error + * occurs. + * + * @param buffers One ore more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected datagram socket. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the datagram socket. The function + * call will block until the data has been sent successfully or an error + * occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected datagram socket. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous send on a connected socket. + /** + * This function is used to asynchronously send data on the datagram socket. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_send operation can only be used with a connected socket. + * Use the async_send_to function to send data on an unconnected datagram + * socket. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_send(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous send on a connected socket. + /** + * This function is used to asynchronously send data on the datagram socket. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_send operation can only be used with a connected socket. + * Use the async_send_to function to send data on an unconnected datagram + * socket. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, buffers, flags); + } + + /// Send a datagram to the specified endpoint. + /** + * This function is used to send a datagram to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * asio::ip::udp::endpoint destination( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.send_to(asio::buffer(data, size), destination); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send_to( + this->impl_.get_implementation(), buffers, destination, 0, ec); + asio::detail::throw_error(ec, "send_to"); + return s; + } + + /// Send a datagram to the specified endpoint. + /** + * This function is used to send a datagram to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send_to( + this->impl_.get_implementation(), buffers, destination, flags, ec); + asio::detail::throw_error(ec, "send_to"); + return s; + } + + /// Send a datagram to the specified endpoint. + /** + * This function is used to send a datagram to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + asio::error_code& ec) + { + return this->impl_.get_service().send_to(this->impl_.get_implementation(), + buffers, destination, flags, ec); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send a datagram to the specified + * remote endpoint. The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param destination The remote endpoint to which the data will be sent. + * Copies will be made of the endpoint as required. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * asio::ip::udp::endpoint destination( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.async_send_to( + * asio::buffer(data, size), destination, handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send_to(this), handler, buffers, + destination, socket_base::message_flags(0)); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send a datagram to the specified + * remote endpoint. The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param destination The remote endpoint to which the data will be sent. + * Copies will be made of the endpoint as required. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send_to(this), handler, buffers, destination, flags); + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the datagram socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected datagram + * socket. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code socket.receive(asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the datagram socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected datagram + * socket. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the datagram socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected datagram + * socket. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous receive on a connected socket. + /** + * This function is used to asynchronously receive data from the datagram + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_receive operation can only be used with a connected socket. + * Use the async_receive_from function to receive data on an unconnected + * datagram socket. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous receive on a connected socket. + /** + * This function is used to asynchronously receive data from the datagram + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_receive operation can only be used with a connected socket. + * Use the async_receive_from function to receive data on an unconnected + * datagram socket. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, buffers, flags); + } + + /// Receive a datagram with the endpoint of the sender. + /** + * This function is used to receive a datagram. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the datagram. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * asio::ip::udp::endpoint sender_endpoint; + * socket.receive_from( + * asio::buffer(data, size), sender_endpoint); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec); + asio::detail::throw_error(ec, "receive_from"); + return s; + } + + /// Receive a datagram with the endpoint of the sender. + /** + * This function is used to receive a datagram. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the datagram. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); + asio::detail::throw_error(ec, "receive_from"); + return s; + } + + /// Receive a datagram with the endpoint of the sender. + /** + * This function is used to receive a datagram. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the datagram. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + asio::error_code& ec) + { + return this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive a datagram. The function + * call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the datagram. Ownership of the sender_endpoint object + * is retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code socket.async_receive_from( + * asio::buffer(data, size), sender_endpoint, handler); @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_from(this), handler, buffers, + &sender_endpoint, socket_base::message_flags(0)); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive a datagram. The function + * call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the datagram. Ownership of the sender_endpoint object + * is retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_from(this), handler, + buffers, &sender_endpoint, flags); + } + +private: + class initiate_async_send + { + public: + typedef Executor executor_type; + + explicit initiate_async_send(basic_datagram_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_datagram_socket* self_; + }; + + class initiate_async_send_to + { + public: + typedef Executor executor_type; + + explicit initiate_async_send_to(basic_datagram_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send_to( + self_->impl_.get_implementation(), buffers, destination, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_datagram_socket* self_; + }; + + class initiate_async_receive + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive(basic_datagram_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_datagram_socket* self_; + }; + + class initiate_async_receive_from + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive_from(basic_datagram_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, endpoint_type* sender_endpoint, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive_from( + self_->impl_.get_implementation(), buffers, *sender_endpoint, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_datagram_socket* self_; + }; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_DATAGRAM_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_deadline_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_deadline_timer.hpp new file mode 100644 index 00000000..01adaf51 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_deadline_timer.hpp @@ -0,0 +1,693 @@ +// +// basic_deadline_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_DEADLINE_TIMER_HPP +#define ASIO_BASIC_DEADLINE_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/detail/deadline_timer_service.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/time_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides waitable timer functionality. +/** + * The basic_deadline_timer class template provides the ability to perform a + * blocking or asynchronous wait for a timer to expire. + * + * A deadline timer is always in one of two states: "expired" or "not expired". + * If the wait() or async_wait() function is called on an expired timer, the + * wait operation will complete immediately. + * + * Most applications will use the asio::deadline_timer typedef. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Examples + * Performing a blocking wait: + * @code + * // Construct a timer without setting an expiry time. + * asio::deadline_timer timer(my_context); + * + * // Set an expiry time relative to now. + * timer.expires_from_now(boost::posix_time::seconds(5)); + * + * // Wait for the timer to expire. + * timer.wait(); + * @endcode + * + * @par + * Performing an asynchronous wait: + * @code + * void handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Timer expired. + * } + * } + * + * ... + * + * // Construct a timer with an absolute expiry time. + * asio::deadline_timer timer(my_context, + * boost::posix_time::time_from_string("2005-12-07 23:59:59.000")); + * + * // Start an asynchronous wait. + * timer.async_wait(handler); + * @endcode + * + * @par Changing an active deadline_timer's expiry time + * + * Changing the expiry time of a timer while there are pending asynchronous + * waits causes those wait operations to be cancelled. To ensure that the action + * associated with the timer is performed only once, use something like this: + * used: + * + * @code + * void on_some_event() + * { + * if (my_timer.expires_from_now(seconds(5)) > 0) + * { + * // We managed to cancel the timer. Start new asynchronous wait. + * my_timer.async_wait(on_timeout); + * } + * else + * { + * // Too late, timer has already expired! + * } + * } + * + * void on_timeout(const asio::error_code& e) + * { + * if (e != asio::error::operation_aborted) + * { + * // Timer was not cancelled, take necessary action. + * } + * } + * @endcode + * + * @li The asio::basic_deadline_timer::expires_from_now() function + * cancels any pending asynchronous waits, and returns the number of + * asynchronous waits that were cancelled. If it returns 0 then you were too + * late and the wait handler has already been executed, or will soon be + * executed. If it returns 1 then the wait handler was successfully cancelled. + * + * @li If a wait handler is cancelled, the asio::error_code passed to + * it contains the value asio::error::operation_aborted. + */ +template , + typename Executor = executor> +class basic_deadline_timer +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the timer type to another executor. + template + struct rebind_executor + { + /// The timer type when rebound to the specified executor. + typedef basic_deadline_timer other; + }; + + /// The time traits type. + typedef TimeTraits traits_type; + + /// The time type. + typedef typename traits_type::time_type time_type; + + /// The duration type. + typedef typename traits_type::duration_type duration_type; + + /// Constructor. + /** + * This constructor creates a timer without setting an expiry time. The + * expires_at() or expires_from_now() functions must be called to set an + * expiry time before the timer can be waited on. + * + * @param ex The I/O executor that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + */ + explicit basic_deadline_timer(const executor_type& ex) + : impl_(ex) + { + } + + /// Constructor. + /** + * This constructor creates a timer without setting an expiry time. The + * expires_at() or expires_from_now() functions must be called to set an + * expiry time before the timer can be waited on. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + */ + template + explicit basic_deadline_timer(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param ex The I/O executor that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, expressed + * as an absolute time. + */ + basic_deadline_timer(const executor_type& ex, const time_type& expiry_time) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, expressed + * as an absolute time. + */ + template + basic_deadline_timer(ExecutionContext& context, const time_type& expiry_time, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + } + + /// Constructor to set a particular expiry time relative to now. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param ex The I/O executor that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, relative to + * now. + */ + basic_deadline_timer(const executor_type& ex, + const duration_type& expiry_time) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_from_now"); + } + + /// Constructor to set a particular expiry time relative to now. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, relative to + * now. + */ + template + basic_deadline_timer(ExecutionContext& context, + const duration_type& expiry_time, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_from_now"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_deadline_timer from another. + /** + * This constructor moves a timer from one object to another. + * + * @param other The other basic_deadline_timer object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_deadline_timer(const executor_type&) + * constructor. + */ + basic_deadline_timer(basic_deadline_timer&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_deadline_timer from another. + /** + * This assignment operator moves a timer from one object to another. Cancels + * any outstanding asynchronous operations associated with the target object. + * + * @param other The other basic_deadline_timer object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_deadline_timer(const executor_type&) + * constructor. + */ + basic_deadline_timer& operator=(basic_deadline_timer&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the timer. + /** + * This function destroys the timer, cancelling any outstanding asynchronous + * wait operations associated with the timer as if by calling @c cancel. + */ + ~basic_deadline_timer() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Cancel any asynchronous operations that are waiting on the timer. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the timer. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel() + { + asio::error_code ec; + std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + return s; + } + + /// Cancel any asynchronous operations that are waiting on the timer. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the timer. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel(asio::error_code& ec) + { + return impl_.get_service().cancel(impl_.get_implementation(), ec); + } + + /// Cancels one asynchronous operation that is waiting on the timer. + /** + * This function forces the completion of one pending asynchronous wait + * operation against the timer. Handlers are cancelled in FIFO order. The + * handler for the cancelled operation will be invoked with the + * asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @return The number of asynchronous operations that were cancelled. That is, + * either 0 or 1. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when cancel_one() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel_one() + { + asio::error_code ec; + std::size_t s = impl_.get_service().cancel_one( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel_one"); + return s; + } + + /// Cancels one asynchronous operation that is waiting on the timer. + /** + * This function forces the completion of one pending asynchronous wait + * operation against the timer. Handlers are cancelled in FIFO order. The + * handler for the cancelled operation will be invoked with the + * asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. That is, + * either 0 or 1. + * + * @note If the timer has already expired when cancel_one() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel_one(asio::error_code& ec) + { + return impl_.get_service().cancel_one(impl_.get_implementation(), ec); + } + + /// Get the timer's expiry time as an absolute time. + /** + * This function may be used to obtain the timer's current expiry time. + * Whether the timer has expired or not does not affect this value. + */ + time_type expires_at() const + { + return impl_.get_service().expires_at(impl_.get_implementation()); + } + + /// Set the timer's expiry time as an absolute time. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when expires_at() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_at(const time_type& expiry_time) + { + asio::error_code ec; + std::size_t s = impl_.get_service().expires_at( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + return s; + } + + /// Set the timer's expiry time as an absolute time. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when expires_at() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_at(const time_type& expiry_time, + asio::error_code& ec) + { + return impl_.get_service().expires_at( + impl_.get_implementation(), expiry_time, ec); + } + + /// Get the timer's expiry time relative to now. + /** + * This function may be used to obtain the timer's current expiry time. + * Whether the timer has expired or not does not affect this value. + */ + duration_type expires_from_now() const + { + return impl_.get_service().expires_from_now(impl_.get_implementation()); + } + + /// Set the timer's expiry time relative to now. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when expires_from_now() is called, + * then the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_from_now(const duration_type& expiry_time) + { + asio::error_code ec; + std::size_t s = impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_from_now"); + return s; + } + + /// Set the timer's expiry time relative to now. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when expires_from_now() is called, + * then the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_from_now(const duration_type& expiry_time, + asio::error_code& ec) + { + return impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + } + + /// Perform a blocking wait on the timer. + /** + * This function is used to wait for the timer to expire. This function + * blocks and does not return until the timer has expired. + * + * @throws asio::system_error Thrown on failure. + */ + void wait() + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Perform a blocking wait on the timer. + /** + * This function is used to wait for the timer to expire. This function + * blocks and does not return until the timer has expired. + * + * @param ec Set to indicate what error occurred, if any. + */ + void wait(asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), ec); + } + + /// Start an asynchronous wait on the timer. + /** + * This function may be used to initiate an asynchronous wait against the + * timer. It always returns immediately. + * + * For each call to async_wait(), the supplied handler will be called exactly + * once. The handler will be called when: + * + * @li The timer has expired. + * + * @li The timer was cancelled, in which case the handler is passed the error + * code asio::error::operation_aborted. + * + * @param handler The handler to be called when the timer expires. Copies + * will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait( + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler); + } + +private: + // Disallow copying and assignment. + basic_deadline_timer(const basic_deadline_timer&) ASIO_DELETED; + basic_deadline_timer& operator=( + const basic_deadline_timer&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_deadline_timer* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_deadline_timer* self_; + }; + + detail::io_object_impl< + detail::deadline_timer_service, Executor> impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_BASIC_DEADLINE_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_io_object.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_io_object.hpp new file mode 100644 index 00000000..faf20034 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_io_object.hpp @@ -0,0 +1,290 @@ +// +// basic_io_object.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_IO_OBJECT_HPP +#define ASIO_BASIC_IO_OBJECT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_MOVE) +namespace detail +{ + // Type trait used to determine whether a service supports move. + template + class service_has_move + { + private: + typedef IoObjectService service_type; + typedef typename service_type::implementation_type implementation_type; + + template + static auto asio_service_has_move_eval(T* t, U* u) + -> decltype(t->move_construct(*u, *u), char()); + static char (&asio_service_has_move_eval(...))[2]; + + public: + static const bool value = + sizeof(asio_service_has_move_eval( + static_cast(0), + static_cast(0))) == 1; + }; +} +#endif // defined(ASIO_HAS_MOVE) + +/// Base class for all I/O objects. +/** + * @note All I/O objects are non-copyable. However, when using C++0x, certain + * I/O objects do support move construction and move assignment. + */ +#if !defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) +template +#else +template ::value> +#endif +class basic_io_object +{ +public: + /// The type of the service that will be used to provide I/O operations. + typedef IoObjectService service_type; + + /// The underlying implementation type of I/O object. + typedef typename service_type::implementation_type implementation_type; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + /** + * This function may be used to obtain the io_context object that the I/O + * object uses to dispatch handlers for asynchronous operations. + * + * @return A reference to the io_context object that the I/O object will use + * to dispatch handlers. Ownership is not transferred to the caller. + */ + asio::io_context& get_io_context() + { + return service_.get_io_context(); + } + + /// (Deprecated: Use get_executor().) Get the io_context associated with the + /// object. + /** + * This function may be used to obtain the io_context object that the I/O + * object uses to dispatch handlers for asynchronous operations. + * + * @return A reference to the io_context object that the I/O object will use + * to dispatch handlers. Ownership is not transferred to the caller. + */ + asio::io_context& get_io_service() + { + return service_.get_io_context(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// The type of the executor associated with the object. + typedef asio::io_context::executor_type executor_type; + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return service_.get_io_context().get_executor(); + } + +protected: + /// Construct a basic_io_object. + /** + * Performs: + * @code get_service().construct(get_implementation()); @endcode + */ + explicit basic_io_object(asio::io_context& io_context) + : service_(asio::use_service(io_context)) + { + service_.construct(implementation_); + } + +#if defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_io_object. + /** + * Performs: + * @code get_service().move_construct( + * get_implementation(), other.get_implementation()); @endcode + * + * @note Available only for services that support movability, + */ + basic_io_object(basic_io_object&& other); + + /// Move-assign a basic_io_object. + /** + * Performs: + * @code get_service().move_assign(get_implementation(), + * other.get_service(), other.get_implementation()); @endcode + * + * @note Available only for services that support movability, + */ + basic_io_object& operator=(basic_io_object&& other); + + /// Perform a converting move-construction of a basic_io_object. + template + basic_io_object(IoObjectService1& other_service, + typename IoObjectService1::implementation_type& other_implementation); +#endif // defined(GENERATING_DOCUMENTATION) + + /// Protected destructor to prevent deletion through this type. + /** + * Performs: + * @code get_service().destroy(get_implementation()); @endcode + */ + ~basic_io_object() + { + service_.destroy(implementation_); + } + + /// Get the service associated with the I/O object. + service_type& get_service() + { + return service_; + } + + /// Get the service associated with the I/O object. + const service_type& get_service() const + { + return service_; + } + + /// Get the underlying implementation of the I/O object. + implementation_type& get_implementation() + { + return implementation_; + } + + /// Get the underlying implementation of the I/O object. + const implementation_type& get_implementation() const + { + return implementation_; + } + +private: + basic_io_object(const basic_io_object&); + basic_io_object& operator=(const basic_io_object&); + + // The service associated with the I/O object. + service_type& service_; + + /// The underlying implementation of the I/O object. + implementation_type implementation_; +}; + +#if defined(ASIO_HAS_MOVE) +// Specialisation for movable objects. +template +class basic_io_object +{ +public: + typedef IoObjectService service_type; + typedef typename service_type::implementation_type implementation_type; + +#if !defined(ASIO_NO_DEPRECATED) + asio::io_context& get_io_context() + { + return service_->get_io_context(); + } + + asio::io_context& get_io_service() + { + return service_->get_io_context(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + typedef asio::io_context::executor_type executor_type; + + executor_type get_executor() ASIO_NOEXCEPT + { + return service_->get_io_context().get_executor(); + } + +protected: + explicit basic_io_object(asio::io_context& io_context) + : service_(&asio::use_service(io_context)) + { + service_->construct(implementation_); + } + + basic_io_object(basic_io_object&& other) + : service_(&other.get_service()) + { + service_->move_construct(implementation_, other.implementation_); + } + + template + basic_io_object(IoObjectService1& other_service, + typename IoObjectService1::implementation_type& other_implementation) + : service_(&asio::use_service( + other_service.get_io_context())) + { + service_->converting_move_construct(implementation_, + other_service, other_implementation); + } + + ~basic_io_object() + { + service_->destroy(implementation_); + } + + basic_io_object& operator=(basic_io_object&& other) + { + service_->move_assign(implementation_, + *other.service_, other.implementation_); + service_ = other.service_; + return *this; + } + + service_type& get_service() + { + return *service_; + } + + const service_type& get_service() const + { + return *service_; + } + + implementation_type& get_implementation() + { + return implementation_; + } + + const implementation_type& get_implementation() const + { + return implementation_; + } + +private: + basic_io_object(const basic_io_object&); + void operator=(const basic_io_object&); + + IoObjectService* service_; + implementation_type implementation_; +}; +#endif // defined(ASIO_HAS_MOVE) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_IO_OBJECT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_raw_socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_raw_socket.hpp new file mode 100644 index 00000000..64ee351c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_raw_socket.hpp @@ -0,0 +1,1202 @@ +// +// basic_raw_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_RAW_SOCKET_HPP +#define ASIO_BASIC_RAW_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_RAW_SOCKET_FWD_DECL) +#define ASIO_BASIC_RAW_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_raw_socket; + +#endif // !defined(ASIO_BASIC_RAW_SOCKET_FWD_DECL) + +/// Provides raw-oriented socket functionality. +/** + * The basic_raw_socket class template provides asynchronous and blocking + * raw-oriented socket functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_raw_socket + : public basic_socket +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the socket type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_raw_socket other; + }; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// Construct a basic_raw_socket without opening it. + /** + * This constructor creates a raw socket without opening it. The open() + * function must be called before data can be sent or received on the socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_raw_socket(const executor_type& ex) + : basic_socket(ex) + { + } + + /// Construct a basic_raw_socket without opening it. + /** + * This constructor creates a raw socket without opening it. The open() + * function must be called before data can be sent or received on the socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + */ + template + explicit basic_raw_socket(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context) + { + } + + /// Construct and open a basic_raw_socket. + /** + * This constructor creates and opens a raw socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_raw_socket(const executor_type& ex, const protocol_type& protocol) + : basic_socket(ex, protocol) + { + } + + /// Construct and open a basic_raw_socket. + /** + * This constructor creates and opens a raw socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_raw_socket(ExecutionContext& context, const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol) + { + } + + /// Construct a basic_raw_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a raw socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the raw + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + basic_raw_socket(const executor_type& ex, const endpoint_type& endpoint) + : basic_socket(ex, endpoint) + { + } + + /// Construct a basic_raw_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a raw socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the raw + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_raw_socket(ExecutionContext& context, const endpoint_type& endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, endpoint) + { + } + + /// Construct a basic_raw_socket on an existing native socket. + /** + * This constructor creates a raw socket object to hold an existing + * native socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_raw_socket(const executor_type& ex, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket(ex, protocol, native_socket) + { + } + + /// Construct a basic_raw_socket on an existing native socket. + /** + * This constructor creates a raw socket object to hold an existing + * native socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_raw_socket(ExecutionContext& context, + const protocol_type& protocol, const native_handle_type& native_socket, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol, native_socket) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_raw_socket from another. + /** + * This constructor moves a raw socket from one object to another. + * + * @param other The other basic_raw_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_raw_socket(const executor_type&) + * constructor. + */ + basic_raw_socket(basic_raw_socket&& other) ASIO_NOEXCEPT + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_raw_socket from another. + /** + * This assignment operator moves a raw socket from one object to another. + * + * @param other The other basic_raw_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_raw_socket(const executor_type&) + * constructor. + */ + basic_raw_socket& operator=(basic_raw_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } + + /// Move-construct a basic_raw_socket from a socket of another protocol + /// type. + /** + * This constructor moves a raw socket from one object to another. + * + * @param other The other basic_raw_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_raw_socket(const executor_type&) + * constructor. + */ + template + basic_raw_socket(basic_raw_socket&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_raw_socket from a socket of another protocol type. + /** + * This assignment operator moves a raw socket from one object to another. + * + * @param other The other basic_raw_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_raw_socket(const executor_type&) + * constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_raw_socket& + >::type operator=(basic_raw_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the socket. + /** + * This function destroys the socket, cancelling any outstanding asynchronous + * operations associated with the socket as if by calling @c cancel. + */ + ~basic_raw_socket() + { + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the raw socket. The function call + * will block until the data has been sent successfully or an error occurs. + * + * @param buffers One ore more data buffers to be sent on the socket. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected raw socket. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code socket.send(asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the raw socket. The function call + * will block until the data has been sent successfully or an error occurs. + * + * @param buffers One ore more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected raw socket. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on a connected socket. + /** + * This function is used to send data on the raw socket. The function call + * will block until the data has been sent successfully or an error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. + * + * @note The send operation can only be used with a connected socket. Use + * the send_to function to send data on an unconnected raw socket. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous send on a connected socket. + /** + * This function is used to send data on the raw socket. The function call + * will block until the data has been sent successfully or an error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_send operation can only be used with a connected socket. + * Use the async_send_to function to send data on an unconnected raw + * socket. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_send(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous send on a connected socket. + /** + * This function is used to send data on the raw socket. The function call + * will block until the data has been sent successfully or an error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_send operation can only be used with a connected socket. + * Use the async_send_to function to send data on an unconnected raw + * socket. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, buffers, flags); + } + + /// Send raw data to the specified endpoint. + /** + * This function is used to send raw data to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * asio::ip::udp::endpoint destination( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.send_to(asio::buffer(data, size), destination); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send_to( + this->impl_.get_implementation(), buffers, destination, 0, ec); + asio::detail::throw_error(ec, "send_to"); + return s; + } + + /// Send raw data to the specified endpoint. + /** + * This function is used to send raw data to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send_to( + this->impl_.get_implementation(), buffers, destination, flags, ec); + asio::detail::throw_error(ec, "send_to"); + return s; + } + + /// Send raw data to the specified endpoint. + /** + * This function is used to send raw data to the specified remote endpoint. + * The function call will block until the data has been sent successfully or + * an error occurs. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * + * @param destination The remote endpoint to which the data will be sent. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. + */ + template + std::size_t send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + asio::error_code& ec) + { + return this->impl_.get_service().send_to(this->impl_.get_implementation(), + buffers, destination, flags, ec); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send raw data to the specified + * remote endpoint. The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param destination The remote endpoint to which the data will be sent. + * Copies will be made of the endpoint as required. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * asio::ip::udp::endpoint destination( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.async_send_to( + * asio::buffer(data, size), destination, handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send_to(this), handler, buffers, + destination, socket_base::message_flags(0)); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send raw data to the specified + * remote endpoint. The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent to the remote endpoint. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param destination The remote endpoint to which the data will be sent. + * Copies will be made of the endpoint as required. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send_to(const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send_to(this), handler, buffers, destination, flags); + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the raw socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected raw + * socket. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code socket.receive(asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the raw socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected raw + * socket. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the raw socket. The function + * call will block until data has been received successfully or an error + * occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. + * + * @note The receive operation can only be used with a connected socket. Use + * the receive_from function to receive data on an unconnected raw + * socket. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous receive on a connected socket. + /** + * This function is used to asynchronously receive data from the raw + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_receive operation can only be used with a connected socket. + * Use the async_receive_from function to receive data on an unconnected + * raw socket. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous receive on a connected socket. + /** + * This function is used to asynchronously receive data from the raw + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The async_receive operation can only be used with a connected socket. + * Use the async_receive_from function to receive data on an unconnected + * raw socket. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, buffers, flags); + } + + /// Receive raw data with the endpoint of the sender. + /** + * This function is used to receive raw data. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the data. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * asio::ip::udp::endpoint sender_endpoint; + * socket.receive_from( + * asio::buffer(data, size), sender_endpoint); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec); + asio::detail::throw_error(ec, "receive_from"); + return s; + } + + /// Receive raw data with the endpoint of the sender. + /** + * This function is used to receive raw data. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the data. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); + asio::detail::throw_error(ec, "receive_from"); + return s; + } + + /// Receive raw data with the endpoint of the sender. + /** + * This function is used to receive raw data. The function call will block + * until data has been received successfully or an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the data. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. + */ + template + std::size_t receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + asio::error_code& ec) + { + return this->impl_.get_service().receive_from( + this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive raw data. The function + * call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the data. Ownership of the sender_endpoint object + * is retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code socket.async_receive_from( + * asio::buffer(data, size), 0, sender_endpoint, handler); @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_from(this), handler, buffers, + &sender_endpoint, socket_base::message_flags(0)); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive raw data. The function + * call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param sender_endpoint An endpoint object that receives the endpoint of + * the remote sender of the data. Ownership of the sender_endpoint object + * is retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive_from(const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_from(this), handler, + buffers, &sender_endpoint, flags); + } + +private: + class initiate_async_send + { + public: + typedef Executor executor_type; + + explicit initiate_async_send(basic_raw_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_raw_socket* self_; + }; + + class initiate_async_send_to + { + public: + typedef Executor executor_type; + + explicit initiate_async_send_to(basic_raw_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send_to( + self_->impl_.get_implementation(), buffers, destination, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_raw_socket* self_; + }; + + class initiate_async_receive + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive(basic_raw_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_raw_socket* self_; + }; + + class initiate_async_receive_from + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive_from(basic_raw_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, endpoint_type* sender_endpoint, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive_from( + self_->impl_.get_implementation(), buffers, *sender_endpoint, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_raw_socket* self_; + }; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_RAW_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_seq_packet_socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_seq_packet_socket.hpp new file mode 100644 index 00000000..11ec3542 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_seq_packet_socket.hpp @@ -0,0 +1,756 @@ +// +// basic_seq_packet_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SEQ_PACKET_SOCKET_HPP +#define ASIO_BASIC_SEQ_PACKET_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL) +#define ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_seq_packet_socket; + +#endif // !defined(ASIO_BASIC_SEQ_PACKET_SOCKET_FWD_DECL) + +/// Provides sequenced packet socket functionality. +/** + * The basic_seq_packet_socket class template provides asynchronous and blocking + * sequenced packet socket functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_seq_packet_socket + : public basic_socket +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the socket type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_seq_packet_socket other; + }; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// Construct a basic_seq_packet_socket without opening it. + /** + * This constructor creates a sequenced packet socket without opening it. The + * socket needs to be opened and then connected or accepted before data can + * be sent or received on it. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_seq_packet_socket(const executor_type& ex) + : basic_socket(ex) + { + } + + /// Construct a basic_seq_packet_socket without opening it. + /** + * This constructor creates a sequenced packet socket without opening it. The + * socket needs to be opened and then connected or accepted before data can + * be sent or received on it. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + */ + template + explicit basic_seq_packet_socket(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context) + { + } + + /// Construct and open a basic_seq_packet_socket. + /** + * This constructor creates and opens a sequenced_packet socket. The socket + * needs to be connected or accepted before data can be sent or received on + * it. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_seq_packet_socket(const executor_type& ex, + const protocol_type& protocol) + : basic_socket(ex, protocol) + { + } + + /// Construct and open a basic_seq_packet_socket. + /** + * This constructor creates and opens a sequenced_packet socket. The socket + * needs to be connected or accepted before data can be sent or received on + * it. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_seq_packet_socket(ExecutionContext& context, + const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol) + { + } + + /// Construct a basic_seq_packet_socket, opening it and binding it to the + /// given local endpoint. + /** + * This constructor creates a sequenced packet socket and automatically opens + * it bound to the specified endpoint on the local machine. The protocol used + * is the protocol associated with the given endpoint. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the sequenced + * packet socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + basic_seq_packet_socket(const executor_type& ex, + const endpoint_type& endpoint) + : basic_socket(ex, endpoint) + { + } + + /// Construct a basic_seq_packet_socket, opening it and binding it to the + /// given local endpoint. + /** + * This constructor creates a sequenced packet socket and automatically opens + * it bound to the specified endpoint on the local machine. The protocol used + * is the protocol associated with the given endpoint. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the sequenced + * packet socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_seq_packet_socket(ExecutionContext& context, + const endpoint_type& endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, endpoint) + { + } + + /// Construct a basic_seq_packet_socket on an existing native socket. + /** + * This constructor creates a sequenced packet socket object to hold an + * existing native socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_seq_packet_socket(const executor_type& ex, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket(ex, protocol, native_socket) + { + } + + /// Construct a basic_seq_packet_socket on an existing native socket. + /** + * This constructor creates a sequenced packet socket object to hold an + * existing native socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_seq_packet_socket(ExecutionContext& context, + const protocol_type& protocol, const native_handle_type& native_socket, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol, native_socket) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_seq_packet_socket from another. + /** + * This constructor moves a sequenced packet socket from one object to + * another. + * + * @param other The other basic_seq_packet_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_seq_packet_socket(const executor_type&) + * constructor. + */ + basic_seq_packet_socket(basic_seq_packet_socket&& other) ASIO_NOEXCEPT + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_seq_packet_socket from another. + /** + * This assignment operator moves a sequenced packet socket from one object to + * another. + * + * @param other The other basic_seq_packet_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_seq_packet_socket(const executor_type&) + * constructor. + */ + basic_seq_packet_socket& operator=(basic_seq_packet_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } + + /// Move-construct a basic_seq_packet_socket from a socket of another protocol + /// type. + /** + * This constructor moves a sequenced packet socket from one object to + * another. + * + * @param other The other basic_seq_packet_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_seq_packet_socket(const executor_type&) + * constructor. + */ + template + basic_seq_packet_socket(basic_seq_packet_socket&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_seq_packet_socket from a socket of another protocol + /// type. + /** + * This assignment operator moves a sequenced packet socket from one object to + * another. + * + * @param other The other basic_seq_packet_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_seq_packet_socket(const executor_type&) + * constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_seq_packet_socket& + >::type operator=(basic_seq_packet_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the socket. + /** + * This function destroys the socket, cancelling any outstanding asynchronous + * operations associated with the socket as if by calling @c cancel. + */ + ~basic_seq_packet_socket() + { + } + + /// Send some data on the socket. + /** + * This function is used to send data on the sequenced packet socket. The + * function call will block until the data has been sent successfully, or an + * until error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.send(asio::buffer(data, size), 0); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on the socket. + /** + * This function is used to send data on the sequenced packet socket. The + * function call will block the data has been sent successfully, or an until + * error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. Returns 0 if an error occurred. + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref write function if you need to ensure that all data + * is written before the blocking operation completes. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send data on the sequenced packet + * socket. The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_send(asio::buffer(data, size), 0, handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, buffers, flags); + } + + /// Receive some data on the socket. + /** + * This function is used to receive data on the sequenced packet socket. The + * function call will block until data has been received successfully, or + * until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param out_flags After the receive call completes, contains flags + * associated with the received data. For example, if the + * socket_base::message_end_of_record bit is set then the received data marks + * the end of a record. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.receive(asio::buffer(data, size), out_flags); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags& out_flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_with_flags( + this->impl_.get_implementation(), buffers, 0, out_flags, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on the socket. + /** + * This function is used to receive data on the sequenced packet socket. The + * function call will block until data has been received successfully, or + * until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param in_flags Flags specifying how the receive call is to be made. + * + * @param out_flags After the receive call completes, contains flags + * associated with the received data. For example, if the + * socket_base::message_end_of_record bit is set then the received data marks + * the end of a record. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.receive(asio::buffer(data, size), 0, out_flags); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags& out_flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive_with_flags( + this->impl_.get_implementation(), buffers, in_flags, out_flags, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the sequenced packet socket. The + * function call will block until data has been received successfully, or + * until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param in_flags Flags specifying how the receive call is to be made. + * + * @param out_flags After the receive call completes, contains flags + * associated with the received data. For example, if the + * socket_base::message_end_of_record bit is set then the received data marks + * the end of a record. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. Returns 0 if an error occurred. + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + return this->impl_.get_service().receive_with_flags( + this->impl_.get_implementation(), buffers, in_flags, out_flags, ec); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive data from the sequenced + * packet socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param out_flags Once the asynchronous operation completes, contains flags + * associated with the received data. For example, if the + * socket_base::message_end_of_record bit is set then the received data marks + * the end of a record. The caller must guarantee that the referenced + * variable remains valid until the handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive(asio::buffer(data, size), out_flags, handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + socket_base::message_flags& out_flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_with_flags(this), handler, + buffers, socket_base::message_flags(0), &out_flags); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive data from the sequenced + * data socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param in_flags Flags specifying how the receive call is to be made. + * + * @param out_flags Once the asynchronous operation completes, contains flags + * associated with the received data. For example, if the + * socket_base::message_end_of_record bit is set then the received data marks + * the end of a record. The caller must guarantee that the referenced + * variable remains valid until the handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive( + * asio::buffer(data, size), + * 0, out_flags, handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive_with_flags(this), + handler, buffers, in_flags, &out_flags); + } + +private: + class initiate_async_send + { + public: + typedef Executor executor_type; + + explicit initiate_async_send(basic_seq_packet_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_seq_packet_socket* self_; + }; + + class initiate_async_receive_with_flags + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive_with_flags(basic_seq_packet_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags* out_flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive_with_flags( + self_->impl_.get_implementation(), buffers, in_flags, *out_flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_seq_packet_socket* self_; + }; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_SEQ_PACKET_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_serial_port.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_serial_port.hpp new file mode 100644 index 00000000..b1d9c4a2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_serial_port.hpp @@ -0,0 +1,907 @@ +// +// basic_serial_port.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SERIAL_PORT_HPP +#define ASIO_BASIC_SERIAL_PORT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_SERIAL_PORT) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/serial_port_base.hpp" +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_serial_port_service.hpp" +#else +# include "asio/detail/reactive_serial_port_service.hpp" +#endif + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides serial port functionality. +/** + * The basic_serial_port class provides a wrapper over serial port + * functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_serial_port + : public serial_port_base +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the serial port type to another executor. + template + struct rebind_executor + { + /// The serial port type when rebound to the specified executor. + typedef basic_serial_port other; + }; + + /// The native representation of a serial port. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#elif defined(ASIO_HAS_IOCP) + typedef detail::win_iocp_serial_port_service::native_handle_type + native_handle_type; +#else + typedef detail::reactive_serial_port_service::native_handle_type + native_handle_type; +#endif + + /// A basic_basic_serial_port is always the lowest layer. + typedef basic_serial_port lowest_layer_type; + + /// Construct a basic_serial_port without opening it. + /** + * This constructor creates a serial port without opening it. + * + * @param ex The I/O executor that the serial port will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * serial port. + */ + explicit basic_serial_port(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct a basic_serial_port without opening it. + /** + * This constructor creates a serial port without opening it. + * + * @param context An execution context which provides the I/O executor that + * the serial port will use, by default, to dispatch handlers for any + * asynchronous operations performed on the serial port. + */ + template + explicit basic_serial_port(ExecutionContext& context, + typename enable_if< + is_convertible::value, + basic_serial_port + >::type* = 0) + : impl_(context) + { + } + + /// Construct and open a basic_serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param ex The I/O executor that the serial port will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * serial port. + * + * @param device The platform-specific device name for this serial + * port. + */ + basic_serial_port(const executor_type& ex, const char* device) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct and open a basic_serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param context An execution context which provides the I/O executor that + * the serial port will use, by default, to dispatch handlers for any + * asynchronous operations performed on the serial port. + * + * @param device The platform-specific device name for this serial + * port. + */ + template + basic_serial_port(ExecutionContext& context, const char* device, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct and open a basic_serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param ex The I/O executor that the serial port will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * serial port. + * + * @param device The platform-specific device name for this serial + * port. + */ + basic_serial_port(const executor_type& ex, const std::string& device) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct and open a basic_serial_port. + /** + * This constructor creates and opens a serial port for the specified device + * name. + * + * @param context An execution context which provides the I/O executor that + * the serial port will use, by default, to dispatch handlers for any + * asynchronous operations performed on the serial port. + * + * @param device The platform-specific device name for this serial + * port. + */ + template + basic_serial_port(ExecutionContext& context, const std::string& device, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct a basic_serial_port on an existing native serial port. + /** + * This constructor creates a serial port object to hold an existing native + * serial port. + * + * @param ex The I/O executor that the serial port will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * serial port. + * + * @param native_serial_port A native serial port. + * + * @throws asio::system_error Thrown on failure. + */ + basic_serial_port(const executor_type& ex, + const native_handle_type& native_serial_port) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_serial_port, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct a basic_serial_port on an existing native serial port. + /** + * This constructor creates a serial port object to hold an existing native + * serial port. + * + * @param context An execution context which provides the I/O executor that + * the serial port will use, by default, to dispatch handlers for any + * asynchronous operations performed on the serial port. + * + * @param native_serial_port A native serial port. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_serial_port(ExecutionContext& context, + const native_handle_type& native_serial_port, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_serial_port, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_serial_port from another. + /** + * This constructor moves a serial port from one object to another. + * + * @param other The other basic_serial_port object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_serial_port(const executor_type&) + * constructor. + */ + basic_serial_port(basic_serial_port&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_serial_port from another. + /** + * This assignment operator moves a serial port from one object to another. + * + * @param other The other basic_serial_port object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_serial_port(const executor_type&) + * constructor. + */ + basic_serial_port& operator=(basic_serial_port&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the serial port. + /** + * This function destroys the serial port, cancelling any outstanding + * asynchronous wait operations associated with the serial port as if by + * calling @c cancel. + */ + ~basic_serial_port() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since a basic_serial_port cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A reference to the lowest layer in the stack of layers. Ownership + * is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return *this; + } + + /// Get a const reference to the lowest layer. + /** + * This function returns a const reference to the lowest layer in a stack of + * layers. Since a basic_serial_port cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A const reference to the lowest layer in the stack of layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return *this; + } + + /// Open the serial port using the specified device name. + /** + * This function opens the serial port for the specified device name. + * + * @param device The platform-specific device name. + * + * @throws asio::system_error Thrown on failure. + */ + void open(const std::string& device) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), device, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Open the serial port using the specified device name. + /** + * This function opens the serial port using the given platform-specific + * device name. + * + * @param device The platform-specific device name. + * + * @param ec Set the indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID open(const std::string& device, + asio::error_code& ec) + { + impl_.get_service().open(impl_.get_implementation(), device, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native serial port to the serial port. + /* + * This function opens the serial port to hold an existing native serial port. + * + * @param native_serial_port A native serial port. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const native_handle_type& native_serial_port) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_serial_port, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assign an existing native serial port to the serial port. + /* + * This function opens the serial port to hold an existing native serial port. + * + * @param native_serial_port A native serial port. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const native_handle_type& native_serial_port, + asio::error_code& ec) + { + impl_.get_service().assign(impl_.get_implementation(), + native_serial_port, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the serial port is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Close the serial port. + /** + * This function is used to close the serial port. Any asynchronous read or + * write operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the serial port. + /** + * This function is used to close the serial port. Any asynchronous read or + * write operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native serial port representation. + /** + * This function may be used to obtain the underlying representation of the + * serial port. This is intended to allow access to native serial port + * functionality that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the serial port. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the serial port. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Send a break sequence to the serial port. + /** + * This function causes a break sequence of platform-specific duration to be + * sent out the serial port. + * + * @throws asio::system_error Thrown on failure. + */ + void send_break() + { + asio::error_code ec; + impl_.get_service().send_break(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "send_break"); + } + + /// Send a break sequence to the serial port. + /** + * This function causes a break sequence of platform-specific duration to be + * sent out the serial port. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID send_break(asio::error_code& ec) + { + impl_.get_service().send_break(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Set an option on the serial port. + /** + * This function is used to set an option on the serial port. + * + * @param option The option value to be set on the serial port. + * + * @throws asio::system_error Thrown on failure. + * + * @sa SettableSerialPortOption @n + * asio::serial_port_base::baud_rate @n + * asio::serial_port_base::flow_control @n + * asio::serial_port_base::parity @n + * asio::serial_port_base::stop_bits @n + * asio::serial_port_base::character_size + */ + template + void set_option(const SettableSerialPortOption& option) + { + asio::error_code ec; + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "set_option"); + } + + /// Set an option on the serial port. + /** + * This function is used to set an option on the serial port. + * + * @param option The option value to be set on the serial port. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa SettableSerialPortOption @n + * asio::serial_port_base::baud_rate @n + * asio::serial_port_base::flow_control @n + * asio::serial_port_base::parity @n + * asio::serial_port_base::stop_bits @n + * asio::serial_port_base::character_size + */ + template + ASIO_SYNC_OP_VOID set_option(const SettableSerialPortOption& option, + asio::error_code& ec) + { + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get an option from the serial port. + /** + * This function is used to get the current value of an option on the serial + * port. + * + * @param option The option value to be obtained from the serial port. + * + * @throws asio::system_error Thrown on failure. + * + * @sa GettableSerialPortOption @n + * asio::serial_port_base::baud_rate @n + * asio::serial_port_base::flow_control @n + * asio::serial_port_base::parity @n + * asio::serial_port_base::stop_bits @n + * asio::serial_port_base::character_size + */ + template + void get_option(GettableSerialPortOption& option) const + { + asio::error_code ec; + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "get_option"); + } + + /// Get an option from the serial port. + /** + * This function is used to get the current value of an option on the serial + * port. + * + * @param option The option value to be obtained from the serial port. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa GettableSerialPortOption @n + * asio::serial_port_base::baud_rate @n + * asio::serial_port_base::flow_control @n + * asio::serial_port_base::parity @n + * asio::serial_port_base::stop_bits @n + * asio::serial_port_base::character_size + */ + template + ASIO_SYNC_OP_VOID get_option(GettableSerialPortOption& option, + asio::error_code& ec) const + { + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Write some data to the serial port. + /** + * This function is used to write data to the serial port. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the serial port. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * basic_serial_port.write_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = impl_.get_service().write_some( + impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "write_some"); + return s; + } + + /// Write some data to the serial port. + /** + * This function is used to write data to the serial port. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the serial port. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return impl_.get_service().write_some( + impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous write. + /** + * This function is used to asynchronously write data to the serial port. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be written to the serial port. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The write operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * basic_serial_port.async_write_some( + * asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_write_some(this), handler, buffers); + } + + /// Read some data from the serial port. + /** + * This function is used to read data from the serial port. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * basic_serial_port.read_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = impl_.get_service().read_some( + impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "read_some"); + return s; + } + + /// Read some data from the serial port. + /** + * This function is used to read data from the serial port. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return impl_.get_service().read_some( + impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous read. + /** + * This function is used to asynchronously read data from the serial port. + * The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The read operation may not read all of the requested number of bytes. + * Consider using the @ref async_read function if you need to ensure that the + * requested amount of data is read before the asynchronous operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * basic_serial_port.async_read_some( + * asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_read_some(this), handler, buffers); + } + +private: + // Disallow copying and assignment. + basic_serial_port(const basic_serial_port&) ASIO_DELETED; + basic_serial_port& operator=(const basic_serial_port&) ASIO_DELETED; + + class initiate_async_write_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_write_some(basic_serial_port* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_write_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_serial_port* self_; + }; + + class initiate_async_read_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_read_some(basic_serial_port* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_read_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_serial_port* self_; + }; + +#if defined(ASIO_HAS_IOCP) + detail::io_object_impl impl_; +#else + detail::io_object_impl impl_; +#endif +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_BASIC_SERIAL_PORT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_signal_set.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_signal_set.hpp new file mode 100644 index 00000000..63515ae5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_signal_set.hpp @@ -0,0 +1,568 @@ +// +// basic_signal_set.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SIGNAL_SET_HPP +#define ASIO_BASIC_SIGNAL_SET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/signal_set_service.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" + +namespace asio { + +/// Provides signal functionality. +/** + * The basic_signal_set class provides the ability to perform an asynchronous + * wait for one or more signals to occur. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Example + * Performing an asynchronous wait: + * @code + * void handler( + * const asio::error_code& error, + * int signal_number) + * { + * if (!error) + * { + * // A signal occurred. + * } + * } + * + * ... + * + * // Construct a signal set registered for process termination. + * asio::signal_set signals(my_context, SIGINT, SIGTERM); + * + * // Start an asynchronous wait for one of the signals to occur. + * signals.async_wait(handler); + * @endcode + * + * @par Queueing of signal notifications + * + * If a signal is registered with a signal_set, and the signal occurs when + * there are no waiting handlers, then the signal notification is queued. The + * next async_wait operation on that signal_set will dequeue the notification. + * If multiple notifications are queued, subsequent async_wait operations + * dequeue them one at a time. Signal notifications are dequeued in order of + * ascending signal number. + * + * If a signal number is removed from a signal_set (using the @c remove or @c + * erase member functions) then any queued notifications for that signal are + * discarded. + * + * @par Multiple registration of signals + * + * The same signal number may be registered with different signal_set objects. + * When the signal occurs, one handler is called for each signal_set object. + * + * Note that multiple registration only works for signals that are registered + * using Asio. The application must not also register a signal handler using + * functions such as @c signal() or @c sigaction(). + * + * @par Signal masking on POSIX platforms + * + * POSIX allows signals to be blocked using functions such as @c sigprocmask() + * and @c pthread_sigmask(). For signals to be delivered, programs must ensure + * that any signals registered using signal_set objects are unblocked in at + * least one thread. + */ +template +class basic_signal_set +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the signal set type to another executor. + template + struct rebind_executor + { + /// The signal set type when rebound to the specified executor. + typedef basic_signal_set other; + }; + + /// Construct a signal set without adding any signals. + /** + * This constructor creates a signal set without registering for any signals. + * + * @param ex The I/O executor that the signal set will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * signal set. + */ + explicit basic_signal_set(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct a signal set without adding any signals. + /** + * This constructor creates a signal set without registering for any signals. + * + * @param context An execution context which provides the I/O executor that + * the signal set will use, by default, to dispatch handlers for any + * asynchronous operations performed on the signal set. + */ + template + explicit basic_signal_set(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Construct a signal set and add one signal. + /** + * This constructor creates a signal set and registers for one signal. + * + * @param ex The I/O executor that the signal set will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * signal set. + * + * @param signal_number_1 The signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(ex); + * signals.add(signal_number_1); @endcode + */ + basic_signal_set(const executor_type& ex, int signal_number_1) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Construct a signal set and add one signal. + /** + * This constructor creates a signal set and registers for one signal. + * + * @param context An execution context which provides the I/O executor that + * the signal set will use, by default, to dispatch handlers for any + * asynchronous operations performed on the signal set. + * + * @param signal_number_1 The signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(context); + * signals.add(signal_number_1); @endcode + */ + template + basic_signal_set(ExecutionContext& context, int signal_number_1, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Construct a signal set and add two signals. + /** + * This constructor creates a signal set and registers for two signals. + * + * @param ex The I/O executor that the signal set will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * signal set. + * + * @param signal_number_1 The first signal number to be added. + * + * @param signal_number_2 The second signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(ex); + * signals.add(signal_number_1); + * signals.add(signal_number_2); @endcode + */ + basic_signal_set(const executor_type& ex, int signal_number_1, + int signal_number_2) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Construct a signal set and add two signals. + /** + * This constructor creates a signal set and registers for two signals. + * + * @param context An execution context which provides the I/O executor that + * the signal set will use, by default, to dispatch handlers for any + * asynchronous operations performed on the signal set. + * + * @param signal_number_1 The first signal number to be added. + * + * @param signal_number_2 The second signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); @endcode + */ + template + basic_signal_set(ExecutionContext& context, int signal_number_1, + int signal_number_2, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Construct a signal set and add three signals. + /** + * This constructor creates a signal set and registers for three signals. + * + * @param ex The I/O executor that the signal set will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * signal set. + * + * @param signal_number_1 The first signal number to be added. + * + * @param signal_number_2 The second signal number to be added. + * + * @param signal_number_3 The third signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(ex); + * signals.add(signal_number_1); + * signals.add(signal_number_2); + * signals.add(signal_number_3); @endcode + */ + basic_signal_set(const executor_type& ex, int signal_number_1, + int signal_number_2, int signal_number_3) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Construct a signal set and add three signals. + /** + * This constructor creates a signal set and registers for three signals. + * + * @param context An execution context which provides the I/O executor that + * the signal set will use, by default, to dispatch handlers for any + * asynchronous operations performed on the signal set. + * + * @param signal_number_1 The first signal number to be added. + * + * @param signal_number_2 The second signal number to be added. + * + * @param signal_number_3 The third signal number to be added. + * + * @note This constructor is equivalent to performing: + * @code asio::signal_set signals(context); + * signals.add(signal_number_1); + * signals.add(signal_number_2); + * signals.add(signal_number_3); @endcode + */ + template + basic_signal_set(ExecutionContext& context, int signal_number_1, + int signal_number_2, int signal_number_3, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number_1, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_2, ec); + asio::detail::throw_error(ec, "add"); + impl_.get_service().add(impl_.get_implementation(), signal_number_3, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Destroys the signal set. + /** + * This function destroys the signal set, cancelling any outstanding + * asynchronous wait operations associated with the signal set as if by + * calling @c cancel. + */ + ~basic_signal_set() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Add a signal to a signal_set. + /** + * This function adds the specified signal to the set. It has no effect if the + * signal is already in the set. + * + * @param signal_number The signal to be added to the set. + * + * @throws asio::system_error Thrown on failure. + */ + void add(int signal_number) + { + asio::error_code ec; + impl_.get_service().add(impl_.get_implementation(), signal_number, ec); + asio::detail::throw_error(ec, "add"); + } + + /// Add a signal to a signal_set. + /** + * This function adds the specified signal to the set. It has no effect if the + * signal is already in the set. + * + * @param signal_number The signal to be added to the set. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID add(int signal_number, + asio::error_code& ec) + { + impl_.get_service().add(impl_.get_implementation(), signal_number, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Remove a signal from a signal_set. + /** + * This function removes the specified signal from the set. It has no effect + * if the signal is not in the set. + * + * @param signal_number The signal to be removed from the set. + * + * @throws asio::system_error Thrown on failure. + * + * @note Removes any notifications that have been queued for the specified + * signal number. + */ + void remove(int signal_number) + { + asio::error_code ec; + impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); + asio::detail::throw_error(ec, "remove"); + } + + /// Remove a signal from a signal_set. + /** + * This function removes the specified signal from the set. It has no effect + * if the signal is not in the set. + * + * @param signal_number The signal to be removed from the set. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Removes any notifications that have been queued for the specified + * signal number. + */ + ASIO_SYNC_OP_VOID remove(int signal_number, + asio::error_code& ec) + { + impl_.get_service().remove(impl_.get_implementation(), signal_number, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Remove all signals from a signal_set. + /** + * This function removes all signals from the set. It has no effect if the set + * is already empty. + * + * @throws asio::system_error Thrown on failure. + * + * @note Removes all queued notifications. + */ + void clear() + { + asio::error_code ec; + impl_.get_service().clear(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "clear"); + } + + /// Remove all signals from a signal_set. + /** + * This function removes all signals from the set. It has no effect if the set + * is already empty. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Removes all queued notifications. + */ + ASIO_SYNC_OP_VOID clear(asio::error_code& ec) + { + impl_.get_service().clear(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Cancel all operations associated with the signal set. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the signal set. The handler for each cancelled + * operation will be invoked with the asio::error::operation_aborted + * error code. + * + * Cancellation does not alter the set of registered signals. + * + * @throws asio::system_error Thrown on failure. + * + * @note If a registered signal occurred before cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all operations associated with the signal set. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the signal set. The handler for each cancelled + * operation will be invoked with the asio::error::operation_aborted + * error code. + * + * Cancellation does not alter the set of registered signals. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note If a registered signal occurred before cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous operation to wait for a signal to be delivered. + /** + * This function may be used to initiate an asynchronous wait against the + * signal set. It always returns immediately. + * + * For each call to async_wait(), the supplied handler will be called exactly + * once. The handler will be called when: + * + * @li One of the registered signals in the signal set occurs; or + * + * @li The signal set was cancelled, in which case the handler is passed the + * error code asio::error::operation_aborted. + * + * @param handler The handler to be called when the signal occurs. Copies + * will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * int signal_number // Indicates which signal occurred. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, int)) + SignalHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(SignalHandler, + void (asio::error_code, int)) + async_wait( + ASIO_MOVE_ARG(SignalHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler); + } + +private: + // Disallow copying and assignment. + basic_signal_set(const basic_signal_set&) ASIO_DELETED; + basic_signal_set& operator=(const basic_signal_set&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_signal_set* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(SignalHandler) handler) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a SignalHandler. + ASIO_SIGNAL_HANDLER_CHECK(SignalHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_signal_set* self_; + }; + + detail::io_object_impl impl_; +}; + +} // namespace asio + +#endif // ASIO_BASIC_SIGNAL_SET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket.hpp new file mode 100644 index 00000000..665ba29f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket.hpp @@ -0,0 +1,1894 @@ +// +// basic_socket.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SOCKET_HPP +#define ASIO_BASIC_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/post.hpp" +#include "asio/socket_base.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/null_socket_service.hpp" +#elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_socket_service.hpp" +#else +# include "asio/detail/reactive_socket_service.hpp" +#endif + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_SOCKET_FWD_DECL) +#define ASIO_BASIC_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_socket; + +#endif // !defined(ASIO_BASIC_SOCKET_FWD_DECL) + +/// Provides socket functionality. +/** + * The basic_socket class template provides functionality that is common to both + * stream-oriented and datagram-oriented sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_socket + : public socket_base +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the socket type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_socket other; + }; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#elif defined(ASIO_WINDOWS_RUNTIME) + typedef typename detail::null_socket_service< + Protocol>::native_handle_type native_handle_type; +#elif defined(ASIO_HAS_IOCP) + typedef typename detail::win_iocp_socket_service< + Protocol>::native_handle_type native_handle_type; +#else + typedef typename detail::reactive_socket_service< + Protocol>::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + +#if !defined(ASIO_NO_EXTENSIONS) + /// A basic_socket is always the lowest layer. + typedef basic_socket lowest_layer_type; +#endif // !defined(ASIO_NO_EXTENSIONS) + + /// Construct a basic_socket without opening it. + /** + * This constructor creates a socket without opening it. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_socket(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct a basic_socket without opening it. + /** + * This constructor creates a socket without opening it. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + */ + template + explicit basic_socket(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Construct and open a basic_socket. + /** + * This constructor creates and opens a socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_socket(const executor_type& ex, const protocol_type& protocol) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct and open a basic_socket. + /** + * This constructor creates and opens a socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_socket(ExecutionContext& context, const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct a basic_socket, opening it and binding it to the given local + /// endpoint. + /** + * This constructor creates a socket and automatically opens it bound to the + * specified endpoint on the local machine. The protocol used is the protocol + * associated with the given endpoint. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the socket will + * be bound. + * + * @throws asio::system_error Thrown on failure. + */ + basic_socket(const executor_type& ex, const endpoint_type& endpoint) + : impl_(ex) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + } + + /// Construct a basic_socket, opening it and binding it to the given local + /// endpoint. + /** + * This constructor creates a socket and automatically opens it bound to the + * specified endpoint on the local machine. The protocol used is the protocol + * associated with the given endpoint. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the socket will + * be bound. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_socket(ExecutionContext& context, const endpoint_type& endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + } + + /// Construct a basic_socket on an existing native socket. + /** + * This constructor creates a socket object to hold an existing native socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket A native socket. + * + * @throws asio::system_error Thrown on failure. + */ + basic_socket(const executor_type& ex, const protocol_type& protocol, + const native_handle_type& native_socket) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_socket, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct a basic_socket on an existing native socket. + /** + * This constructor creates a socket object to hold an existing native socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket A native socket. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_socket(ExecutionContext& context, const protocol_type& protocol, + const native_handle_type& native_socket, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_socket, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_socket from another. + /** + * This constructor moves a socket from one object to another. + * + * @param other The other basic_socket object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket(const executor_type&) constructor. + */ + basic_socket(basic_socket&& other) ASIO_NOEXCEPT + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_socket from another. + /** + * This assignment operator moves a socket from one object to another. + * + * @param other The other basic_socket object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket(const executor_type&) constructor. + */ + basic_socket& operator=(basic_socket&& other) + { + impl_ = std::move(other.impl_); + return *this; + } + + // All sockets have access to each other's implementations. + template + friend class basic_socket; + + /// Move-construct a basic_socket from a socket of another protocol type. + /** + * This constructor moves a socket from one object to another. + * + * @param other The other basic_socket object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket(const executor_type&) constructor. + */ + template + basic_socket(basic_socket&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_socket from a socket of another protocol type. + /** + * This assignment operator moves a socket from one object to another. + * + * @param other The other basic_socket object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket(const executor_type&) constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_socket& + >::type operator=(basic_socket && other) + { + basic_socket tmp(std::move(other)); + impl_ = std::move(tmp.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + +#if !defined(ASIO_NO_EXTENSIONS) + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since a basic_socket cannot contain any further layers, it simply + * returns a reference to itself. + * + * @return A reference to the lowest layer in the stack of layers. Ownership + * is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return *this; + } + + /// Get a const reference to the lowest layer. + /** + * This function returns a const reference to the lowest layer in a stack of + * layers. Since a basic_socket cannot contain any further layers, it simply + * returns a reference to itself. + * + * @return A const reference to the lowest layer in the stack of layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return *this; + } +#endif // !defined(ASIO_NO_EXTENSIONS) + + /// Open the socket using the specified protocol. + /** + * This function opens the socket so that it will use the specified protocol. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * socket.open(asio::ip::tcp::v4()); + * @endcode + */ + void open(const protocol_type& protocol = protocol_type()) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Open the socket using the specified protocol. + /** + * This function opens the socket so that it will use the specified protocol. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * asio::error_code ec; + * socket.open(asio::ip::tcp::v4(), ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID open(const protocol_type& protocol, + asio::error_code& ec) + { + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assign an existing native socket to the socket. + /* + * This function opens the socket to hold an existing native socket. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param native_socket A native socket. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const protocol_type& protocol, + const native_handle_type& native_socket) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_socket, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assign an existing native socket to the socket. + /* + * This function opens the socket to hold an existing native socket. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param native_socket A native socket. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, + const native_handle_type& native_socket, asio::error_code& ec) + { + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_socket, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Close the socket. + /** + * This function is used to close the socket. Any asynchronous send, receive + * or connect operations will be cancelled immediately, and will complete + * with the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. Note that, even if + * the function indicates an error, the underlying descriptor is closed. + * + * @note For portable behaviour with respect to graceful closure of a + * connected socket, call shutdown() before closing the socket. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the socket. + /** + * This function is used to close the socket. Any asynchronous send, receive + * or connect operations will be cancelled immediately, and will complete + * with the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. Note that, even if + * the function indicates an error, the underlying descriptor is closed. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::error_code ec; + * socket.close(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + * + * @note For portable behaviour with respect to graceful closure of a + * connected socket, call shutdown() before closing the socket. + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying native socket. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. Ownership + * of the native socket is then transferred to the caller. + * + * @throws asio::system_error Thrown on failure. + * + * @note This function is unsupported on Windows versions prior to Windows + * 8.1, and will fail with asio::error::operation_not_supported on + * these platforms. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) + __declspec(deprecated("This function always fails with " + "operation_not_supported when used on Windows versions " + "prior to Windows 8.1.")) +#endif + native_handle_type release() + { + asio::error_code ec; + native_handle_type s = impl_.get_service().release( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "release"); + return s; + } + + /// Release ownership of the underlying native socket. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. Ownership + * of the native socket is then transferred to the caller. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note This function is unsupported on Windows versions prior to Windows + * 8.1, and will fail with asio::error::operation_not_supported on + * these platforms. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) + __declspec(deprecated("This function always fails with " + "operation_not_supported when used on Windows versions " + "prior to Windows 8.1.")) +#endif + native_handle_type release(asio::error_code& ec) + { + return impl_.get_service().release(impl_.get_implementation(), ec); + } + + /// Get the native socket representation. + /** + * This function may be used to obtain the underlying representation of the + * socket. This is intended to allow access to native socket functionality + * that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the socket. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls to cancel() will always fail with + * asio::error::operation_not_supported when run on Windows XP, Windows + * Server 2003, and earlier versions of Windows, unless + * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has + * two issues that should be considered before enabling its use: + * + * @li It will only cancel asynchronous operations that were initiated in the + * current thread. + * + * @li It can appear to complete without error, but the request to cancel the + * unfinished operations may be silently ignored by the operating system. + * Whether it works or not seems to depend on the drivers that are installed. + * + * For portable cancellation, consider using one of the following + * alternatives: + * + * @li Disable asio's I/O completion port backend by defining + * ASIO_DISABLE_IOCP. + * + * @li Use the close() function to simultaneously cancel the outstanding + * operations and close the socket. + * + * When running on Windows Vista, Windows Server 2008, and later, the + * CancelIoEx function is always used. This function does not have the + * problems described above. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ + && !defined(ASIO_ENABLE_CANCELIO) + __declspec(deprecated("By default, this function always fails with " + "operation_not_supported when used on Windows XP, Windows Server 2003, " + "or earlier. Consult documentation for details.")) +#endif + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the socket. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls to cancel() will always fail with + * asio::error::operation_not_supported when run on Windows XP, Windows + * Server 2003, and earlier versions of Windows, unless + * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has + * two issues that should be considered before enabling its use: + * + * @li It will only cancel asynchronous operations that were initiated in the + * current thread. + * + * @li It can appear to complete without error, but the request to cancel the + * unfinished operations may be silently ignored by the operating system. + * Whether it works or not seems to depend on the drivers that are installed. + * + * For portable cancellation, consider using one of the following + * alternatives: + * + * @li Disable asio's I/O completion port backend by defining + * ASIO_DISABLE_IOCP. + * + * @li Use the close() function to simultaneously cancel the outstanding + * operations and close the socket. + * + * When running on Windows Vista, Windows Server 2008, and later, the + * CancelIoEx function is always used. This function does not have the + * problems described above. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ + && !defined(ASIO_ENABLE_CANCELIO) + __declspec(deprecated("By default, this function always fails with " + "operation_not_supported when used on Windows XP, Windows Server 2003, " + "or earlier. Consult documentation for details.")) +#endif + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the socket is at the out-of-band data mark. + /** + * This function is used to check whether the socket input is currently + * positioned at the out-of-band data mark. + * + * @return A bool indicating whether the socket is at the out-of-band data + * mark. + * + * @throws asio::system_error Thrown on failure. + */ + bool at_mark() const + { + asio::error_code ec; + bool b = impl_.get_service().at_mark(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "at_mark"); + return b; + } + + /// Determine whether the socket is at the out-of-band data mark. + /** + * This function is used to check whether the socket input is currently + * positioned at the out-of-band data mark. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return A bool indicating whether the socket is at the out-of-band data + * mark. + */ + bool at_mark(asio::error_code& ec) const + { + return impl_.get_service().at_mark(impl_.get_implementation(), ec); + } + + /// Determine the number of bytes available for reading. + /** + * This function is used to determine the number of bytes that may be read + * without blocking. + * + * @return The number of bytes that may be read without blocking, or 0 if an + * error occurs. + * + * @throws asio::system_error Thrown on failure. + */ + std::size_t available() const + { + asio::error_code ec; + std::size_t s = impl_.get_service().available( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "available"); + return s; + } + + /// Determine the number of bytes available for reading. + /** + * This function is used to determine the number of bytes that may be read + * without blocking. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of bytes that may be read without blocking, or 0 if an + * error occurs. + */ + std::size_t available(asio::error_code& ec) const + { + return impl_.get_service().available(impl_.get_implementation(), ec); + } + + /// Bind the socket to the given local endpoint. + /** + * This function binds the socket to the specified endpoint on the local + * machine. + * + * @param endpoint An endpoint on the local machine to which the socket will + * be bound. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * socket.open(asio::ip::tcp::v4()); + * socket.bind(asio::ip::tcp::endpoint( + * asio::ip::tcp::v4(), 12345)); + * @endcode + */ + void bind(const endpoint_type& endpoint) + { + asio::error_code ec; + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + } + + /// Bind the socket to the given local endpoint. + /** + * This function binds the socket to the specified endpoint on the local + * machine. + * + * @param endpoint An endpoint on the local machine to which the socket will + * be bound. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * socket.open(asio::ip::tcp::v4()); + * asio::error_code ec; + * socket.bind(asio::ip::tcp::endpoint( + * asio::ip::tcp::v4(), 12345), ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, + asio::error_code& ec) + { + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Connect the socket to the specified endpoint. + /** + * This function is used to connect a socket to the specified remote endpoint. + * The function call will block until the connection is successfully made or + * an error occurs. + * + * The socket is automatically opened if it is not already open. If the + * connect fails, and the socket was automatically opened, the socket is + * not returned to the closed state. + * + * @param peer_endpoint The remote endpoint to which the socket will be + * connected. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * asio::ip::tcp::endpoint endpoint( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.connect(endpoint); + * @endcode + */ + void connect(const endpoint_type& peer_endpoint) + { + asio::error_code ec; + if (!is_open()) + { + impl_.get_service().open(impl_.get_implementation(), + peer_endpoint.protocol(), ec); + asio::detail::throw_error(ec, "connect"); + } + impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); + asio::detail::throw_error(ec, "connect"); + } + + /// Connect the socket to the specified endpoint. + /** + * This function is used to connect a socket to the specified remote endpoint. + * The function call will block until the connection is successfully made or + * an error occurs. + * + * The socket is automatically opened if it is not already open. If the + * connect fails, and the socket was automatically opened, the socket is + * not returned to the closed state. + * + * @param peer_endpoint The remote endpoint to which the socket will be + * connected. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * asio::ip::tcp::endpoint endpoint( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * asio::error_code ec; + * socket.connect(endpoint, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID connect(const endpoint_type& peer_endpoint, + asio::error_code& ec) + { + if (!is_open()) + { + impl_.get_service().open(impl_.get_implementation(), + peer_endpoint.protocol(), ec); + if (ec) + { + ASIO_SYNC_OP_VOID_RETURN(ec); + } + } + + impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous connect. + /** + * This function is used to asynchronously connect a socket to the specified + * remote endpoint. The function call always returns immediately. + * + * The socket is automatically opened if it is not already open. If the + * connect fails, and the socket was automatically opened, the socket is + * not returned to the closed state. + * + * @param peer_endpoint The remote endpoint to which the socket will be + * connected. Copies will be made of the endpoint object as required. + * + * @param handler The handler to be called when the connection operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void connect_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Connect succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::socket socket(my_context); + * asio::ip::tcp::endpoint endpoint( + * asio::ip::address::from_string("1.2.3.4"), 12345); + * socket.async_connect(endpoint, connect_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + ConnectHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ConnectHandler, + void (asio::error_code)) + async_connect(const endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(ConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + asio::error_code open_ec; + if (!is_open()) + { + const protocol_type protocol = peer_endpoint.protocol(); + impl_.get_service().open(impl_.get_implementation(), protocol, open_ec); + } + + return async_initiate( + initiate_async_connect(this), handler, peer_endpoint, open_ec); + } + + /// Set an option on the socket. + /** + * This function is used to set an option on the socket. + * + * @param option The new option value to be set on the socket. + * + * @throws asio::system_error Thrown on failure. + * + * @sa SettableSocketOption @n + * asio::socket_base::broadcast @n + * asio::socket_base::do_not_route @n + * asio::socket_base::keep_alive @n + * asio::socket_base::linger @n + * asio::socket_base::receive_buffer_size @n + * asio::socket_base::receive_low_watermark @n + * asio::socket_base::reuse_address @n + * asio::socket_base::send_buffer_size @n + * asio::socket_base::send_low_watermark @n + * asio::ip::multicast::join_group @n + * asio::ip::multicast::leave_group @n + * asio::ip::multicast::enable_loopback @n + * asio::ip::multicast::outbound_interface @n + * asio::ip::multicast::hops @n + * asio::ip::tcp::no_delay + * + * @par Example + * Setting the IPPROTO_TCP/TCP_NODELAY option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::no_delay option(true); + * socket.set_option(option); + * @endcode + */ + template + void set_option(const SettableSocketOption& option) + { + asio::error_code ec; + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "set_option"); + } + + /// Set an option on the socket. + /** + * This function is used to set an option on the socket. + * + * @param option The new option value to be set on the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa SettableSocketOption @n + * asio::socket_base::broadcast @n + * asio::socket_base::do_not_route @n + * asio::socket_base::keep_alive @n + * asio::socket_base::linger @n + * asio::socket_base::receive_buffer_size @n + * asio::socket_base::receive_low_watermark @n + * asio::socket_base::reuse_address @n + * asio::socket_base::send_buffer_size @n + * asio::socket_base::send_low_watermark @n + * asio::ip::multicast::join_group @n + * asio::ip::multicast::leave_group @n + * asio::ip::multicast::enable_loopback @n + * asio::ip::multicast::outbound_interface @n + * asio::ip::multicast::hops @n + * asio::ip::tcp::no_delay + * + * @par Example + * Setting the IPPROTO_TCP/TCP_NODELAY option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::no_delay option(true); + * asio::error_code ec; + * socket.set_option(option, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, + asio::error_code& ec) + { + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get an option from the socket. + /** + * This function is used to get the current value of an option on the socket. + * + * @param option The option value to be obtained from the socket. + * + * @throws asio::system_error Thrown on failure. + * + * @sa GettableSocketOption @n + * asio::socket_base::broadcast @n + * asio::socket_base::do_not_route @n + * asio::socket_base::keep_alive @n + * asio::socket_base::linger @n + * asio::socket_base::receive_buffer_size @n + * asio::socket_base::receive_low_watermark @n + * asio::socket_base::reuse_address @n + * asio::socket_base::send_buffer_size @n + * asio::socket_base::send_low_watermark @n + * asio::ip::multicast::join_group @n + * asio::ip::multicast::leave_group @n + * asio::ip::multicast::enable_loopback @n + * asio::ip::multicast::outbound_interface @n + * asio::ip::multicast::hops @n + * asio::ip::tcp::no_delay + * + * @par Example + * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::socket::keep_alive option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + */ + template + void get_option(GettableSocketOption& option) const + { + asio::error_code ec; + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "get_option"); + } + + /// Get an option from the socket. + /** + * This function is used to get the current value of an option on the socket. + * + * @param option The option value to be obtained from the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa GettableSocketOption @n + * asio::socket_base::broadcast @n + * asio::socket_base::do_not_route @n + * asio::socket_base::keep_alive @n + * asio::socket_base::linger @n + * asio::socket_base::receive_buffer_size @n + * asio::socket_base::receive_low_watermark @n + * asio::socket_base::reuse_address @n + * asio::socket_base::send_buffer_size @n + * asio::socket_base::send_low_watermark @n + * asio::ip::multicast::join_group @n + * asio::ip::multicast::leave_group @n + * asio::ip::multicast::enable_loopback @n + * asio::ip::multicast::outbound_interface @n + * asio::ip::multicast::hops @n + * asio::ip::tcp::no_delay + * + * @par Example + * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::socket::keep_alive option; + * asio::error_code ec; + * socket.get_option(option, ec); + * if (ec) + * { + * // An error occurred. + * } + * bool is_set = option.value(); + * @endcode + */ + template + ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, + asio::error_code& ec) const + { + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the socket. + /** + * This function is used to execute an IO control command on the socket. + * + * @param command The IO control command to be performed on the socket. + * + * @throws asio::system_error Thrown on failure. + * + * @sa IoControlCommand @n + * asio::socket_base::bytes_readable @n + * asio::socket_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::socket::bytes_readable command; + * socket.io_control(command); + * std::size_t bytes_readable = command.get(); + * @endcode + */ + template + void io_control(IoControlCommand& command) + { + asio::error_code ec; + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + asio::detail::throw_error(ec, "io_control"); + } + + /// Perform an IO control command on the socket. + /** + * This function is used to execute an IO control command on the socket. + * + * @param command The IO control command to be performed on the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa IoControlCommand @n + * asio::socket_base::bytes_readable @n + * asio::socket_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::socket::bytes_readable command; + * asio::error_code ec; + * socket.io_control(command, ec); + * if (ec) + * { + * // An error occurred. + * } + * std::size_t bytes_readable = command.get(); + * @endcode + */ + template + ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, + asio::error_code& ec) + { + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the socket. + /** + * @returns @c true if the socket's synchronous operations will fail with + * asio::error::would_block if they are unable to perform the requested + * operation immediately. If @c false, synchronous operations will block + * until complete. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + bool non_blocking() const + { + return impl_.get_service().non_blocking(impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the socket. + /** + * @param mode If @c true, the socket's synchronous operations will fail with + * asio::error::would_block if they are unable to perform the requested + * operation immediately. If @c false, synchronous operations will block + * until complete. + * + * @throws asio::system_error Thrown on failure. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + void non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "non_blocking"); + } + + /// Sets the non-blocking mode of the socket. + /** + * @param mode If @c true, the socket's synchronous operations will fail with + * asio::error::would_block if they are unable to perform the requested + * operation immediately. If @c false, synchronous operations will block + * until complete. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + ASIO_SYNC_OP_VOID non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native socket implementation. + /** + * This function is used to retrieve the non-blocking mode of the underlying + * native socket. This mode has no effect on the behaviour of the socket + * object's synchronous operations. + * + * @returns @c true if the underlying socket is in non-blocking mode and + * direct system calls may fail with asio::error::would_block (or the + * equivalent system error). + * + * @note The current non-blocking mode is cached by the socket object. + * Consequently, the return value may be incorrect if the non-blocking mode + * was set directly on the native socket. + * + * @par Example + * This function is intended to allow the encapsulation of arbitrary + * non-blocking system calls as asynchronous operations, in a way that is + * transparent to the user of the socket object. The following example + * illustrates how Linux's @c sendfile system call might be encapsulated: + * @code template + * struct sendfile_op + * { + * tcp::socket& sock_; + * int fd_; + * Handler handler_; + * off_t offset_; + * std::size_t total_bytes_transferred_; + * + * // Function call operator meeting WriteHandler requirements. + * // Used as the handler for the async_write_some operation. + * void operator()(asio::error_code ec, std::size_t) + * { + * // Put the underlying socket into non-blocking mode. + * if (!ec) + * if (!sock_.native_non_blocking()) + * sock_.native_non_blocking(true, ec); + * + * if (!ec) + * { + * for (;;) + * { + * // Try the system call. + * errno = 0; + * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); + * ec = asio::error_code(n < 0 ? errno : 0, + * asio::error::get_system_category()); + * total_bytes_transferred_ += ec ? 0 : n; + * + * // Retry operation immediately if interrupted by signal. + * if (ec == asio::error::interrupted) + * continue; + * + * // Check if we need to run the operation again. + * if (ec == asio::error::would_block + * || ec == asio::error::try_again) + * { + * // We have to wait for the socket to become ready again. + * sock_.async_wait(tcp::socket::wait_write, *this); + * return; + * } + * + * if (ec || n == 0) + * { + * // An error occurred, or we have reached the end of the file. + * // Either way we must exit the loop so we can call the handler. + * break; + * } + * + * // Loop around to try calling sendfile again. + * } + * } + * + * // Pass result back to user's handler. + * handler_(ec, total_bytes_transferred_); + * } + * }; + * + * template + * void async_sendfile(tcp::socket& sock, int fd, Handler h) + * { + * sendfile_op op = { sock, fd, h, 0, 0 }; + * sock.async_wait(tcp::socket::wait_write, op); + * } @endcode + */ + bool native_non_blocking() const + { + return impl_.get_service().native_non_blocking(impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the native socket implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native socket. It has no effect on the behaviour of the socket object's + * synchronous operations. + * + * @param mode If @c true, the underlying socket is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @throws asio::system_error Thrown on failure. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + * + * @par Example + * This function is intended to allow the encapsulation of arbitrary + * non-blocking system calls as asynchronous operations, in a way that is + * transparent to the user of the socket object. The following example + * illustrates how Linux's @c sendfile system call might be encapsulated: + * @code template + * struct sendfile_op + * { + * tcp::socket& sock_; + * int fd_; + * Handler handler_; + * off_t offset_; + * std::size_t total_bytes_transferred_; + * + * // Function call operator meeting WriteHandler requirements. + * // Used as the handler for the async_write_some operation. + * void operator()(asio::error_code ec, std::size_t) + * { + * // Put the underlying socket into non-blocking mode. + * if (!ec) + * if (!sock_.native_non_blocking()) + * sock_.native_non_blocking(true, ec); + * + * if (!ec) + * { + * for (;;) + * { + * // Try the system call. + * errno = 0; + * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); + * ec = asio::error_code(n < 0 ? errno : 0, + * asio::error::get_system_category()); + * total_bytes_transferred_ += ec ? 0 : n; + * + * // Retry operation immediately if interrupted by signal. + * if (ec == asio::error::interrupted) + * continue; + * + * // Check if we need to run the operation again. + * if (ec == asio::error::would_block + * || ec == asio::error::try_again) + * { + * // We have to wait for the socket to become ready again. + * sock_.async_wait(tcp::socket::wait_write, *this); + * return; + * } + * + * if (ec || n == 0) + * { + * // An error occurred, or we have reached the end of the file. + * // Either way we must exit the loop so we can call the handler. + * break; + * } + * + * // Loop around to try calling sendfile again. + * } + * } + * + * // Pass result back to user's handler. + * handler_(ec, total_bytes_transferred_); + * } + * }; + * + * template + * void async_sendfile(tcp::socket& sock, int fd, Handler h) + * { + * sendfile_op op = { sock, fd, h, 0, 0 }; + * sock.async_wait(tcp::socket::wait_write, op); + * } @endcode + */ + void native_non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "native_non_blocking"); + } + + /// Sets the non-blocking mode of the native socket implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native socket. It has no effect on the behaviour of the socket object's + * synchronous operations. + * + * @param mode If @c true, the underlying socket is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @param ec Set to indicate what error occurred, if any. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + * + * @par Example + * This function is intended to allow the encapsulation of arbitrary + * non-blocking system calls as asynchronous operations, in a way that is + * transparent to the user of the socket object. The following example + * illustrates how Linux's @c sendfile system call might be encapsulated: + * @code template + * struct sendfile_op + * { + * tcp::socket& sock_; + * int fd_; + * Handler handler_; + * off_t offset_; + * std::size_t total_bytes_transferred_; + * + * // Function call operator meeting WriteHandler requirements. + * // Used as the handler for the async_write_some operation. + * void operator()(asio::error_code ec, std::size_t) + * { + * // Put the underlying socket into non-blocking mode. + * if (!ec) + * if (!sock_.native_non_blocking()) + * sock_.native_non_blocking(true, ec); + * + * if (!ec) + * { + * for (;;) + * { + * // Try the system call. + * errno = 0; + * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); + * ec = asio::error_code(n < 0 ? errno : 0, + * asio::error::get_system_category()); + * total_bytes_transferred_ += ec ? 0 : n; + * + * // Retry operation immediately if interrupted by signal. + * if (ec == asio::error::interrupted) + * continue; + * + * // Check if we need to run the operation again. + * if (ec == asio::error::would_block + * || ec == asio::error::try_again) + * { + * // We have to wait for the socket to become ready again. + * sock_.async_wait(tcp::socket::wait_write, *this); + * return; + * } + * + * if (ec || n == 0) + * { + * // An error occurred, or we have reached the end of the file. + * // Either way we must exit the loop so we can call the handler. + * break; + * } + * + * // Loop around to try calling sendfile again. + * } + * } + * + * // Pass result back to user's handler. + * handler_(ec, total_bytes_transferred_); + * } + * }; + * + * template + * void async_sendfile(tcp::socket& sock, int fd, Handler h) + * { + * sendfile_op op = { sock, fd, h, 0, 0 }; + * sock.async_wait(tcp::socket::wait_write, op); + * } @endcode + */ + ASIO_SYNC_OP_VOID native_non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint of the socket. + /** + * This function is used to obtain the locally bound endpoint of the socket. + * + * @returns An object that represents the local endpoint of the socket. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); + * @endcode + */ + endpoint_type local_endpoint() const + { + asio::error_code ec; + endpoint_type ep = impl_.get_service().local_endpoint( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "local_endpoint"); + return ep; + } + + /// Get the local endpoint of the socket. + /** + * This function is used to obtain the locally bound endpoint of the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns An object that represents the local endpoint of the socket. + * Returns a default-constructed endpoint object if an error occurred. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::error_code ec; + * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + endpoint_type local_endpoint(asio::error_code& ec) const + { + return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); + } + + /// Get the remote endpoint of the socket. + /** + * This function is used to obtain the remote endpoint of the socket. + * + * @returns An object that represents the remote endpoint of the socket. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); + * @endcode + */ + endpoint_type remote_endpoint() const + { + asio::error_code ec; + endpoint_type ep = impl_.get_service().remote_endpoint( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "remote_endpoint"); + return ep; + } + + /// Get the remote endpoint of the socket. + /** + * This function is used to obtain the remote endpoint of the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns An object that represents the remote endpoint of the socket. + * Returns a default-constructed endpoint object if an error occurred. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::error_code ec; + * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + endpoint_type remote_endpoint(asio::error_code& ec) const + { + return impl_.get_service().remote_endpoint(impl_.get_implementation(), ec); + } + + /// Disable sends or receives on the socket. + /** + * This function is used to disable send operations, receive operations, or + * both. + * + * @param what Determines what types of operation will no longer be allowed. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * Shutting down the send side of the socket: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * socket.shutdown(asio::ip::tcp::socket::shutdown_send); + * @endcode + */ + void shutdown(shutdown_type what) + { + asio::error_code ec; + impl_.get_service().shutdown(impl_.get_implementation(), what, ec); + asio::detail::throw_error(ec, "shutdown"); + } + + /// Disable sends or receives on the socket. + /** + * This function is used to disable send operations, receive operations, or + * both. + * + * @param what Determines what types of operation will no longer be allowed. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * Shutting down the send side of the socket: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::error_code ec; + * socket.shutdown(asio::ip::tcp::socket::shutdown_send, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID shutdown(shutdown_type what, + asio::error_code& ec) + { + impl_.get_service().shutdown(impl_.get_implementation(), what, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Wait for the socket to become ready to read, ready to write, or to have + /// pending error conditions. + /** + * This function is used to perform a blocking wait for a socket to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired socket state. + * + * @par Example + * Waiting for a socket to become readable. + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * socket.wait(asio::ip::tcp::socket::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), w, ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Wait for the socket to become ready to read, ready to write, or to have + /// pending error conditions. + /** + * This function is used to perform a blocking wait for a socket to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired socket state. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * Waiting for a socket to become readable. + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::error_code ec; + * socket.wait(asio::ip::tcp::socket::wait_read, ec); + * @endcode + */ + ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), w, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Asynchronously wait for the socket to become ready to read, ready to + /// write, or to have pending error conditions. + /** + * This function is used to perform an asynchronous wait for a socket to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired socket state. + * + * @param handler The handler to be called when the wait operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::socket socket(my_context); + * ... + * socket.async_wait(asio::ip::tcp::socket::wait_read, wait_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler, w); + } + +protected: + /// Protected destructor to prevent deletion through this type. + /** + * This function destroys the socket, cancelling any outstanding asynchronous + * operations associated with the socket as if by calling @c cancel. + */ + ~basic_socket() + { + } + +#if defined(ASIO_WINDOWS_RUNTIME) + detail::io_object_impl< + detail::null_socket_service, Executor> impl_; +#elif defined(ASIO_HAS_IOCP) + detail::io_object_impl< + detail::win_iocp_socket_service, Executor> impl_; +#else + detail::io_object_impl< + detail::reactive_socket_service, Executor> impl_; +#endif + +private: + // Disallow copying and assignment. + basic_socket(const basic_socket&) ASIO_DELETED; + basic_socket& operator=(const basic_socket&) ASIO_DELETED; + + class initiate_async_connect + { + public: + typedef Executor executor_type; + + explicit initiate_async_connect(basic_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ConnectHandler) handler, + const endpoint_type& peer_endpoint, + const asio::error_code& open_ec) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ConnectHandler. + ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check; + + if (open_ec) + { + asio::post(self_->impl_.get_executor(), + asio::detail::bind_handler( + ASIO_MOVE_CAST(ConnectHandler)(handler), open_ec)); + } + else + { + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_connect( + self_->impl_.get_implementation(), peer_endpoint, + handler2.value, self_->impl_.get_implementation_executor()); + } + } + + private: + basic_socket* self_; + }; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler, wait_type w) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), w, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_socket* self_; + }; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_acceptor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_acceptor.hpp new file mode 100644 index 00000000..06af2619 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_acceptor.hpp @@ -0,0 +1,2495 @@ +// +// basic_socket_acceptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SOCKET_ACCEPTOR_HPP +#define ASIO_BASIC_SOCKET_ACCEPTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/socket_base.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/null_socket_service.hpp" +#elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_socket_service.hpp" +#else +# include "asio/detail/reactive_socket_service.hpp" +#endif + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) +#define ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_socket_acceptor; + +#endif // !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) + +/// Provides the ability to accept new connections. +/** + * The basic_socket_acceptor class template is used for accepting new socket + * connections. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Example + * Opening a socket acceptor with the SO_REUSEADDR option enabled: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); + * acceptor.open(endpoint.protocol()); + * acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true)); + * acceptor.bind(endpoint); + * acceptor.listen(); + * @endcode + */ +template +class basic_socket_acceptor + : public socket_base +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the acceptor type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_socket_acceptor other; + }; + + /// The native representation of an acceptor. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#elif defined(ASIO_WINDOWS_RUNTIME) + typedef typename detail::null_socket_service< + Protocol>::native_handle_type native_handle_type; +#elif defined(ASIO_HAS_IOCP) + typedef typename detail::win_iocp_socket_service< + Protocol>::native_handle_type native_handle_type; +#else + typedef typename detail::reactive_socket_service< + Protocol>::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// Construct an acceptor without opening it. + /** + * This constructor creates an acceptor without opening it to listen for new + * connections. The open() function must be called before the acceptor can + * accept new socket connections. + * + * @param ex The I/O executor that the acceptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * acceptor. + */ + explicit basic_socket_acceptor(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct an acceptor without opening it. + /** + * This constructor creates an acceptor without opening it to listen for new + * connections. The open() function must be called before the acceptor can + * accept new socket connections. + * + * @param context An execution context which provides the I/O executor that + * the acceptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the acceptor. + */ + template + explicit basic_socket_acceptor(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Construct an open acceptor. + /** + * This constructor creates an acceptor and automatically opens it. + * + * @param ex The I/O executor that the acceptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * acceptor. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_socket_acceptor(const executor_type& ex, const protocol_type& protocol) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct an open acceptor. + /** + * This constructor creates an acceptor and automatically opens it. + * + * @param context An execution context which provides the I/O executor that + * the acceptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the acceptor. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_socket_acceptor(ExecutionContext& context, + const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Construct an acceptor opened on the given endpoint. + /** + * This constructor creates an acceptor and automatically opens it to listen + * for new connections on the specified endpoint. + * + * @param ex The I/O executor that the acceptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * acceptor. + * + * @param endpoint An endpoint on the local machine on which the acceptor + * will listen for new connections. + * + * @param reuse_addr Whether the constructor should set the socket option + * socket_base::reuse_address. + * + * @throws asio::system_error Thrown on failure. + * + * @note This constructor is equivalent to the following code: + * @code + * basic_socket_acceptor acceptor(my_context); + * acceptor.open(endpoint.protocol()); + * if (reuse_addr) + * acceptor.set_option(socket_base::reuse_address(true)); + * acceptor.bind(endpoint); + * acceptor.listen(); + * @endcode + */ + basic_socket_acceptor(const executor_type& ex, + const endpoint_type& endpoint, bool reuse_addr = true) + : impl_(ex) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + if (reuse_addr) + { + impl_.get_service().set_option(impl_.get_implementation(), + socket_base::reuse_address(true), ec); + asio::detail::throw_error(ec, "set_option"); + } + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + impl_.get_service().listen(impl_.get_implementation(), + socket_base::max_listen_connections, ec); + asio::detail::throw_error(ec, "listen"); + } + + /// Construct an acceptor opened on the given endpoint. + /** + * This constructor creates an acceptor and automatically opens it to listen + * for new connections on the specified endpoint. + * + * @param context An execution context which provides the I/O executor that + * the acceptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the acceptor. + * + * @param endpoint An endpoint on the local machine on which the acceptor + * will listen for new connections. + * + * @param reuse_addr Whether the constructor should set the socket option + * socket_base::reuse_address. + * + * @throws asio::system_error Thrown on failure. + * + * @note This constructor is equivalent to the following code: + * @code + * basic_socket_acceptor acceptor(my_context); + * acceptor.open(endpoint.protocol()); + * if (reuse_addr) + * acceptor.set_option(socket_base::reuse_address(true)); + * acceptor.bind(endpoint); + * acceptor.listen(); + * @endcode + */ + template + basic_socket_acceptor(ExecutionContext& context, + const endpoint_type& endpoint, bool reuse_addr = true, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + const protocol_type protocol = endpoint.protocol(); + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + if (reuse_addr) + { + impl_.get_service().set_option(impl_.get_implementation(), + socket_base::reuse_address(true), ec); + asio::detail::throw_error(ec, "set_option"); + } + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + impl_.get_service().listen(impl_.get_implementation(), + socket_base::max_listen_connections, ec); + asio::detail::throw_error(ec, "listen"); + } + + /// Construct a basic_socket_acceptor on an existing native acceptor. + /** + * This constructor creates an acceptor object to hold an existing native + * acceptor. + * + * @param ex The I/O executor that the acceptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * acceptor. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_acceptor A native acceptor. + * + * @throws asio::system_error Thrown on failure. + */ + basic_socket_acceptor(const executor_type& ex, + const protocol_type& protocol, const native_handle_type& native_acceptor) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_acceptor, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct a basic_socket_acceptor on an existing native acceptor. + /** + * This constructor creates an acceptor object to hold an existing native + * acceptor. + * + * @param context An execution context which provides the I/O executor that + * the acceptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the acceptor. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_acceptor A native acceptor. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_socket_acceptor(ExecutionContext& context, + const protocol_type& protocol, const native_handle_type& native_acceptor, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_acceptor, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_socket_acceptor from another. + /** + * This constructor moves an acceptor from one object to another. + * + * @param other The other basic_socket_acceptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket_acceptor(const executor_type&) + * constructor. + */ + basic_socket_acceptor(basic_socket_acceptor&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_socket_acceptor from another. + /** + * This assignment operator moves an acceptor from one object to another. + * + * @param other The other basic_socket_acceptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket_acceptor(const executor_type&) + * constructor. + */ + basic_socket_acceptor& operator=(basic_socket_acceptor&& other) + { + impl_ = std::move(other.impl_); + return *this; + } + + // All socket acceptors have access to each other's implementations. + template + friend class basic_socket_acceptor; + + /// Move-construct a basic_socket_acceptor from an acceptor of another + /// protocol type. + /** + * This constructor moves an acceptor from one object to another. + * + * @param other The other basic_socket_acceptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket_acceptor(const executor_type&) + * constructor. + */ + template + basic_socket_acceptor(basic_socket_acceptor&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_socket_acceptor from an acceptor of another protocol + /// type. + /** + * This assignment operator moves an acceptor from one object to another. + * + * @param other The other basic_socket_acceptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_socket_acceptor(const executor_type&) + * constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_socket_acceptor& + >::type operator=(basic_socket_acceptor&& other) + { + basic_socket_acceptor tmp(std::move(other)); + impl_ = std::move(tmp.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the acceptor. + /** + * This function destroys the acceptor, cancelling any outstanding + * asynchronous operations associated with the acceptor as if by calling + * @c cancel. + */ + ~basic_socket_acceptor() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Open the acceptor using the specified protocol. + /** + * This function opens the socket acceptor so that it will use the specified + * protocol. + * + * @param protocol An object specifying which protocol is to be used. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * acceptor.open(asio::ip::tcp::v4()); + * @endcode + */ + void open(const protocol_type& protocol = protocol_type()) + { + asio::error_code ec; + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + asio::detail::throw_error(ec, "open"); + } + + /// Open the acceptor using the specified protocol. + /** + * This function opens the socket acceptor so that it will use the specified + * protocol. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * asio::error_code ec; + * acceptor.open(asio::ip::tcp::v4(), ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID open(const protocol_type& protocol, + asio::error_code& ec) + { + impl_.get_service().open(impl_.get_implementation(), protocol, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Assigns an existing native acceptor to the acceptor. + /* + * This function opens the acceptor to hold an existing native acceptor. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param native_acceptor A native acceptor. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const protocol_type& protocol, + const native_handle_type& native_acceptor) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_acceptor, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assigns an existing native acceptor to the acceptor. + /* + * This function opens the acceptor to hold an existing native acceptor. + * + * @param protocol An object specifying which protocol is to be used. + * + * @param native_acceptor A native acceptor. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, + const native_handle_type& native_acceptor, asio::error_code& ec) + { + impl_.get_service().assign(impl_.get_implementation(), + protocol, native_acceptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the acceptor is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Bind the acceptor to the given local endpoint. + /** + * This function binds the socket acceptor to the specified endpoint on the + * local machine. + * + * @param endpoint An endpoint on the local machine to which the socket + * acceptor will be bound. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), 12345); + * acceptor.open(endpoint.protocol()); + * acceptor.bind(endpoint); + * @endcode + */ + void bind(const endpoint_type& endpoint) + { + asio::error_code ec; + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + asio::detail::throw_error(ec, "bind"); + } + + /// Bind the acceptor to the given local endpoint. + /** + * This function binds the socket acceptor to the specified endpoint on the + * local machine. + * + * @param endpoint An endpoint on the local machine to which the socket + * acceptor will be bound. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), 12345); + * acceptor.open(endpoint.protocol()); + * asio::error_code ec; + * acceptor.bind(endpoint, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, + asio::error_code& ec) + { + impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Place the acceptor into the state where it will listen for new + /// connections. + /** + * This function puts the socket acceptor into the state where it may accept + * new connections. + * + * @param backlog The maximum length of the queue of pending connections. + * + * @throws asio::system_error Thrown on failure. + */ + void listen(int backlog = socket_base::max_listen_connections) + { + asio::error_code ec; + impl_.get_service().listen(impl_.get_implementation(), backlog, ec); + asio::detail::throw_error(ec, "listen"); + } + + /// Place the acceptor into the state where it will listen for new + /// connections. + /** + * This function puts the socket acceptor into the state where it may accept + * new connections. + * + * @param backlog The maximum length of the queue of pending connections. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::error_code ec; + * acceptor.listen(asio::socket_base::max_listen_connections, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID listen(int backlog, asio::error_code& ec) + { + impl_.get_service().listen(impl_.get_implementation(), backlog, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Close the acceptor. + /** + * This function is used to close the acceptor. Any asynchronous accept + * operations will be cancelled immediately. + * + * A subsequent call to open() is required before the acceptor can again be + * used to again perform socket accept operations. + * + * @throws asio::system_error Thrown on failure. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the acceptor. + /** + * This function is used to close the acceptor. Any asynchronous accept + * operations will be cancelled immediately. + * + * A subsequent call to open() is required before the acceptor can again be + * used to again perform socket accept operations. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::error_code ec; + * acceptor.close(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Release ownership of the underlying native acceptor. + /** + * This function causes all outstanding asynchronous accept operations to + * finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. Ownership of the + * native acceptor is then transferred to the caller. + * + * @throws asio::system_error Thrown on failure. + * + * @note This function is unsupported on Windows versions prior to Windows + * 8.1, and will fail with asio::error::operation_not_supported on + * these platforms. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) + __declspec(deprecated("This function always fails with " + "operation_not_supported when used on Windows versions " + "prior to Windows 8.1.")) +#endif + native_handle_type release() + { + asio::error_code ec; + native_handle_type s = impl_.get_service().release( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "release"); + return s; + } + + /// Release ownership of the underlying native acceptor. + /** + * This function causes all outstanding asynchronous accept operations to + * finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. Ownership of the + * native acceptor is then transferred to the caller. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note This function is unsupported on Windows versions prior to Windows + * 8.1, and will fail with asio::error::operation_not_supported on + * these platforms. + */ +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ + && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) + __declspec(deprecated("This function always fails with " + "operation_not_supported when used on Windows versions " + "prior to Windows 8.1.")) +#endif + native_handle_type release(asio::error_code& ec) + { + return impl_.get_service().release(impl_.get_implementation(), ec); + } + + /// Get the native acceptor representation. + /** + * This function may be used to obtain the underlying representation of the + * acceptor. This is intended to allow access to native acceptor functionality + * that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the acceptor. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the acceptor. + /** + * This function causes all outstanding asynchronous connect, send and receive + * operations to finish immediately, and the handlers for cancelled operations + * will be passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Set an option on the acceptor. + /** + * This function is used to set an option on the acceptor. + * + * @param option The new option value to be set on the acceptor. + * + * @throws asio::system_error Thrown on failure. + * + * @sa SettableSocketOption @n + * asio::socket_base::reuse_address + * asio::socket_base::enable_connection_aborted + * + * @par Example + * Setting the SOL_SOCKET/SO_REUSEADDR option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::reuse_address option(true); + * acceptor.set_option(option); + * @endcode + */ + template + void set_option(const SettableSocketOption& option) + { + asio::error_code ec; + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "set_option"); + } + + /// Set an option on the acceptor. + /** + * This function is used to set an option on the acceptor. + * + * @param option The new option value to be set on the acceptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa SettableSocketOption @n + * asio::socket_base::reuse_address + * asio::socket_base::enable_connection_aborted + * + * @par Example + * Setting the SOL_SOCKET/SO_REUSEADDR option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::reuse_address option(true); + * asio::error_code ec; + * acceptor.set_option(option, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, + asio::error_code& ec) + { + impl_.get_service().set_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get an option from the acceptor. + /** + * This function is used to get the current value of an option on the + * acceptor. + * + * @param option The option value to be obtained from the acceptor. + * + * @throws asio::system_error Thrown on failure. + * + * @sa GettableSocketOption @n + * asio::socket_base::reuse_address + * + * @par Example + * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::reuse_address option; + * acceptor.get_option(option); + * bool is_set = option.get(); + * @endcode + */ + template + void get_option(GettableSocketOption& option) const + { + asio::error_code ec; + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + asio::detail::throw_error(ec, "get_option"); + } + + /// Get an option from the acceptor. + /** + * This function is used to get the current value of an option on the + * acceptor. + * + * @param option The option value to be obtained from the acceptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa GettableSocketOption @n + * asio::socket_base::reuse_address + * + * @par Example + * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::reuse_address option; + * asio::error_code ec; + * acceptor.get_option(option, ec); + * if (ec) + * { + * // An error occurred. + * } + * bool is_set = option.get(); + * @endcode + */ + template + ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, + asio::error_code& ec) const + { + impl_.get_service().get_option(impl_.get_implementation(), option, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the acceptor. + /** + * This function is used to execute an IO control command on the acceptor. + * + * @param command The IO control command to be performed on the acceptor. + * + * @throws asio::system_error Thrown on failure. + * + * @sa IoControlCommand @n + * asio::socket_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::non_blocking_io command(true); + * socket.io_control(command); + * @endcode + */ + template + void io_control(IoControlCommand& command) + { + asio::error_code ec; + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + asio::detail::throw_error(ec, "io_control"); + } + + /// Perform an IO control command on the acceptor. + /** + * This function is used to execute an IO control command on the acceptor. + * + * @param command The IO control command to be performed on the acceptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa IoControlCommand @n + * asio::socket_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::acceptor::non_blocking_io command(true); + * asio::error_code ec; + * socket.io_control(command, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, + asio::error_code& ec) + { + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the acceptor. + /** + * @returns @c true if the acceptor's synchronous operations will fail with + * asio::error::would_block if they are unable to perform the requested + * operation immediately. If @c false, synchronous operations will block + * until complete. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + bool non_blocking() const + { + return impl_.get_service().non_blocking(impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the acceptor. + /** + * @param mode If @c true, the acceptor's synchronous operations will fail + * with asio::error::would_block if they are unable to perform the + * requested operation immediately. If @c false, synchronous operations will + * block until complete. + * + * @throws asio::system_error Thrown on failure. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + void non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "non_blocking"); + } + + /// Sets the non-blocking mode of the acceptor. + /** + * @param mode If @c true, the acceptor's synchronous operations will fail + * with asio::error::would_block if they are unable to perform the + * requested operation immediately. If @c false, synchronous operations will + * block until complete. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + ASIO_SYNC_OP_VOID non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native acceptor implementation. + /** + * This function is used to retrieve the non-blocking mode of the underlying + * native acceptor. This mode has no effect on the behaviour of the acceptor + * object's synchronous operations. + * + * @returns @c true if the underlying acceptor is in non-blocking mode and + * direct system calls may fail with asio::error::would_block (or the + * equivalent system error). + * + * @note The current non-blocking mode is cached by the acceptor object. + * Consequently, the return value may be incorrect if the non-blocking mode + * was set directly on the native acceptor. + */ + bool native_non_blocking() const + { + return impl_.get_service().native_non_blocking(impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the native acceptor implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native acceptor. It has no effect on the behaviour of the acceptor object's + * synchronous operations. + * + * @param mode If @c true, the underlying acceptor is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @throws asio::system_error Thrown on failure. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + */ + void native_non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "native_non_blocking"); + } + + /// Sets the non-blocking mode of the native acceptor implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native acceptor. It has no effect on the behaviour of the acceptor object's + * synchronous operations. + * + * @param mode If @c true, the underlying acceptor is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @param ec Set to indicate what error occurred, if any. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + */ + ASIO_SYNC_OP_VOID native_non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the local endpoint of the acceptor. + /** + * This function is used to obtain the locally bound endpoint of the acceptor. + * + * @returns An object that represents the local endpoint of the acceptor. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(); + * @endcode + */ + endpoint_type local_endpoint() const + { + asio::error_code ec; + endpoint_type ep = impl_.get_service().local_endpoint( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "local_endpoint"); + return ep; + } + + /// Get the local endpoint of the acceptor. + /** + * This function is used to obtain the locally bound endpoint of the acceptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns An object that represents the local endpoint of the acceptor. + * Returns a default-constructed endpoint object if an error occurred and the + * error handler did not throw an exception. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::error_code ec; + * asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + endpoint_type local_endpoint(asio::error_code& ec) const + { + return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); + } + + /// Wait for the acceptor to become ready to read, ready to write, or to have + /// pending error conditions. + /** + * This function is used to perform a blocking wait for an acceptor to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired acceptor state. + * + * @par Example + * Waiting for an acceptor to become readable. + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * acceptor.wait(asio::ip::tcp::acceptor::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), w, ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Wait for the acceptor to become ready to read, ready to write, or to have + /// pending error conditions. + /** + * This function is used to perform a blocking wait for an acceptor to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired acceptor state. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * Waiting for an acceptor to become readable. + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::error_code ec; + * acceptor.wait(asio::ip::tcp::acceptor::wait_read, ec); + * @endcode + */ + ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), w, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Asynchronously wait for the acceptor to become ready to read, ready to + /// write, or to have pending error conditions. + /** + * This function is used to perform an asynchronous wait for an acceptor to + * enter a ready to read, write or error condition state. + * + * @param w Specifies the desired acceptor state. + * + * @param handler The handler to be called when the wait operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * acceptor.async_wait( + * asio::ip::tcp::acceptor::wait_read, + * wait_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler, w); + } + +#if !defined(ASIO_NO_EXTENSIONS) + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer into the + * given socket. The function call will block until a new connection has been + * accepted successfully or an error occurs. + * + * @param peer The socket into which the new connection will be accepted. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(my_context); + * acceptor.accept(socket); + * @endcode + */ + template + void accept(basic_socket& peer, + typename enable_if< + is_convertible::value + >::type* = 0) + { + asio::error_code ec; + impl_.get_service().accept(impl_.get_implementation(), + peer, static_cast(0), ec); + asio::detail::throw_error(ec, "accept"); + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer into the + * given socket. The function call will block until a new connection has been + * accepted successfully or an error occurs. + * + * @param peer The socket into which the new connection will be accepted. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(my_context); + * asio::error_code ec; + * acceptor.accept(socket, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + ASIO_SYNC_OP_VOID accept( + basic_socket& peer, asio::error_code& ec, + typename enable_if< + is_convertible::value + >::type* = 0) + { + impl_.get_service().accept(impl_.get_implementation(), + peer, static_cast(0), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection into a + * socket. The function call always returns immediately. + * + * @param peer The socket into which the new connection will be accepted. + * Ownership of the peer object is retained by the caller, which must + * guarantee that it is valid until the handler is called. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(my_context); + * acceptor.async_accept(socket, accept_handler); + * @endcode + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + ASIO_MOVE_ARG(AcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type), + typename enable_if< + is_convertible::value + >::type* = 0) + { + return async_initiate( + initiate_async_accept(this), handler, + &peer, static_cast(0)); + } + + /// Accept a new connection and obtain the endpoint of the peer + /** + * This function is used to accept a new connection from a peer into the + * given socket, and additionally provide the endpoint of the remote peer. + * The function call will block until a new connection has been accepted + * successfully or an error occurs. + * + * @param peer The socket into which the new connection will be accepted. + * + * @param peer_endpoint An endpoint object which will receive the endpoint of + * the remote peer. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(my_context); + * asio::ip::tcp::endpoint endpoint; + * acceptor.accept(socket, endpoint); + * @endcode + */ + template + void accept(basic_socket& peer, + endpoint_type& peer_endpoint) + { + asio::error_code ec; + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + asio::detail::throw_error(ec, "accept"); + } + + /// Accept a new connection and obtain the endpoint of the peer + /** + * This function is used to accept a new connection from a peer into the + * given socket, and additionally provide the endpoint of the remote peer. + * The function call will block until a new connection has been accepted + * successfully or an error occurs. + * + * @param peer The socket into which the new connection will be accepted. + * + * @param peer_endpoint An endpoint object which will receive the endpoint of + * the remote peer. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(my_context); + * asio::ip::tcp::endpoint endpoint; + * asio::error_code ec; + * acceptor.accept(socket, endpoint, ec); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + ASIO_SYNC_OP_VOID accept(basic_socket& peer, + endpoint_type& peer_endpoint, asio::error_code& ec) + { + impl_.get_service().accept( + impl_.get_implementation(), peer, &peer_endpoint, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection into a + * socket, and additionally obtain the endpoint of the remote peer. The + * function call always returns immediately. + * + * @param peer The socket into which the new connection will be accepted. + * Ownership of the peer object is retained by the caller, which must + * guarantee that it is valid until the handler is called. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. Ownership of the peer_endpoint object is + * retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(AcceptHandler, + void (asio::error_code)) + async_accept(basic_socket& peer, + endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(AcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_accept(this), handler, &peer, &peer_endpoint); + } +#endif // !defined(ASIO_NO_EXTENSIONS) + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept()); + * @endcode + */ + typename Protocol::socket::template rebind_executor::other + accept() + { + asio::error_code ec; + typename Protocol::socket::template rebind_executor< + executor_type>::other peer(impl_.get_executor()); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept(ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket::template rebind_executor::other + accept(asio::error_code& ec) + { + typename Protocol::socket::template rebind_executor< + executor_type>::other peer(impl_.get_executor()); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + return peer; + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * // On success, the newly accepted socket. + * typename Protocol::socket::template + * rebind_executor::other peer + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * acceptor.async_accept(accept_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + typename Protocol::socket::template rebind_executor< + executor_type>::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template + rebind_executor::other)) + async_accept( + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate::other)>( + initiate_async_move_accept(this), handler, + impl_.get_executor(), static_cast(0), + static_cast::other*>(0)); + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly + * accepted socket. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept()); + * @endcode + */ + template + typename Protocol::socket::template rebind_executor::other + accept(const Executor1& ex, + typename enable_if< + is_executor::value + >::type* = 0) + { + asio::error_code ec; + typename Protocol::socket::template + rebind_executor::other peer(ex); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept()); + * @endcode + */ + template + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other + accept(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + { + asio::error_code ec; + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other peer(context); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly accepted + * socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + typename Protocol::socket::template rebind_executor::other + accept(const Executor1& ex, asio::error_code& ec, + typename enable_if< + is_executor::value + >::type* = 0) + { + typename Protocol::socket::template + rebind_executor::other peer(ex); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other + accept(ExecutionContext& context, asio::error_code& ec, + typename enable_if< + is_convertible::value + >::type* = 0) + { + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other peer(context); + impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); + return peer; + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly accepted + * socket. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket::template rebind_executor< + * Executor1>::other peer // On success, the newly accepted socket. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * acceptor.async_accept(my_context2, accept_handler); + * @endcode + */ + template ::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template rebind_executor< + Executor1>::other)) + async_accept(const Executor1& ex, + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type), + typename enable_if< + is_executor::value + >::type* = 0) + { + typedef typename Protocol::socket::template rebind_executor< + Executor1>::other other_socket_type; + + return async_initiate( + initiate_async_move_accept(this), handler, + ex, static_cast(0), + static_cast(0)); + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket::template rebind_executor< + * typename ExecutionContext::executor_type>::other peer + * // On success, the newly accepted socket. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * acceptor.async_accept(my_context2, accept_handler); + * @endcode + */ + template ::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other)) + async_accept(ExecutionContext& context, + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type), + typename enable_if< + is_convertible::value + >::type* = 0) + { + typedef typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other other_socket_type; + + return async_initiate( + initiate_async_move_accept(this), handler, + context.get_executor(), static_cast(0), + static_cast(0)); + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket(acceptor.accept(endpoint)); + * @endcode + */ + typename Protocol::socket::template rebind_executor::other + accept(endpoint_type& peer_endpoint) + { + asio::error_code ec; + typename Protocol::socket::template rebind_executor< + executor_type>::other peer(impl_.get_executor()); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket(acceptor.accept(endpoint, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + typename Protocol::socket::template rebind_executor::other + accept(endpoint_type& peer_endpoint, asio::error_code& ec) + { + typename Protocol::socket::template rebind_executor< + executor_type>::other peer(impl_.get_executor()); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + return peer; + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. Ownership of the peer_endpoint object is + * retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * // On success, the newly accepted socket. + * typename Protocol::socket::template + * rebind_executor::other peer + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * acceptor.async_accept(endpoint, accept_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + typename Protocol::socket::template rebind_executor< + executor_type>::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template + rebind_executor::other)) + async_accept(endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate::other)>( + initiate_async_move_accept(this), handler, + impl_.get_executor(), &peer_endpoint, + static_cast::other*>(0)); + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly accepted + * socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(my_context2, endpoint)); + * @endcode + */ + template + typename Protocol::socket::template rebind_executor::other + accept(const Executor1& ex, endpoint_type& peer_endpoint, + typename enable_if< + is_executor::value + >::type* = 0) + { + asio::error_code ec; + typename Protocol::socket::template + rebind_executor::other peer(ex); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @returns A socket object representing the newly accepted connection. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(my_context2, endpoint)); + * @endcode + */ + template + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other + accept(ExecutionContext& context, endpoint_type& peer_endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + { + asio::error_code ec; + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other peer(context); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + asio::detail::throw_error(ec, "accept"); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly accepted + * socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(my_context2, endpoint, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + typename Protocol::socket::template rebind_executor::other + accept(const executor_type& ex, + endpoint_type& peer_endpoint, asio::error_code& ec, + typename enable_if< + is_executor::value + >::type* = 0) + { + typename Protocol::socket::template + rebind_executor::other peer(ex); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + return peer; + } + + /// Accept a new connection. + /** + * This function is used to accept a new connection from a peer. The function + * call will block until a new connection has been accepted successfully or + * an error occurs. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns On success, a socket object representing the newly accepted + * connection. On error, a socket object where is_open() is false. + * + * @par Example + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * asio::ip::tcp::socket socket( + * acceptor.accept(my_context2, endpoint, ec)); + * if (ec) + * { + * // An error occurred. + * } + * @endcode + */ + template + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other + accept(ExecutionContext& context, + endpoint_type& peer_endpoint, asio::error_code& ec, + typename enable_if< + is_convertible::value + >::type* = 0) + { + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other peer(context); + impl_.get_service().accept(impl_.get_implementation(), + peer, &peer_endpoint, ec); + return peer; + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param ex The I/O executor object to be used for the newly accepted + * socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. Ownership of the peer_endpoint object is + * retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket::template rebind_executor< + * Executor1>::other peer // On success, the newly accepted socket. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * acceptor.async_accept(my_context2, endpoint, accept_handler); + * @endcode + */ + template ::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template rebind_executor< + Executor1>::other)) + async_accept(const Executor1& ex, endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type), + typename enable_if< + is_executor::value + >::type* = 0) + { + typedef typename Protocol::socket::template rebind_executor< + Executor1>::other other_socket_type; + + return async_initiate( + initiate_async_move_accept(this), handler, + ex, &peer_endpoint, + static_cast(0)); + } + + /// Start an asynchronous accept. + /** + * This function is used to asynchronously accept a new connection. The + * function call always returns immediately. + * + * This overload requires that the Protocol template parameter satisfy the + * AcceptableProtocol type requirements. + * + * @param context The I/O execution context object to be used for the newly + * accepted socket. + * + * @param peer_endpoint An endpoint object into which the endpoint of the + * remote peer will be written. Ownership of the peer_endpoint object is + * retained by the caller, which must guarantee that it is valid until the + * handler is called. + * + * @param handler The handler to be called when the accept operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * typename Protocol::socket::template rebind_executor< + * typename ExecutionContext::executor_type>::other peer + * // On success, the newly accepted socket. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void accept_handler(const asio::error_code& error, + * asio::ip::tcp::socket peer) + * { + * if (!error) + * { + * // Accept succeeded. + * } + * } + * + * ... + * + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::ip::tcp::endpoint endpoint; + * acceptor.async_accept(my_context2, endpoint, accept_handler); + * @endcode + */ + template ::other)) MoveAcceptHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(MoveAcceptHandler, + void (asio::error_code, + typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other)) + async_accept(ExecutionContext& context, + endpoint_type& peer_endpoint, + ASIO_MOVE_ARG(MoveAcceptHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type), + typename enable_if< + is_convertible::value + >::type* = 0) + { + typedef typename Protocol::socket::template rebind_executor< + typename ExecutionContext::executor_type>::other other_socket_type; + + return async_initiate( + initiate_async_move_accept(this), handler, + context.get_executor(), &peer_endpoint, + static_cast(0)); + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +private: + // Disallow copying and assignment. + basic_socket_acceptor(const basic_socket_acceptor&) ASIO_DELETED; + basic_socket_acceptor& operator=( + const basic_socket_acceptor&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_socket_acceptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler, wait_type w) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), w, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_socket_acceptor* self_; + }; + + class initiate_async_accept + { + public: + typedef Executor executor_type; + + explicit initiate_async_accept(basic_socket_acceptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(AcceptHandler) handler, + basic_socket* peer, + endpoint_type* peer_endpoint) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a AcceptHandler. + ASIO_ACCEPT_HANDLER_CHECK(AcceptHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_accept( + self_->impl_.get_implementation(), *peer, peer_endpoint, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_socket_acceptor* self_; + }; + + class initiate_async_move_accept + { + public: + typedef Executor executor_type; + + explicit initiate_async_move_accept(basic_socket_acceptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(MoveAcceptHandler) handler, + const Executor1& peer_ex, endpoint_type* peer_endpoint, Socket*) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a MoveAcceptHandler. + ASIO_MOVE_ACCEPT_HANDLER_CHECK( + MoveAcceptHandler, handler, Socket) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_move_accept( + self_->impl_.get_implementation(), peer_ex, peer_endpoint, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_socket_acceptor* self_; + }; + +#if defined(ASIO_WINDOWS_RUNTIME) + detail::io_object_impl< + detail::null_socket_service, Executor> impl_; +#elif defined(ASIO_HAS_IOCP) + detail::io_object_impl< + detail::win_iocp_socket_service, Executor> impl_; +#else + detail::io_object_impl< + detail::reactive_socket_service, Executor> impl_; +#endif +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_SOCKET_ACCEPTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_iostream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_iostream.hpp new file mode 100644 index 00000000..135f23d7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_iostream.hpp @@ -0,0 +1,407 @@ +// +// basic_socket_iostream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SOCKET_IOSTREAM_HPP +#define ASIO_BASIC_SOCKET_IOSTREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_IOSTREAM) + +#include +#include +#include "asio/basic_socket_streambuf.hpp" + +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +# include "asio/detail/variadic_templates.hpp" + +// A macro that should expand to: +// template +// explicit basic_socket_iostream(T1 x1, ..., Tn xn) +// : std::basic_iostream( +// &this->detail::socket_iostream_base< +// Protocol, Clock, WaitTraits>::streambuf_) +// { +// if (rdbuf()->connect(x1, ..., xn) == 0) +// this->setstate(std::ios_base::failbit); +// } +// This macro should only persist within this file. + +# define ASIO_PRIVATE_CTR_DEF(n) \ + template \ + explicit basic_socket_iostream(ASIO_VARIADIC_BYVAL_PARAMS(n)) \ + : std::basic_iostream( \ + &this->detail::socket_iostream_base< \ + Protocol, Clock, WaitTraits>::streambuf_) \ + { \ + this->setf(std::ios_base::unitbuf); \ + if (rdbuf()->connect(ASIO_VARIADIC_BYVAL_ARGS(n)) == 0) \ + this->setstate(std::ios_base::failbit); \ + } \ + /**/ + +// A macro that should expand to: +// template +// void connect(T1 x1, ..., Tn xn) +// { +// if (rdbuf()->connect(x1, ..., xn) == 0) +// this->setstate(std::ios_base::failbit); +// } +// This macro should only persist within this file. + +# define ASIO_PRIVATE_CONNECT_DEF(n) \ + template \ + void connect(ASIO_VARIADIC_BYVAL_PARAMS(n)) \ + { \ + if (rdbuf()->connect(ASIO_VARIADIC_BYVAL_ARGS(n)) == 0) \ + this->setstate(std::ios_base::failbit); \ + } \ + /**/ + +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// A separate base class is used to ensure that the streambuf is initialised +// prior to the basic_socket_iostream's basic_iostream base class. +template +class socket_iostream_base +{ +protected: + socket_iostream_base() + { + } + +#if defined(ASIO_HAS_MOVE) + socket_iostream_base(socket_iostream_base&& other) + : streambuf_(std::move(other.streambuf_)) + { + } + + socket_iostream_base(basic_stream_socket s) + : streambuf_(std::move(s)) + { + } + + socket_iostream_base& operator=(socket_iostream_base&& other) + { + streambuf_ = std::move(other.streambuf_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + basic_socket_streambuf streambuf_; +}; + +} // namespace detail + +#if !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) +#define ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL + +// Forward declaration with defaulted arguments. +template > +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits > +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) +class basic_socket_iostream; + +#endif // !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) + +/// Iostream interface for a socket. +#if defined(GENERATING_DOCUMENTATION) +template > +#else // defined(GENERATING_DOCUMENTATION) +template +#endif // defined(GENERATING_DOCUMENTATION) +class basic_socket_iostream + : private detail::socket_iostream_base, + public std::basic_iostream +{ +private: + // These typedefs are intended keep this class's implementation independent + // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typedef WaitTraits traits_helper; +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typedef detail::chrono_time_traits traits_helper; +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + +public: + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// The clock type. + typedef Clock clock_type; + +#if defined(GENERATING_DOCUMENTATION) + /// (Deprecated: Use time_point.) The time type. + typedef typename WaitTraits::time_type time_type; + + /// The time type. + typedef typename WaitTraits::time_point time_point; + + /// (Deprecated: Use duration.) The duration type. + typedef typename WaitTraits::duration_type duration_type; + + /// The duration type. + typedef typename WaitTraits::duration duration; +#else +# if !defined(ASIO_NO_DEPRECATED) + typedef typename traits_helper::time_type time_type; + typedef typename traits_helper::duration_type duration_type; +# endif // !defined(ASIO_NO_DEPRECATED) + typedef typename traits_helper::time_type time_point; + typedef typename traits_helper::duration_type duration; +#endif + + /// Construct a basic_socket_iostream without establishing a connection. + basic_socket_iostream() + : std::basic_iostream( + &this->detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::streambuf_) + { + this->setf(std::ios_base::unitbuf); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Construct a basic_socket_iostream from the supplied socket. + explicit basic_socket_iostream(basic_stream_socket s) + : detail::socket_iostream_base< + Protocol, Clock, WaitTraits>(std::move(s)), + std::basic_iostream( + &this->detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::streambuf_) + { + this->setf(std::ios_base::unitbuf); + } + +#if defined(ASIO_HAS_STD_IOSTREAM_MOVE) \ + || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_socket_iostream from another. + basic_socket_iostream(basic_socket_iostream&& other) + : detail::socket_iostream_base< + Protocol, Clock, WaitTraits>(std::move(other)), + std::basic_iostream(std::move(other)) + { + this->set_rdbuf(&this->detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::streambuf_); + } + + /// Move-assign a basic_socket_iostream from another. + basic_socket_iostream& operator=(basic_socket_iostream&& other) + { + std::basic_iostream::operator=(std::move(other)); + detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_STD_IOSTREAM_MOVE) + // || defined(GENERATING_DOCUMENTATION) +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#if defined(GENERATING_DOCUMENTATION) + /// Establish a connection to an endpoint corresponding to a resolver query. + /** + * This constructor automatically establishes a connection based on the + * supplied resolver query parameters. The arguments are used to construct + * a resolver query object. + */ + template + explicit basic_socket_iostream(T1 t1, ..., TN tn); +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + template + explicit basic_socket_iostream(T... x) + : std::basic_iostream( + &this->detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::streambuf_) + { + this->setf(std::ios_base::unitbuf); + if (rdbuf()->connect(x...) == 0) + this->setstate(std::ios_base::failbit); + } +#else + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CTR_DEF) +#endif + +#if defined(GENERATING_DOCUMENTATION) + /// Establish a connection to an endpoint corresponding to a resolver query. + /** + * This function automatically establishes a connection based on the supplied + * resolver query parameters. The arguments are used to construct a resolver + * query object. + */ + template + void connect(T1 t1, ..., TN tn); +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + template + void connect(T... x) + { + if (rdbuf()->connect(x...) == 0) + this->setstate(std::ios_base::failbit); + } +#else + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CONNECT_DEF) +#endif + + /// Close the connection. + void close() + { + if (rdbuf()->close() == 0) + this->setstate(std::ios_base::failbit); + } + + /// Return a pointer to the underlying streambuf. + basic_socket_streambuf* rdbuf() const + { + return const_cast*>( + &this->detail::socket_iostream_base< + Protocol, Clock, WaitTraits>::streambuf_); + } + + /// Get a reference to the underlying socket. + basic_socket& socket() + { + return rdbuf()->socket(); + } + + /// Get the last error associated with the stream. + /** + * @return An \c error_code corresponding to the last error from the stream. + * + * @par Example + * To print the error associated with a failure to establish a connection: + * @code tcp::iostream s("www.boost.org", "http"); + * if (!s) + * { + * std::cout << "Error: " << s.error().message() << std::endl; + * } @endcode + */ + const asio::error_code& error() const + { + return rdbuf()->error(); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the stream's expiry time as an absolute + /// time. + /** + * @return An absolute time value representing the stream's expiry time. + */ + time_point expires_at() const + { + return rdbuf()->expires_at(); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the stream's expiry time as an absolute time. + /** + * @return An absolute time value representing the stream's expiry time. + */ + time_point expiry() const + { + return rdbuf()->expiry(); + } + + /// Set the stream's expiry time as an absolute time. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the stream. + */ + void expires_at(const time_point& expiry_time) + { + rdbuf()->expires_at(expiry_time); + } + + /// Set the stream's expiry time relative to now. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the timer. + */ + void expires_after(const duration& expiry_time) + { + rdbuf()->expires_after(expiry_time); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the stream's expiry time relative to now. + /** + * @return A relative time value representing the stream's expiry time. + */ + duration expires_from_now() const + { + return rdbuf()->expires_from_now(); + } + + /// (Deprecated: Use expires_after().) Set the stream's expiry time relative + /// to now. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the timer. + */ + void expires_from_now(const duration& expiry_time) + { + rdbuf()->expires_from_now(expiry_time); + } +#endif // !defined(ASIO_NO_DEPRECATED) + +private: + // Disallow copying and assignment. + basic_socket_iostream(const basic_socket_iostream&) ASIO_DELETED; + basic_socket_iostream& operator=( + const basic_socket_iostream&) ASIO_DELETED; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) +# undef ASIO_PRIVATE_CTR_DEF +# undef ASIO_PRIVATE_CONNECT_DEF +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_BASIC_SOCKET_IOSTREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_streambuf.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_streambuf.hpp new file mode 100644 index 00000000..bf36bac1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_socket_streambuf.hpp @@ -0,0 +1,687 @@ +// +// basic_socket_streambuf.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_SOCKET_STREAMBUF_HPP +#define ASIO_BASIC_SOCKET_STREAMBUF_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_IOSTREAM) + +#include +#include +#include "asio/basic_socket.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/io_context.hpp" + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) +# include "asio/detail/deadline_timer_service.hpp" +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) +# include "asio/steady_timer.hpp" +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +# include "asio/detail/variadic_templates.hpp" + +// A macro that should expand to: +// template +// basic_socket_streambuf* connect(T1 x1, ..., Tn xn) +// { +// init_buffers(); +// typedef typename Protocol::resolver resolver_type; +// resolver_type resolver(socket().get_executor()); +// connect_to_endpoints( +// resolver.resolve(x1, ..., xn, ec_)); +// return !ec_ ? this : 0; +// } +// This macro should only persist within this file. + +# define ASIO_PRIVATE_CONNECT_DEF(n) \ + template \ + basic_socket_streambuf* connect(ASIO_VARIADIC_BYVAL_PARAMS(n)) \ + { \ + init_buffers(); \ + typedef typename Protocol::resolver resolver_type; \ + resolver_type resolver(socket().get_executor()); \ + connect_to_endpoints( \ + resolver.resolve(ASIO_VARIADIC_BYVAL_ARGS(n), ec_)); \ + return !ec_ ? this : 0; \ + } \ + /**/ + +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// A separate base class is used to ensure that the io_context member is +// initialised prior to the basic_socket_streambuf's basic_socket base class. +class socket_streambuf_io_context +{ +protected: + socket_streambuf_io_context(io_context* ctx) + : default_io_context_(ctx) + { + } + + shared_ptr default_io_context_; +}; + +// A separate base class is used to ensure that the dynamically allocated +// buffers are constructed prior to the basic_socket_streambuf's basic_socket +// base class. This makes moving the socket is the last potentially throwing +// step in the streambuf's move constructor, giving the constructor a strong +// exception safety guarantee. +class socket_streambuf_buffers +{ +protected: + socket_streambuf_buffers() + : get_buffer_(buffer_size), + put_buffer_(buffer_size) + { + } + + enum { buffer_size = 512 }; + std::vector get_buffer_; + std::vector put_buffer_; +}; + +} // namespace detail + +#if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) +#define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL + +// Forward declaration with defaulted arguments. +template > +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits > +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) +class basic_socket_streambuf; + +#endif // !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) + +/// Iostream streambuf for a socket. +#if defined(GENERATING_DOCUMENTATION) +template > +#else // defined(GENERATING_DOCUMENTATION) +template +#endif // defined(GENERATING_DOCUMENTATION) +class basic_socket_streambuf + : public std::streambuf, + private detail::socket_streambuf_io_context, + private detail::socket_streambuf_buffers, +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + private basic_socket +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + public basic_socket +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +{ +private: + // These typedefs are intended keep this class's implementation independent + // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typedef WaitTraits traits_helper; +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + typedef detail::chrono_time_traits traits_helper; +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + +public: + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// The clock type. + typedef Clock clock_type; + +#if defined(GENERATING_DOCUMENTATION) + /// (Deprecated: Use time_point.) The time type. + typedef typename WaitTraits::time_type time_type; + + /// The time type. + typedef typename WaitTraits::time_point time_point; + + /// (Deprecated: Use duration.) The duration type. + typedef typename WaitTraits::duration_type duration_type; + + /// The duration type. + typedef typename WaitTraits::duration duration; +#else +# if !defined(ASIO_NO_DEPRECATED) + typedef typename traits_helper::time_type time_type; + typedef typename traits_helper::duration_type duration_type; +# endif // !defined(ASIO_NO_DEPRECATED) + typedef typename traits_helper::time_type time_point; + typedef typename traits_helper::duration_type duration; +#endif + + /// Construct a basic_socket_streambuf without establishing a connection. + basic_socket_streambuf() + : detail::socket_streambuf_io_context(new io_context), + basic_socket(*default_io_context_), + expiry_time_(max_expiry_time()) + { + init_buffers(); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Construct a basic_socket_streambuf from the supplied socket. + explicit basic_socket_streambuf(basic_stream_socket s) + : detail::socket_streambuf_io_context(0), + basic_socket(std::move(s)), + expiry_time_(max_expiry_time()) + { + init_buffers(); + } + + /// Move-construct a basic_socket_streambuf from another. + basic_socket_streambuf(basic_socket_streambuf&& other) + : detail::socket_streambuf_io_context(other), + basic_socket(std::move(other.socket())), + ec_(other.ec_), + expiry_time_(other.expiry_time_) + { + get_buffer_.swap(other.get_buffer_); + put_buffer_.swap(other.put_buffer_); + setg(other.eback(), other.gptr(), other.egptr()); + setp(other.pptr(), other.epptr()); + other.ec_ = asio::error_code(); + other.expiry_time_ = max_expiry_time(); + other.init_buffers(); + } + + /// Move-assign a basic_socket_streambuf from another. + basic_socket_streambuf& operator=(basic_socket_streambuf&& other) + { + this->close(); + socket() = std::move(other.socket()); + detail::socket_streambuf_io_context::operator=(other); + ec_ = other.ec_; + expiry_time_ = other.expiry_time_; + get_buffer_.swap(other.get_buffer_); + put_buffer_.swap(other.put_buffer_); + setg(other.eback(), other.gptr(), other.egptr()); + setp(other.pptr(), other.epptr()); + other.ec_ = asio::error_code(); + other.expiry_time_ = max_expiry_time(); + other.put_buffer_.resize(buffer_size); + other.init_buffers(); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor flushes buffered data. + virtual ~basic_socket_streambuf() + { + if (pptr() != pbase()) + overflow(traits_type::eof()); + } + + /// Establish a connection. + /** + * This function establishes a connection to the specified endpoint. + * + * @return \c this if a connection was successfully established, a null + * pointer otherwise. + */ + basic_socket_streambuf* connect(const endpoint_type& endpoint) + { + init_buffers(); + ec_ = asio::error_code(); + this->connect_to_endpoints(&endpoint, &endpoint + 1); + return !ec_ ? this : 0; + } + +#if defined(GENERATING_DOCUMENTATION) + /// Establish a connection. + /** + * This function automatically establishes a connection based on the supplied + * resolver query parameters. The arguments are used to construct a resolver + * query object. + * + * @return \c this if a connection was successfully established, a null + * pointer otherwise. + */ + template + basic_socket_streambuf* connect(T1 t1, ..., TN tn); +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + template + basic_socket_streambuf* connect(T... x) + { + init_buffers(); + typedef typename Protocol::resolver resolver_type; + resolver_type resolver(socket().get_executor()); + connect_to_endpoints(resolver.resolve(x..., ec_)); + return !ec_ ? this : 0; + } +#else + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CONNECT_DEF) +#endif + + /// Close the connection. + /** + * @return \c this if a connection was successfully established, a null + * pointer otherwise. + */ + basic_socket_streambuf* close() + { + sync(); + socket().close(ec_); + if (!ec_) + init_buffers(); + return !ec_ ? this : 0; + } + + /// Get a reference to the underlying socket. + basic_socket& socket() + { + return *this; + } + + /// Get the last error associated with the stream buffer. + /** + * @return An \c error_code corresponding to the last error from the stream + * buffer. + */ + const asio::error_code& error() const + { + return ec_; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use error().) Get the last error associated with the stream + /// buffer. + /** + * @return An \c error_code corresponding to the last error from the stream + * buffer. + */ + const asio::error_code& puberror() const + { + return error(); + } + + /// (Deprecated: Use expiry().) Get the stream buffer's expiry time as an + /// absolute time. + /** + * @return An absolute time value representing the stream buffer's expiry + * time. + */ + time_point expires_at() const + { + return expiry_time_; + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the stream buffer's expiry time as an absolute time. + /** + * @return An absolute time value representing the stream buffer's expiry + * time. + */ + time_point expiry() const + { + return expiry_time_; + } + + /// Set the stream buffer's expiry time as an absolute time. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the stream. + */ + void expires_at(const time_point& expiry_time) + { + expiry_time_ = expiry_time; + } + + /// Set the stream buffer's expiry time relative to now. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the timer. + */ + void expires_after(const duration& expiry_time) + { + expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the stream buffer's expiry time relative + /// to now. + /** + * @return A relative time value representing the stream buffer's expiry time. + */ + duration expires_from_now() const + { + return traits_helper::subtract(expires_at(), traits_helper::now()); + } + + /// (Deprecated: Use expires_after().) Set the stream buffer's expiry time + /// relative to now. + /** + * This function sets the expiry time associated with the stream. Stream + * operations performed after this time (where the operations cannot be + * completed using the internal buffers) will fail with the error + * asio::error::operation_aborted. + * + * @param expiry_time The expiry time to be used for the timer. + */ + void expires_from_now(const duration& expiry_time) + { + expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); + } +#endif // !defined(ASIO_NO_DEPRECATED) + +protected: + int_type underflow() + { +#if defined(ASIO_WINDOWS_RUNTIME) + ec_ = asio::error::operation_not_supported; + return traits_type::eof(); +#else // defined(ASIO_WINDOWS_RUNTIME) + if (gptr() != egptr()) + return traits_type::eof(); + + for (;;) + { + // Check if we are past the expiry time. + if (traits_helper::less_than(expiry_time_, traits_helper::now())) + { + ec_ = asio::error::timed_out; + return traits_type::eof(); + } + + // Try to complete the operation without blocking. + if (!socket().native_non_blocking()) + socket().native_non_blocking(true, ec_); + detail::buffer_sequence_adapter + bufs(asio::buffer(get_buffer_) + putback_max); + detail::signed_size_type bytes = detail::socket_ops::recv( + socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); + + // Check if operation succeeded. + if (bytes > 0) + { + setg(&get_buffer_[0], &get_buffer_[0] + putback_max, + &get_buffer_[0] + putback_max + bytes); + return traits_type::to_int_type(*gptr()); + } + + // Check for EOF. + if (bytes == 0) + { + ec_ = asio::error::eof; + return traits_type::eof(); + } + + // Operation failed. + if (ec_ != asio::error::would_block + && ec_ != asio::error::try_again) + return traits_type::eof(); + + // Wait for socket to become ready. + if (detail::socket_ops::poll_read( + socket().native_handle(), 0, timeout(), ec_) < 0) + return traits_type::eof(); + } +#endif // defined(ASIO_WINDOWS_RUNTIME) + } + + int_type overflow(int_type c) + { +#if defined(ASIO_WINDOWS_RUNTIME) + ec_ = asio::error::operation_not_supported; + return traits_type::eof(); +#else // defined(ASIO_WINDOWS_RUNTIME) + char_type ch = traits_type::to_char_type(c); + + // Determine what needs to be sent. + const_buffer output_buffer; + if (put_buffer_.empty()) + { + if (traits_type::eq_int_type(c, traits_type::eof())) + return traits_type::not_eof(c); // Nothing to do. + output_buffer = asio::buffer(&ch, sizeof(char_type)); + } + else + { + output_buffer = asio::buffer(pbase(), + (pptr() - pbase()) * sizeof(char_type)); + } + + while (output_buffer.size() > 0) + { + // Check if we are past the expiry time. + if (traits_helper::less_than(expiry_time_, traits_helper::now())) + { + ec_ = asio::error::timed_out; + return traits_type::eof(); + } + + // Try to complete the operation without blocking. + if (!socket().native_non_blocking()) + socket().native_non_blocking(true, ec_); + detail::buffer_sequence_adapter< + const_buffer, const_buffer> bufs(output_buffer); + detail::signed_size_type bytes = detail::socket_ops::send( + socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); + + // Check if operation succeeded. + if (bytes > 0) + { + output_buffer += static_cast(bytes); + continue; + } + + // Operation failed. + if (ec_ != asio::error::would_block + && ec_ != asio::error::try_again) + return traits_type::eof(); + + // Wait for socket to become ready. + if (detail::socket_ops::poll_write( + socket().native_handle(), 0, timeout(), ec_) < 0) + return traits_type::eof(); + } + + if (!put_buffer_.empty()) + { + setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); + + // If the new character is eof then our work here is done. + if (traits_type::eq_int_type(c, traits_type::eof())) + return traits_type::not_eof(c); + + // Add the new character to the output buffer. + *pptr() = ch; + pbump(1); + } + + return c; +#endif // defined(ASIO_WINDOWS_RUNTIME) + } + + int sync() + { + return overflow(traits_type::eof()); + } + + std::streambuf* setbuf(char_type* s, std::streamsize n) + { + if (pptr() == pbase() && s == 0 && n == 0) + { + put_buffer_.clear(); + setp(0, 0); + sync(); + return this; + } + + return 0; + } + +private: + // Disallow copying and assignment. + basic_socket_streambuf(const basic_socket_streambuf&) ASIO_DELETED; + basic_socket_streambuf& operator=( + const basic_socket_streambuf&) ASIO_DELETED; + + void init_buffers() + { + setg(&get_buffer_[0], + &get_buffer_[0] + putback_max, + &get_buffer_[0] + putback_max); + + if (put_buffer_.empty()) + setp(0, 0); + else + setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); + } + + int timeout() const + { + int64_t msec = traits_helper::to_posix_duration( + traits_helper::subtract(expiry_time_, + traits_helper::now())).total_milliseconds(); + if (msec > (std::numeric_limits::max)()) + msec = (std::numeric_limits::max)(); + else if (msec < 0) + msec = 0; + return static_cast(msec); + } + + template + void connect_to_endpoints(const EndpointSequence& endpoints) + { + this->connect_to_endpoints(endpoints.begin(), endpoints.end()); + } + + template + void connect_to_endpoints(EndpointIterator begin, EndpointIterator end) + { +#if defined(ASIO_WINDOWS_RUNTIME) + ec_ = asio::error::operation_not_supported; +#else // defined(ASIO_WINDOWS_RUNTIME) + if (ec_) + return; + + ec_ = asio::error::not_found; + for (EndpointIterator i = begin; i != end; ++i) + { + // Check if we are past the expiry time. + if (traits_helper::less_than(expiry_time_, traits_helper::now())) + { + ec_ = asio::error::timed_out; + return; + } + + // Close and reopen the socket. + typename Protocol::endpoint ep(*i); + socket().close(ec_); + socket().open(ep.protocol(), ec_); + if (ec_) + continue; + + // Try to complete the operation without blocking. + if (!socket().native_non_blocking()) + socket().native_non_blocking(true, ec_); + detail::socket_ops::connect(socket().native_handle(), + ep.data(), ep.size(), ec_); + + // Check if operation succeeded. + if (!ec_) + return; + + // Operation failed. + if (ec_ != asio::error::in_progress + && ec_ != asio::error::would_block) + continue; + + // Wait for socket to become ready. + if (detail::socket_ops::poll_connect( + socket().native_handle(), timeout(), ec_) < 0) + continue; + + // Get the error code from the connect operation. + int connect_error = 0; + size_t connect_error_len = sizeof(connect_error); + if (detail::socket_ops::getsockopt(socket().native_handle(), 0, + SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec_) + == detail::socket_error_retval) + return; + + // Check the result of the connect operation. + ec_ = asio::error_code(connect_error, + asio::error::get_system_category()); + if (!ec_) + return; + } +#endif // defined(ASIO_WINDOWS_RUNTIME) + } + + // Helper function to get the maximum expiry time. + static time_point max_expiry_time() + { +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + return boost::posix_time::pos_infin; +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + return (time_point::max)(); +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) + } + + enum { putback_max = 8 }; + asio::error_code ec_; + time_point expiry_time_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) +# undef ASIO_PRIVATE_CONNECT_DEF +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_BASIC_SOCKET_STREAMBUF_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_stream_socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_stream_socket.hpp new file mode 100644 index 00000000..f7b03c23 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_stream_socket.hpp @@ -0,0 +1,1049 @@ +// +// basic_stream_socket.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_STREAM_SOCKET_HPP +#define ASIO_BASIC_STREAM_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/basic_socket.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) +#define ASIO_BASIC_STREAM_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_stream_socket; + +#endif // !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) + +/// Provides stream-oriented socket functionality. +/** + * The basic_stream_socket class template provides asynchronous and blocking + * stream-oriented socket functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class basic_stream_socket + : public basic_socket +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the socket type to another executor. + template + struct rebind_executor + { + /// The socket type when rebound to the specified executor. + typedef basic_stream_socket other; + }; + + /// The native representation of a socket. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef typename basic_socket::native_handle_type native_handle_type; +#endif + + /// The protocol type. + typedef Protocol protocol_type; + + /// The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + /// Construct a basic_stream_socket without opening it. + /** + * This constructor creates a stream socket without opening it. The socket + * needs to be opened and then connected or accepted before data can be sent + * or received on it. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + */ + explicit basic_stream_socket(const executor_type& ex) + : basic_socket(ex) + { + } + + /// Construct a basic_stream_socket without opening it. + /** + * This constructor creates a stream socket without opening it. The socket + * needs to be opened and then connected or accepted before data can be sent + * or received on it. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + */ + template + explicit basic_stream_socket(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context) + { + } + + /// Construct and open a basic_stream_socket. + /** + * This constructor creates and opens a stream socket. The socket needs to be + * connected or accepted before data can be sent or received on it. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_socket(const executor_type& ex, const protocol_type& protocol) + : basic_socket(ex, protocol) + { + } + + /// Construct and open a basic_stream_socket. + /** + * This constructor creates and opens a stream socket. The socket needs to be + * connected or accepted before data can be sent or received on it. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_stream_socket(ExecutionContext& context, const protocol_type& protocol, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol) + { + } + + /// Construct a basic_stream_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a stream socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the stream + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_socket(const executor_type& ex, const endpoint_type& endpoint) + : basic_socket(ex, endpoint) + { + } + + /// Construct a basic_stream_socket, opening it and binding it to the given + /// local endpoint. + /** + * This constructor creates a stream socket and automatically opens it bound + * to the specified endpoint on the local machine. The protocol used is the + * protocol associated with the given endpoint. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param endpoint An endpoint on the local machine to which the stream + * socket will be bound. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_stream_socket(ExecutionContext& context, const endpoint_type& endpoint, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, endpoint) + { + } + + /// Construct a basic_stream_socket on an existing native socket. + /** + * This constructor creates a stream socket object to hold an existing native + * socket. + * + * @param ex The I/O executor that the socket will use, by default, to + * dispatch handlers for any asynchronous operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_socket(const executor_type& ex, + const protocol_type& protocol, const native_handle_type& native_socket) + : basic_socket(ex, protocol, native_socket) + { + } + + /// Construct a basic_stream_socket on an existing native socket. + /** + * This constructor creates a stream socket object to hold an existing native + * socket. + * + * @param context An execution context which provides the I/O executor that + * the socket will use, by default, to dispatch handlers for any asynchronous + * operations performed on the socket. + * + * @param protocol An object specifying protocol parameters to be used. + * + * @param native_socket The new underlying socket implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_stream_socket(ExecutionContext& context, + const protocol_type& protocol, const native_handle_type& native_socket, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_socket(context, protocol, native_socket) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_stream_socket from another. + /** + * This constructor moves a stream socket from one object to another. + * + * @param other The other basic_stream_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_socket(const executor_type&) + * constructor. + */ + basic_stream_socket(basic_stream_socket&& other) ASIO_NOEXCEPT + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_stream_socket from another. + /** + * This assignment operator moves a stream socket from one object to another. + * + * @param other The other basic_stream_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_socket(const executor_type&) + * constructor. + */ + basic_stream_socket& operator=(basic_stream_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } + + /// Move-construct a basic_stream_socket from a socket of another protocol + /// type. + /** + * This constructor moves a stream socket from one object to another. + * + * @param other The other basic_stream_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_socket(const executor_type&) + * constructor. + */ + template + basic_stream_socket(basic_stream_socket&& other, + typename enable_if< + is_convertible::value + && is_convertible::value + >::type* = 0) + : basic_socket(std::move(other)) + { + } + + /// Move-assign a basic_stream_socket from a socket of another protocol type. + /** + * This assignment operator moves a stream socket from one object to another. + * + * @param other The other basic_stream_socket object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_socket(const executor_type&) + * constructor. + */ + template + typename enable_if< + is_convertible::value + && is_convertible::value, + basic_stream_socket& + >::type operator=(basic_stream_socket&& other) + { + basic_socket::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the socket. + /** + * This function destroys the socket, cancelling any outstanding asynchronous + * operations associated with the socket as if by calling @c cancel. + */ + ~basic_stream_socket() + { + } + + /// Send some data on the socket. + /** + * This function is used to send data on the stream socket. The function + * call will block until one or more bytes of the data has been sent + * successfully, or an until error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref write function if you need to ensure that all data + * is written before the blocking operation completes. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.send(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on the socket. + /** + * This function is used to send data on the stream socket. The function + * call will block until one or more bytes of the data has been sent + * successfully, or an until error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @returns The number of bytes sent. + * + * @throws asio::system_error Thrown on failure. + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref write function if you need to ensure that all data + * is written before the blocking operation completes. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.send(asio::buffer(data, size), 0); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "send"); + return s; + } + + /// Send some data on the socket. + /** + * This function is used to send data on the stream socket. The function + * call will block until one or more bytes of the data has been sent + * successfully, or an until error occurs. + * + * @param buffers One or more data buffers to be sent on the socket. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes sent. Returns 0 if an error occurred. + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref write function if you need to ensure that all data + * is written before the blocking operation completes. + */ + template + std::size_t send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send data on the stream socket. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_send(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous send. + /** + * This function is used to asynchronously send data on the stream socket. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be sent on the socket. Although + * the buffers object may be copied as necessary, ownership of the underlying + * memory blocks is retained by the caller, which must guarantee that they + * remain valid until the handler is called. + * + * @param flags Flags specifying how the send call is to be made. + * + * @param handler The handler to be called when the send operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes sent. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The send operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To send a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_send(asio::buffer(data, size), 0, handler); + * @endcode + * See the @ref buffer documentation for information on sending multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_send(const ConstBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, buffers, flags); + } + + /// Receive some data on the socket. + /** + * This function is used to receive data on the stream socket. The function + * call will block until one or more bytes of data has been received + * successfully, or until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.receive(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on the socket. + /** + * This function is used to receive data on the stream socket. The function + * call will block until one or more bytes of data has been received + * successfully, or until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @returns The number of bytes received. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.receive(asio::buffer(data, size), 0); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + asio::detail::throw_error(ec, "receive"); + return s; + } + + /// Receive some data on a connected socket. + /** + * This function is used to receive data on the stream socket. The function + * call will block until one or more bytes of data has been received + * successfully, or until an error occurs. + * + * @param buffers One or more buffers into which the data will be received. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes received. Returns 0 if an error occurred. + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + */ + template + std::size_t receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, flags, ec); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive data from the stream + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref async_read function if you need to ensure + * that the requested amount of data is received before the asynchronous + * operation completes. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Start an asynchronous receive. + /** + * This function is used to asynchronously receive data from the stream + * socket. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be received. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param flags Flags specifying how the receive call is to be made. + * + * @param handler The handler to be called when the receive operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes received. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The receive operation may not receive all of the requested number of + * bytes. Consider using the @ref async_read function if you need to ensure + * that the requested amount of data is received before the asynchronous + * operation completes. + * + * @par Example + * To receive into a single data buffer use the @ref buffer function as + * follows: + * @code + * socket.async_receive(asio::buffer(data, size), 0, handler); + * @endcode + * See the @ref buffer documentation for information on receiving into + * multiple buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_receive(const MutableBufferSequence& buffers, + socket_base::message_flags flags, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, buffers, flags); + } + + /// Write some data to the socket. + /** + * This function is used to write data to the stream socket. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the socket. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * socket.write_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "write_some"); + return s; + } + + /// Write some data to the socket. + /** + * This function is used to write data to the stream socket. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the socket. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().send( + this->impl_.get_implementation(), buffers, 0, ec); + } + + /// Start an asynchronous write. + /** + * This function is used to asynchronously write data to the stream socket. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be written to the socket. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The write operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_write_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_send(this), handler, + buffers, socket_base::message_flags(0)); + } + + /// Read some data from the socket. + /** + * This function is used to read data from the stream socket. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * socket.read_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, 0, ec); + asio::detail::throw_error(ec, "read_some"); + return s; + } + + /// Read some data from the socket. + /** + * This function is used to read data from the stream socket. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().receive( + this->impl_.get_implementation(), buffers, 0, ec); + } + + /// Start an asynchronous read. + /** + * This function is used to asynchronously read data from the stream socket. + * The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The read operation may not read all of the requested number of bytes. + * Consider using the @ref async_read function if you need to ensure that the + * requested amount of data is read before the asynchronous operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * socket.async_read_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_receive(this), handler, + buffers, socket_base::message_flags(0)); + } + +private: + class initiate_async_send + { + public: + typedef Executor executor_type; + + explicit initiate_async_send(basic_stream_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_send( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_socket* self_; + }; + + class initiate_async_receive + { + public: + typedef Executor executor_type; + + explicit initiate_async_receive(basic_stream_socket* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, + socket_base::message_flags flags) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_receive( + self_->impl_.get_implementation(), buffers, flags, + handler2.value, self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_socket* self_; + }; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_STREAM_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf.hpp new file mode 100644 index 00000000..7a106721 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf.hpp @@ -0,0 +1,452 @@ +// +// basic_streambuf.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_STREAMBUF_HPP +#define ASIO_BASIC_STREAMBUF_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_IOSTREAM) + +#include +#include +#include +#include +#include +#include "asio/basic_streambuf_fwd.hpp" +#include "asio/buffer.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/throw_exception.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Automatically resizable buffer class based on std::streambuf. +/** + * The @c basic_streambuf class is derived from @c std::streambuf to associate + * the streambuf's input and output sequences with one or more character + * arrays. These character arrays are internal to the @c basic_streambuf + * object, but direct access to the array elements is provided to permit them + * to be used efficiently with I/O operations. Characters written to the output + * sequence of a @c basic_streambuf object are appended to the input sequence + * of the same object. + * + * The @c basic_streambuf class's public interface is intended to permit the + * following implementation strategies: + * + * @li A single contiguous character array, which is reallocated as necessary + * to accommodate changes in the size of the character sequence. This is the + * implementation approach currently used in Asio. + * + * @li A sequence of one or more character arrays, where each array is of the + * same size. Additional character array objects are appended to the sequence + * to accommodate changes in the size of the character sequence. + * + * @li A sequence of one or more character arrays of varying sizes. Additional + * character array objects are appended to the sequence to accommodate changes + * in the size of the character sequence. + * + * The constructor for basic_streambuf accepts a @c size_t argument specifying + * the maximum of the sum of the sizes of the input sequence and output + * sequence. During the lifetime of the @c basic_streambuf object, the following + * invariant holds: + * @code size() <= max_size()@endcode + * Any member function that would, if successful, cause the invariant to be + * violated shall throw an exception of class @c std::length_error. + * + * The constructor for @c basic_streambuf takes an Allocator argument. A copy + * of this argument is used for any memory allocation performed, by the + * constructor and by all member functions, during the lifetime of each @c + * basic_streambuf object. + * + * @par Examples + * Writing directly from an streambuf to a socket: + * @code + * asio::streambuf b; + * std::ostream os(&b); + * os << "Hello, World!\n"; + * + * // try sending some data in input sequence + * size_t n = sock.send(b.data()); + * + * b.consume(n); // sent data is removed from input sequence + * @endcode + * + * Reading from a socket directly into a streambuf: + * @code + * asio::streambuf b; + * + * // reserve 512 bytes in output sequence + * asio::streambuf::mutable_buffers_type bufs = b.prepare(512); + * + * size_t n = sock.receive(bufs); + * + * // received data is "committed" from output sequence to input sequence + * b.commit(n); + * + * std::istream is(&b); + * std::string s; + * is >> s; + * @endcode + */ +#if defined(GENERATING_DOCUMENTATION) +template > +#else +template +#endif +class basic_streambuf + : public std::streambuf, + private noncopyable +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The type used to represent the input sequence as a list of buffers. + typedef implementation_defined const_buffers_type; + + /// The type used to represent the output sequence as a list of buffers. + typedef implementation_defined mutable_buffers_type; +#else + typedef ASIO_CONST_BUFFER const_buffers_type; + typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; +#endif + + /// Construct a basic_streambuf object. + /** + * Constructs a streambuf with the specified maximum size. The initial size + * of the streambuf's input sequence is 0. + */ + explicit basic_streambuf( + std::size_t maximum_size = (std::numeric_limits::max)(), + const Allocator& allocator = Allocator()) + : max_size_(maximum_size), + buffer_(allocator) + { + std::size_t pend = (std::min)(max_size_, buffer_delta); + buffer_.resize((std::max)(pend, 1)); + setg(&buffer_[0], &buffer_[0], &buffer_[0]); + setp(&buffer_[0], &buffer_[0] + pend); + } + + /// Get the size of the input sequence. + /** + * @returns The size of the input sequence. The value is equal to that + * calculated for @c s in the following code: + * @code + * size_t s = 0; + * const_buffers_type bufs = data(); + * const_buffers_type::const_iterator i = bufs.begin(); + * while (i != bufs.end()) + * { + * const_buffer buf(*i++); + * s += buf.size(); + * } + * @endcode + */ + std::size_t size() const ASIO_NOEXCEPT + { + return pptr() - gptr(); + } + + /// Get the maximum size of the basic_streambuf. + /** + * @returns The allowed maximum of the sum of the sizes of the input sequence + * and output sequence. + */ + std::size_t max_size() const ASIO_NOEXCEPT + { + return max_size_; + } + + /// Get the current capacity of the basic_streambuf. + /** + * @returns The current total capacity of the streambuf, i.e. for both the + * input sequence and output sequence. + */ + std::size_t capacity() const ASIO_NOEXCEPT + { + return buffer_.capacity(); + } + + /// Get a list of buffers that represents the input sequence. + /** + * @returns An object of type @c const_buffers_type that satisfies + * ConstBufferSequence requirements, representing all character arrays in the + * input sequence. + * + * @note The returned object is invalidated by any @c basic_streambuf member + * function that modifies the input sequence or output sequence. + */ + const_buffers_type data() const ASIO_NOEXCEPT + { + return asio::buffer(asio::const_buffer(gptr(), + (pptr() - gptr()) * sizeof(char_type))); + } + + /// Get a list of buffers that represents the output sequence, with the given + /// size. + /** + * Ensures that the output sequence can accommodate @c n characters, + * reallocating character array objects as necessary. + * + * @returns An object of type @c mutable_buffers_type that satisfies + * MutableBufferSequence requirements, representing character array objects + * at the start of the output sequence such that the sum of the buffer sizes + * is @c n. + * + * @throws std::length_error If size() + n > max_size(). + * + * @note The returned object is invalidated by any @c basic_streambuf member + * function that modifies the input sequence or output sequence. + */ + mutable_buffers_type prepare(std::size_t n) + { + reserve(n); + return asio::buffer(asio::mutable_buffer( + pptr(), n * sizeof(char_type))); + } + + /// Move characters from the output sequence to the input sequence. + /** + * Appends @c n characters from the start of the output sequence to the input + * sequence. The beginning of the output sequence is advanced by @c n + * characters. + * + * Requires a preceding call prepare(x) where x >= n, and + * no intervening operations that modify the input or output sequence. + * + * @note If @c n is greater than the size of the output sequence, the entire + * output sequence is moved to the input sequence and no error is issued. + */ + void commit(std::size_t n) + { + n = std::min(n, epptr() - pptr()); + pbump(static_cast(n)); + setg(eback(), gptr(), pptr()); + } + + /// Remove characters from the input sequence. + /** + * Removes @c n characters from the beginning of the input sequence. + * + * @note If @c n is greater than the size of the input sequence, the entire + * input sequence is consumed and no error is issued. + */ + void consume(std::size_t n) + { + if (egptr() < pptr()) + setg(&buffer_[0], gptr(), pptr()); + if (gptr() + n > pptr()) + n = pptr() - gptr(); + gbump(static_cast(n)); + } + +protected: + enum { buffer_delta = 128 }; + + /// Override std::streambuf behaviour. + /** + * Behaves according to the specification of @c std::streambuf::underflow(). + */ + int_type underflow() + { + if (gptr() < pptr()) + { + setg(&buffer_[0], gptr(), pptr()); + return traits_type::to_int_type(*gptr()); + } + else + { + return traits_type::eof(); + } + } + + /// Override std::streambuf behaviour. + /** + * Behaves according to the specification of @c std::streambuf::overflow(), + * with the specialisation that @c std::length_error is thrown if appending + * the character to the input sequence would require the condition + * size() > max_size() to be true. + */ + int_type overflow(int_type c) + { + if (!traits_type::eq_int_type(c, traits_type::eof())) + { + if (pptr() == epptr()) + { + std::size_t buffer_size = pptr() - gptr(); + if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta) + { + reserve(max_size_ - buffer_size); + } + else + { + reserve(buffer_delta); + } + } + + *pptr() = traits_type::to_char_type(c); + pbump(1); + return c; + } + + return traits_type::not_eof(c); + } + + void reserve(std::size_t n) + { + // Get current stream positions as offsets. + std::size_t gnext = gptr() - &buffer_[0]; + std::size_t pnext = pptr() - &buffer_[0]; + std::size_t pend = epptr() - &buffer_[0]; + + // Check if there is already enough space in the put area. + if (n <= pend - pnext) + { + return; + } + + // Shift existing contents of get area to start of buffer. + if (gnext > 0) + { + pnext -= gnext; + std::memmove(&buffer_[0], &buffer_[0] + gnext, pnext); + } + + // Ensure buffer is large enough to hold at least the specified size. + if (n > pend - pnext) + { + if (n <= max_size_ && pnext <= max_size_ - n) + { + pend = pnext + n; + buffer_.resize((std::max)(pend, 1)); + } + else + { + std::length_error ex("asio::streambuf too long"); + asio::detail::throw_exception(ex); + } + } + + // Update stream positions. + setg(&buffer_[0], &buffer_[0], &buffer_[0] + pnext); + setp(&buffer_[0] + pnext, &buffer_[0] + pend); + } + +private: + std::size_t max_size_; + std::vector buffer_; + + // Helper function to get the preferred size for reading data. + friend std::size_t read_size_helper( + basic_streambuf& sb, std::size_t max_size) + { + return std::min( + std::max(512, sb.buffer_.capacity() - sb.size()), + std::min(max_size, sb.max_size() - sb.size())); + } +}; + +/// Adapts basic_streambuf to the dynamic buffer sequence type requirements. +#if defined(GENERATING_DOCUMENTATION) +template > +#else +template +#endif +class basic_streambuf_ref +{ +public: + /// The type used to represent the input sequence as a list of buffers. + typedef typename basic_streambuf::const_buffers_type + const_buffers_type; + + /// The type used to represent the output sequence as a list of buffers. + typedef typename basic_streambuf::mutable_buffers_type + mutable_buffers_type; + + /// Construct a basic_streambuf_ref for the given basic_streambuf object. + explicit basic_streambuf_ref(basic_streambuf& sb) + : sb_(sb) + { + } + + /// Copy construct a basic_streambuf_ref. + basic_streambuf_ref(const basic_streambuf_ref& other) ASIO_NOEXCEPT + : sb_(other.sb_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move construct a basic_streambuf_ref. + basic_streambuf_ref(basic_streambuf_ref&& other) ASIO_NOEXCEPT + : sb_(other.sb_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the size of the input sequence. + std::size_t size() const ASIO_NOEXCEPT + { + return sb_.size(); + } + + /// Get the maximum size of the dynamic buffer. + std::size_t max_size() const ASIO_NOEXCEPT + { + return sb_.max_size(); + } + + /// Get the current capacity of the dynamic buffer. + std::size_t capacity() const ASIO_NOEXCEPT + { + return sb_.capacity(); + } + + /// Get a list of buffers that represents the input sequence. + const_buffers_type data() const ASIO_NOEXCEPT + { + return sb_.data(); + } + + /// Get a list of buffers that represents the output sequence, with the given + /// size. + mutable_buffers_type prepare(std::size_t n) + { + return sb_.prepare(n); + } + + /// Move bytes from the output sequence to the input sequence. + void commit(std::size_t n) + { + return sb_.commit(n); + } + + /// Remove characters from the input sequence. + void consume(std::size_t n) + { + return sb_.consume(n); + } + +private: + basic_streambuf& sb_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_BASIC_STREAMBUF_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf_fwd.hpp new file mode 100644 index 00000000..31a4303d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_streambuf_fwd.hpp @@ -0,0 +1,36 @@ +// +// basic_streambuf_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_STREAMBUF_FWD_HPP +#define ASIO_BASIC_STREAMBUF_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_IOSTREAM) + +#include + +namespace asio { + +template > +class basic_streambuf; + +template > +class basic_streambuf_ref; + +} // namespace asio + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_BASIC_STREAMBUF_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_waitable_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_waitable_timer.hpp new file mode 100644 index 00000000..635b6687 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/basic_waitable_timer.hpp @@ -0,0 +1,763 @@ +// +// basic_waitable_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BASIC_WAITABLE_TIMER_HPP +#define ASIO_BASIC_WAITABLE_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/chrono_time_traits.hpp" +#include "asio/detail/deadline_timer_service.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/executor.hpp" +#include "asio/wait_traits.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) +#define ASIO_BASIC_WAITABLE_TIMER_FWD_DECL + +// Forward declaration with defaulted arguments. +template , + typename Executor = executor> +class basic_waitable_timer; + +#endif // !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) + +/// Provides waitable timer functionality. +/** + * The basic_waitable_timer class template provides the ability to perform a + * blocking or asynchronous wait for a timer to expire. + * + * A waitable timer is always in one of two states: "expired" or "not expired". + * If the wait() or async_wait() function is called on an expired timer, the + * wait operation will complete immediately. + * + * Most applications will use one of the asio::steady_timer, + * asio::system_timer or asio::high_resolution_timer typedefs. + * + * @note This waitable timer functionality is for use with the C++11 standard + * library's @c <chrono> facility, or with the Boost.Chrono library. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Examples + * Performing a blocking wait (C++11): + * @code + * // Construct a timer without setting an expiry time. + * asio::steady_timer timer(my_context); + * + * // Set an expiry time relative to now. + * timer.expires_after(std::chrono::seconds(5)); + * + * // Wait for the timer to expire. + * timer.wait(); + * @endcode + * + * @par + * Performing an asynchronous wait (C++11): + * @code + * void handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Timer expired. + * } + * } + * + * ... + * + * // Construct a timer with an absolute expiry time. + * asio::steady_timer timer(my_context, + * std::chrono::steady_clock::now() + std::chrono::seconds(60)); + * + * // Start an asynchronous wait. + * timer.async_wait(handler); + * @endcode + * + * @par Changing an active waitable timer's expiry time + * + * Changing the expiry time of a timer while there are pending asynchronous + * waits causes those wait operations to be cancelled. To ensure that the action + * associated with the timer is performed only once, use something like this: + * used: + * + * @code + * void on_some_event() + * { + * if (my_timer.expires_after(seconds(5)) > 0) + * { + * // We managed to cancel the timer. Start new asynchronous wait. + * my_timer.async_wait(on_timeout); + * } + * else + * { + * // Too late, timer has already expired! + * } + * } + * + * void on_timeout(const asio::error_code& e) + * { + * if (e != asio::error::operation_aborted) + * { + * // Timer was not cancelled, take necessary action. + * } + * } + * @endcode + * + * @li The asio::basic_waitable_timer::expires_after() function + * cancels any pending asynchronous waits, and returns the number of + * asynchronous waits that were cancelled. If it returns 0 then you were too + * late and the wait handler has already been executed, or will soon be + * executed. If it returns 1 then the wait handler was successfully cancelled. + * + * @li If a wait handler is cancelled, the asio::error_code passed to + * it contains the value asio::error::operation_aborted. + */ +template +class basic_waitable_timer +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the timer type to another executor. + template + struct rebind_executor + { + /// The timer type when rebound to the specified executor. + typedef basic_waitable_timer other; + }; + + /// The clock type. + typedef Clock clock_type; + + /// The duration type of the clock. + typedef typename clock_type::duration duration; + + /// The time point type of the clock. + typedef typename clock_type::time_point time_point; + + /// The wait traits type. + typedef WaitTraits traits_type; + + /// Constructor. + /** + * This constructor creates a timer without setting an expiry time. The + * expires_at() or expires_after() functions must be called to set an expiry + * time before the timer can be waited on. + * + * @param ex The I/O executor that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + */ + explicit basic_waitable_timer(const executor_type& ex) + : impl_(ex) + { + } + + /// Constructor. + /** + * This constructor creates a timer without setting an expiry time. The + * expires_at() or expires_after() functions must be called to set an expiry + * time before the timer can be waited on. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + */ + template + explicit basic_waitable_timer(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param ex The I/O executor object that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, expressed + * as an absolute time. + */ + basic_waitable_timer(const executor_type& ex, const time_point& expiry_time) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + } + + /// Constructor to set a particular expiry time as an absolute time. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, expressed + * as an absolute time. + */ + template + explicit basic_waitable_timer(ExecutionContext& context, + const time_point& expiry_time, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().expires_at(impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + } + + /// Constructor to set a particular expiry time relative to now. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param ex The I/O executor that the timer will use, by default, to + * dispatch handlers for any asynchronous operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, relative to + * now. + */ + basic_waitable_timer(const executor_type& ex, const duration& expiry_time) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().expires_after( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_after"); + } + + /// Constructor to set a particular expiry time relative to now. + /** + * This constructor creates a timer and sets the expiry time. + * + * @param context An execution context which provides the I/O executor that + * the timer will use, by default, to dispatch handlers for any asynchronous + * operations performed on the timer. + * + * @param expiry_time The expiry time to be used for the timer, relative to + * now. + */ + template + explicit basic_waitable_timer(ExecutionContext& context, + const duration& expiry_time, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().expires_after( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_after"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_waitable_timer from another. + /** + * This constructor moves a timer from one object to another. + * + * @param other The other basic_waitable_timer object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_waitable_timer(const executor_type&) + * constructor. + */ + basic_waitable_timer(basic_waitable_timer&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_waitable_timer from another. + /** + * This assignment operator moves a timer from one object to another. Cancels + * any outstanding asynchronous operations associated with the target object. + * + * @param other The other basic_waitable_timer object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_waitable_timer(const executor_type&) + * constructor. + */ + basic_waitable_timer& operator=(basic_waitable_timer&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the timer. + /** + * This function destroys the timer, cancelling any outstanding asynchronous + * wait operations associated with the timer as if by calling @c cancel. + */ + ~basic_waitable_timer() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Cancel any asynchronous operations that are waiting on the timer. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the timer. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel() + { + asio::error_code ec; + std::size_t s = impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + return s; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Cancel any asynchronous + /// operations that are waiting on the timer. + /** + * This function forces the completion of any pending asynchronous wait + * operations against the timer. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when cancel() is called, then the + * handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel(asio::error_code& ec) + { + return impl_.get_service().cancel(impl_.get_implementation(), ec); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Cancels one asynchronous operation that is waiting on the timer. + /** + * This function forces the completion of one pending asynchronous wait + * operation against the timer. Handlers are cancelled in FIFO order. The + * handler for the cancelled operation will be invoked with the + * asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @return The number of asynchronous operations that were cancelled. That is, + * either 0 or 1. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when cancel_one() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel_one() + { + asio::error_code ec; + std::size_t s = impl_.get_service().cancel_one( + impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel_one"); + return s; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Cancels one asynchronous + /// operation that is waiting on the timer. + /** + * This function forces the completion of one pending asynchronous wait + * operation against the timer. Handlers are cancelled in FIFO order. The + * handler for the cancelled operation will be invoked with the + * asio::error::operation_aborted error code. + * + * Cancelling the timer does not change the expiry time. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. That is, + * either 0 or 1. + * + * @note If the timer has already expired when cancel_one() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t cancel_one(asio::error_code& ec) + { + return impl_.get_service().cancel_one(impl_.get_implementation(), ec); + } + + /// (Deprecated: Use expiry().) Get the timer's expiry time as an absolute + /// time. + /** + * This function may be used to obtain the timer's current expiry time. + * Whether the timer has expired or not does not affect this value. + */ + time_point expires_at() const + { + return impl_.get_service().expires_at(impl_.get_implementation()); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the timer's expiry time as an absolute time. + /** + * This function may be used to obtain the timer's current expiry time. + * Whether the timer has expired or not does not affect this value. + */ + time_point expiry() const + { + return impl_.get_service().expiry(impl_.get_implementation()); + } + + /// Set the timer's expiry time as an absolute time. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when expires_at() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_at(const time_point& expiry_time) + { + asio::error_code ec; + std::size_t s = impl_.get_service().expires_at( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_at"); + return s; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Set the timer's expiry time as + /// an absolute time. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when expires_at() is called, then + * the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_at(const time_point& expiry_time, + asio::error_code& ec) + { + return impl_.get_service().expires_at( + impl_.get_implementation(), expiry_time, ec); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Set the timer's expiry time relative to now. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when expires_after() is called, + * then the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_after(const duration& expiry_time) + { + asio::error_code ec; + std::size_t s = impl_.get_service().expires_after( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_after"); + return s; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use expiry().) Get the timer's expiry time relative to now. + /** + * This function may be used to obtain the timer's current expiry time. + * Whether the timer has expired or not does not affect this value. + */ + duration expires_from_now() const + { + return impl_.get_service().expires_from_now(impl_.get_implementation()); + } + + /// (Deprecated: Use expires_after().) Set the timer's expiry time relative + /// to now. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @return The number of asynchronous operations that were cancelled. + * + * @throws asio::system_error Thrown on failure. + * + * @note If the timer has already expired when expires_from_now() is called, + * then the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_from_now(const duration& expiry_time) + { + asio::error_code ec; + std::size_t s = impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + asio::detail::throw_error(ec, "expires_from_now"); + return s; + } + + /// (Deprecated: Use expires_after().) Set the timer's expiry time relative + /// to now. + /** + * This function sets the expiry time. Any pending asynchronous wait + * operations will be cancelled. The handler for each cancelled operation will + * be invoked with the asio::error::operation_aborted error code. + * + * @param expiry_time The expiry time to be used for the timer. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of asynchronous operations that were cancelled. + * + * @note If the timer has already expired when expires_from_now() is called, + * then the handlers for asynchronous wait operations will: + * + * @li have already been invoked; or + * + * @li have been queued for invocation in the near future. + * + * These handlers can no longer be cancelled, and therefore are passed an + * error code that indicates the successful completion of the wait operation. + */ + std::size_t expires_from_now(const duration& expiry_time, + asio::error_code& ec) + { + return impl_.get_service().expires_from_now( + impl_.get_implementation(), expiry_time, ec); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Perform a blocking wait on the timer. + /** + * This function is used to wait for the timer to expire. This function + * blocks and does not return until the timer has expired. + * + * @throws asio::system_error Thrown on failure. + */ + void wait() + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Perform a blocking wait on the timer. + /** + * This function is used to wait for the timer to expire. This function + * blocks and does not return until the timer has expired. + * + * @param ec Set to indicate what error occurred, if any. + */ + void wait(asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), ec); + } + + /// Start an asynchronous wait on the timer. + /** + * This function may be used to initiate an asynchronous wait against the + * timer. It always returns immediately. + * + * For each call to async_wait(), the supplied handler will be called exactly + * once. The handler will be called when: + * + * @li The timer has expired. + * + * @li The timer was cancelled, in which case the handler is passed the error + * code asio::error::operation_aborted. + * + * @param handler The handler to be called when the timer expires. Copies + * will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait( + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler); + } + +private: + // Disallow copying and assignment. + basic_waitable_timer(const basic_waitable_timer&) ASIO_DELETED; + basic_waitable_timer& operator=( + const basic_waitable_timer&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_waitable_timer* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_waitable_timer* self_; + }; + + detail::io_object_impl< + detail::deadline_timer_service< + detail::chrono_time_traits >, + executor_type > impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BASIC_WAITABLE_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/bind_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/bind_executor.hpp new file mode 100644 index 00000000..fbcf6588 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/bind_executor.hpp @@ -0,0 +1,580 @@ +// +// bind_executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BIND_EXECUTOR_HPP +#define ASIO_BIND_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/variadic_templates.hpp" +#include "asio/associated_executor.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/async_result.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" +#include "asio/uses_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct executor_binder_check +{ + typedef void type; +}; + +// Helper to automatically define nested typedef result_type. + +template +struct executor_binder_result_type +{ +protected: + typedef void result_type_or_void; +}; + +template +struct executor_binder_result_type::type> +{ + typedef typename T::result_type result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +template +struct executor_binder_result_type +{ + typedef R result_type; +protected: + typedef result_type result_type_or_void; +}; + +// Helper to automatically define nested typedef argument_type. + +template +struct executor_binder_argument_type {}; + +template +struct executor_binder_argument_type::type> +{ + typedef typename T::argument_type argument_type; +}; + +template +struct executor_binder_argument_type +{ + typedef A1 argument_type; +}; + +template +struct executor_binder_argument_type +{ + typedef A1 argument_type; +}; + +// Helper to automatically define nested typedefs first_argument_type and +// second_argument_type. + +template +struct executor_binder_argument_types {}; + +template +struct executor_binder_argument_types::type> +{ + typedef typename T::first_argument_type first_argument_type; + typedef typename T::second_argument_type second_argument_type; +}; + +template +struct executor_binder_argument_type +{ + typedef A1 first_argument_type; + typedef A2 second_argument_type; +}; + +template +struct executor_binder_argument_type +{ + typedef A1 first_argument_type; + typedef A2 second_argument_type; +}; + +// Helper to: +// - Apply the empty base optimisation to the executor. +// - Perform uses_executor construction of the target type, if required. + +template +class executor_binder_base; + +template +class executor_binder_base + : protected Executor +{ +protected: + template + executor_binder_base(ASIO_MOVE_ARG(E) e, ASIO_MOVE_ARG(U) u) + : executor_(ASIO_MOVE_CAST(E)(e)), + target_(executor_arg_t(), executor_, ASIO_MOVE_CAST(U)(u)) + { + } + + Executor executor_; + T target_; +}; + +template +class executor_binder_base +{ +protected: + template + executor_binder_base(ASIO_MOVE_ARG(E) e, ASIO_MOVE_ARG(U) u) + : executor_(ASIO_MOVE_CAST(E)(e)), + target_(ASIO_MOVE_CAST(U)(u)) + { + } + + Executor executor_; + T target_; +}; + +// Helper to enable SFINAE on zero-argument operator() below. + +template +struct executor_binder_result_of0 +{ + typedef void type; +}; + +template +struct executor_binder_result_of0::type>::type> +{ + typedef typename result_of::type type; +}; + +} // namespace detail + +/// A call wrapper type to bind an executor of type @c Executor to an object of +/// type @c T. +template +class executor_binder +#if !defined(GENERATING_DOCUMENTATION) + : public detail::executor_binder_result_type, + public detail::executor_binder_argument_type, + public detail::executor_binder_argument_types, + private detail::executor_binder_base< + T, Executor, uses_executor::value> +#endif // !defined(GENERATING_DOCUMENTATION) +{ +public: + /// The type of the target object. + typedef T target_type; + + /// The type of the associated executor. + typedef Executor executor_type; + +#if defined(GENERATING_DOCUMENTATION) + /// The return type if a function. + /** + * The type of @c result_type is based on the type @c T of the wrapper's + * target object: + * + * @li if @c T is a pointer to function type, @c result_type is a synonym for + * the return type of @c T; + * + * @li if @c T is a class type with a member type @c result_type, then @c + * result_type is a synonym for @c T::result_type; + * + * @li otherwise @c result_type is not defined. + */ + typedef see_below result_type; + + /// The type of the function's argument. + /** + * The type of @c argument_type is based on the type @c T of the wrapper's + * target object: + * + * @li if @c T is a pointer to a function type accepting a single argument, + * @c argument_type is a synonym for the return type of @c T; + * + * @li if @c T is a class type with a member type @c argument_type, then @c + * argument_type is a synonym for @c T::argument_type; + * + * @li otherwise @c argument_type is not defined. + */ + typedef see_below argument_type; + + /// The type of the function's first argument. + /** + * The type of @c first_argument_type is based on the type @c T of the + * wrapper's target object: + * + * @li if @c T is a pointer to a function type accepting two arguments, @c + * first_argument_type is a synonym for the return type of @c T; + * + * @li if @c T is a class type with a member type @c first_argument_type, + * then @c first_argument_type is a synonym for @c T::first_argument_type; + * + * @li otherwise @c first_argument_type is not defined. + */ + typedef see_below first_argument_type; + + /// The type of the function's second argument. + /** + * The type of @c second_argument_type is based on the type @c T of the + * wrapper's target object: + * + * @li if @c T is a pointer to a function type accepting two arguments, @c + * second_argument_type is a synonym for the return type of @c T; + * + * @li if @c T is a class type with a member type @c first_argument_type, + * then @c second_argument_type is a synonym for @c T::second_argument_type; + * + * @li otherwise @c second_argument_type is not defined. + */ + typedef see_below second_argument_type; +#endif // defined(GENERATING_DOCUMENTATION) + + /// Construct an executor wrapper for the specified object. + /** + * This constructor is only valid if the type @c T is constructible from type + * @c U. + */ + template + executor_binder(executor_arg_t, const executor_type& e, + ASIO_MOVE_ARG(U) u) + : base_type(e, ASIO_MOVE_CAST(U)(u)) + { + } + + /// Copy constructor. + executor_binder(const executor_binder& other) + : base_type(other.get_executor(), other.get()) + { + } + + /// Construct a copy, but specify a different executor. + executor_binder(executor_arg_t, const executor_type& e, + const executor_binder& other) + : base_type(e, other.get()) + { + } + + /// Construct a copy of a different executor wrapper type. + /** + * This constructor is only valid if the @c Executor type is constructible + * from type @c OtherExecutor, and the type @c T is constructible from type + * @c U. + */ + template + executor_binder(const executor_binder& other) + : base_type(other.get_executor(), other.get()) + { + } + + /// Construct a copy of a different executor wrapper type, but specify a + /// different executor. + /** + * This constructor is only valid if the type @c T is constructible from type + * @c U. + */ + template + executor_binder(executor_arg_t, const executor_type& e, + const executor_binder& other) + : base_type(e, other.get()) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Move constructor. + executor_binder(executor_binder&& other) + : base_type(ASIO_MOVE_CAST(executor_type)(other.get_executor()), + ASIO_MOVE_CAST(T)(other.get())) + { + } + + /// Move construct the target object, but specify a different executor. + executor_binder(executor_arg_t, const executor_type& e, + executor_binder&& other) + : base_type(e, ASIO_MOVE_CAST(T)(other.get())) + { + } + + /// Move construct from a different executor wrapper type. + template + executor_binder(executor_binder&& other) + : base_type(ASIO_MOVE_CAST(OtherExecutor)(other.get_executor()), + ASIO_MOVE_CAST(U)(other.get())) + { + } + + /// Move construct from a different executor wrapper type, but specify a + /// different executor. + template + executor_binder(executor_arg_t, const executor_type& e, + executor_binder&& other) + : base_type(e, ASIO_MOVE_CAST(U)(other.get())) + { + } + +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor. + ~executor_binder() + { + } + + /// Obtain a reference to the target object. + target_type& get() ASIO_NOEXCEPT + { + return this->target_; + } + + /// Obtain a reference to the target object. + const target_type& get() const ASIO_NOEXCEPT + { + return this->target_; + } + + /// Obtain the associated executor. + executor_type get_executor() const ASIO_NOEXCEPT + { + return this->executor_; + } + +#if defined(GENERATING_DOCUMENTATION) + + template auto operator()(Args&& ...); + template auto operator()(Args&& ...) const; + +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + + /// Forwarding function call operator. + template + typename result_of::type operator()( + ASIO_MOVE_ARG(Args)... args) + { + return this->target_(ASIO_MOVE_CAST(Args)(args)...); + } + + /// Forwarding function call operator. + template + typename result_of::type operator()( + ASIO_MOVE_ARG(Args)... args) const + { + return this->target_(ASIO_MOVE_CAST(Args)(args)...); + } + +#elif defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) + + typename detail::executor_binder_result_of0::type operator()() + { + return this->target_(); + } + + typename detail::executor_binder_result_of0::type operator()() const + { + return this->target_(); + } + +#define ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF(n) \ + template \ + typename result_of::type operator()( \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + \ + template \ + typename result_of::type operator()( \ + ASIO_VARIADIC_MOVE_PARAMS(n)) const \ + { \ + return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF) +#undef ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF + +#else // defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) + + typedef typename detail::executor_binder_result_type::result_type_or_void + result_type_or_void; + + result_type_or_void operator()() + { + return this->target_(); + } + + result_type_or_void operator()() const + { + return this->target_(); + } + +#define ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF(n) \ + template \ + result_type_or_void operator()( \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + \ + template \ + result_type_or_void operator()( \ + ASIO_VARIADIC_MOVE_PARAMS(n)) const \ + { \ + return this->target_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF) +#undef ASIO_PRIVATE_BIND_EXECUTOR_CALL_DEF + +#endif // defined(ASIO_HAS_STD_TYPE_TRAITS) && !defined(_MSC_VER) + +private: + typedef detail::executor_binder_base::value> base_type; +}; + +/// Associate an object of type @c T with an executor of type @c Executor. +template +inline executor_binder::type, Executor> +bind_executor(const Executor& ex, ASIO_MOVE_ARG(T) t, + typename enable_if::value>::type* = 0) +{ + return executor_binder::type, Executor>( + executor_arg_t(), ex, ASIO_MOVE_CAST(T)(t)); +} + +/// Associate an object of type @c T with an execution context's executor. +template +inline executor_binder::type, + typename ExecutionContext::executor_type> +bind_executor(ExecutionContext& ctx, ASIO_MOVE_ARG(T) t, + typename enable_if::value>::type* = 0) +{ + return executor_binder::type, + typename ExecutionContext::executor_type>( + executor_arg_t(), ctx.get_executor(), ASIO_MOVE_CAST(T)(t)); +} + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct uses_executor, Executor> + : true_type {}; + +template +class async_result, Signature> +{ +public: + typedef executor_binder< + typename async_result::completion_handler_type, Executor> + completion_handler_type; + + typedef typename async_result::return_type return_type; + + explicit async_result(executor_binder& b) + : target_(b.get()) + { + } + + return_type get() + { + return target_.get(); + } + +private: + async_result(const async_result&) ASIO_DELETED; + async_result& operator=(const async_result&) ASIO_DELETED; + + async_result target_; +}; + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const executor_binder& b, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(b.get(), a); + } +}; + +template +struct associated_executor, Executor1> +{ + typedef Executor type; + + static type get(const executor_binder& b, + const Executor1& = Executor1()) ASIO_NOEXCEPT + { + return b.get_executor(); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BIND_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffer.hpp new file mode 100644 index 00000000..b8a36750 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffer.hpp @@ -0,0 +1,2494 @@ +// +// buffer.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFER_HPP +#define ASIO_BUFFER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include +#include +#include +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/detail/type_traits.hpp" + +#if defined(ASIO_MSVC) && (ASIO_MSVC >= 1700) +# if defined(_HAS_ITERATOR_DEBUGGING) && (_HAS_ITERATOR_DEBUGGING != 0) +# if !defined(ASIO_DISABLE_BUFFER_DEBUGGING) +# define ASIO_ENABLE_BUFFER_DEBUGGING +# endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING) +# endif // defined(_HAS_ITERATOR_DEBUGGING) +#endif // defined(ASIO_MSVC) && (ASIO_MSVC >= 1700) + +#if defined(__GNUC__) +# if defined(_GLIBCXX_DEBUG) +# if !defined(ASIO_DISABLE_BUFFER_DEBUGGING) +# define ASIO_ENABLE_BUFFER_DEBUGGING +# endif // !defined(ASIO_DISABLE_BUFFER_DEBUGGING) +# endif // defined(_GLIBCXX_DEBUG) +#endif // defined(__GNUC__) + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) +# include "asio/detail/functional.hpp" +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + +#if defined(ASIO_HAS_BOOST_WORKAROUND) +# include +# if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) \ + || BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590)) +# define ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND +# endif // BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x582)) + // || BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x590)) +#endif // defined(ASIO_HAS_BOOST_WORKAROUND) + +#if defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND) +# include "asio/detail/type_traits.hpp" +#endif // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class mutable_buffer; +class const_buffer; + +/// Holds a buffer that can be modified. +/** + * The mutable_buffer class provides a safe representation of a buffer that can + * be modified. It does not own the underlying data, and so is cheap to copy or + * assign. + * + * @par Accessing Buffer Contents + * + * The contents of a buffer may be accessed using the @c data() and @c size() + * member functions: + * + * @code asio::mutable_buffer b1 = ...; + * std::size_t s1 = b1.size(); + * unsigned char* p1 = static_cast(b1.data()); + * @endcode + * + * The @c data() member function permits violations of type safety, so uses of + * it in application code should be carefully considered. + */ +class mutable_buffer +{ +public: + /// Construct an empty buffer. + mutable_buffer() ASIO_NOEXCEPT + : data_(0), + size_(0) + { + } + + /// Construct a buffer to represent a given memory range. + mutable_buffer(void* data, std::size_t size) ASIO_NOEXCEPT + : data_(data), + size_(size) + { + } + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + mutable_buffer(void* data, std::size_t size, + asio::detail::function debug_check) + : data_(data), + size_(size), + debug_check_(debug_check) + { + } + + const asio::detail::function& get_debug_check() const + { + return debug_check_; + } +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + + /// Get a pointer to the beginning of the memory range. + void* data() const ASIO_NOEXCEPT + { +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + if (size_ && debug_check_) + debug_check_(); +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + return data_; + } + + /// Get the size of the memory range. + std::size_t size() const ASIO_NOEXCEPT + { + return size_; + } + + /// Move the start of the buffer by the specified number of bytes. + mutable_buffer& operator+=(std::size_t n) ASIO_NOEXCEPT + { + std::size_t offset = n < size_ ? n : size_; + data_ = static_cast(data_) + offset; + size_ -= offset; + return *this; + } + +private: + void* data_; + std::size_t size_; + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + asio::detail::function debug_check_; +#endif // ASIO_ENABLE_BUFFER_DEBUGGING +}; + +#if !defined(ASIO_NO_DEPRECATED) + +/// (Deprecated: Use mutable_buffer.) Adapts a single modifiable buffer so that +/// it meets the requirements of the MutableBufferSequence concept. +class mutable_buffers_1 + : public mutable_buffer +{ +public: + /// The type for each element in the list of buffers. + typedef mutable_buffer value_type; + + /// A random-access iterator type that may be used to read elements. + typedef const mutable_buffer* const_iterator; + + /// Construct to represent a given memory range. + mutable_buffers_1(void* data, std::size_t size) ASIO_NOEXCEPT + : mutable_buffer(data, size) + { + } + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + mutable_buffers_1(void* data, std::size_t size, + asio::detail::function debug_check) + : mutable_buffer(data, size, debug_check) + { + } +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + + /// Construct to represent a single modifiable buffer. + explicit mutable_buffers_1(const mutable_buffer& b) ASIO_NOEXCEPT + : mutable_buffer(b) + { + } + + /// Get a random-access iterator to the first element. + const_iterator begin() const ASIO_NOEXCEPT + { + return this; + } + + /// Get a random-access iterator for one past the last element. + const_iterator end() const ASIO_NOEXCEPT + { + return begin() + 1; + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Holds a buffer that cannot be modified. +/** + * The const_buffer class provides a safe representation of a buffer that cannot + * be modified. It does not own the underlying data, and so is cheap to copy or + * assign. + * + * @par Accessing Buffer Contents + * + * The contents of a buffer may be accessed using the @c data() and @c size() + * member functions: + * + * @code asio::const_buffer b1 = ...; + * std::size_t s1 = b1.size(); + * const unsigned char* p1 = static_cast(b1.data()); + * @endcode + * + * The @c data() member function permits violations of type safety, so uses of + * it in application code should be carefully considered. + */ +class const_buffer +{ +public: + /// Construct an empty buffer. + const_buffer() ASIO_NOEXCEPT + : data_(0), + size_(0) + { + } + + /// Construct a buffer to represent a given memory range. + const_buffer(const void* data, std::size_t size) ASIO_NOEXCEPT + : data_(data), + size_(size) + { + } + + /// Construct a non-modifiable buffer from a modifiable one. + const_buffer(const mutable_buffer& b) ASIO_NOEXCEPT + : data_(b.data()), + size_(b.size()) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , debug_check_(b.get_debug_check()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + { + } + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + const_buffer(const void* data, std::size_t size, + asio::detail::function debug_check) + : data_(data), + size_(size), + debug_check_(debug_check) + { + } + + const asio::detail::function& get_debug_check() const + { + return debug_check_; + } +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + + /// Get a pointer to the beginning of the memory range. + const void* data() const ASIO_NOEXCEPT + { +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + if (size_ && debug_check_) + debug_check_(); +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + return data_; + } + + /// Get the size of the memory range. + std::size_t size() const ASIO_NOEXCEPT + { + return size_; + } + + /// Move the start of the buffer by the specified number of bytes. + const_buffer& operator+=(std::size_t n) ASIO_NOEXCEPT + { + std::size_t offset = n < size_ ? n : size_; + data_ = static_cast(data_) + offset; + size_ -= offset; + return *this; + } + +private: + const void* data_; + std::size_t size_; + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + asio::detail::function debug_check_; +#endif // ASIO_ENABLE_BUFFER_DEBUGGING +}; + +#if !defined(ASIO_NO_DEPRECATED) + +/// (Deprecated: Use const_buffer.) Adapts a single non-modifiable buffer so +/// that it meets the requirements of the ConstBufferSequence concept. +class const_buffers_1 + : public const_buffer +{ +public: + /// The type for each element in the list of buffers. + typedef const_buffer value_type; + + /// A random-access iterator type that may be used to read elements. + typedef const const_buffer* const_iterator; + + /// Construct to represent a given memory range. + const_buffers_1(const void* data, std::size_t size) ASIO_NOEXCEPT + : const_buffer(data, size) + { + } + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + const_buffers_1(const void* data, std::size_t size, + asio::detail::function debug_check) + : const_buffer(data, size, debug_check) + { + } +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + + /// Construct to represent a single non-modifiable buffer. + explicit const_buffers_1(const const_buffer& b) ASIO_NOEXCEPT + : const_buffer(b) + { + } + + /// Get a random-access iterator to the first element. + const_iterator begin() const ASIO_NOEXCEPT + { + return this; + } + + /// Get a random-access iterator for one past the last element. + const_iterator end() const ASIO_NOEXCEPT + { + return begin() + 1; + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +/// (Deprecated: Use the socket/descriptor wait() and async_wait() member +/// functions.) An implementation of both the ConstBufferSequence and +/// MutableBufferSequence concepts to represent a null buffer sequence. +class null_buffers +{ +public: + /// The type for each element in the list of buffers. + typedef mutable_buffer value_type; + + /// A random-access iterator type that may be used to read elements. + typedef const mutable_buffer* const_iterator; + + /// Get a random-access iterator to the first element. + const_iterator begin() const ASIO_NOEXCEPT + { + return &buf_; + } + + /// Get a random-access iterator for one past the last element. + const_iterator end() const ASIO_NOEXCEPT + { + return &buf_; + } + +private: + mutable_buffer buf_; +}; + +/** @defgroup buffer_sequence_begin asio::buffer_sequence_begin + * + * @brief The asio::buffer_sequence_begin function returns an iterator + * pointing to the first element in a buffer sequence. + */ +/*@{*/ + +/// Get an iterator to the first element in a buffer sequence. +template +inline const mutable_buffer* buffer_sequence_begin(const MutableBuffer& b, + typename enable_if< + is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return static_cast(detail::addressof(b)); +} + +/// Get an iterator to the first element in a buffer sequence. +template +inline const const_buffer* buffer_sequence_begin(const ConstBuffer& b, + typename enable_if< + is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return static_cast(detail::addressof(b)); +} + +#if defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +/// Get an iterator to the first element in a buffer sequence. +template +inline auto buffer_sequence_begin(C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT -> decltype(c.begin()) +{ + return c.begin(); +} + +/// Get an iterator to the first element in a buffer sequence. +template +inline auto buffer_sequence_begin(const C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT -> decltype(c.begin()) +{ + return c.begin(); +} + +#else // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +template +inline typename C::iterator buffer_sequence_begin(C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return c.begin(); +} + +template +inline typename C::const_iterator buffer_sequence_begin(const C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return c.begin(); +} + +#endif // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +/*@}*/ + +/** @defgroup buffer_sequence_end asio::buffer_sequence_end + * + * @brief The asio::buffer_sequence_end function returns an iterator + * pointing to one past the end element in a buffer sequence. + */ +/*@{*/ + +/// Get an iterator to one past the end element in a buffer sequence. +template +inline const mutable_buffer* buffer_sequence_end(const MutableBuffer& b, + typename enable_if< + is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return static_cast(detail::addressof(b)) + 1; +} + +/// Get an iterator to one past the end element in a buffer sequence. +template +inline const const_buffer* buffer_sequence_end(const ConstBuffer& b, + typename enable_if< + is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return static_cast(detail::addressof(b)) + 1; +} + +#if defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +/// Get an iterator to one past the end element in a buffer sequence. +template +inline auto buffer_sequence_end(C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT -> decltype(c.end()) +{ + return c.end(); +} + +/// Get an iterator to one past the end element in a buffer sequence. +template +inline auto buffer_sequence_end(const C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT -> decltype(c.end()) +{ + return c.end(); +} + +#else // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +template +inline typename C::iterator buffer_sequence_end(C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return c.end(); +} + +template +inline typename C::const_iterator buffer_sequence_end(const C& c, + typename enable_if< + !is_convertible::value + && !is_convertible::value + >::type* = 0) ASIO_NOEXCEPT +{ + return c.end(); +} + +#endif // defined(ASIO_HAS_DECLTYPE) || defined(GENERATING_DOCUMENTATION) + +/*@}*/ + +namespace detail { + +// Tag types used to select appropriately optimised overloads. +struct one_buffer {}; +struct multiple_buffers {}; + +// Helper trait to detect single buffers. +template +struct buffer_sequence_cardinality : + conditional< + is_same::value +#if !defined(ASIO_NO_DEPRECATED) + || is_same::value + || is_same::value +#endif // !defined(ASIO_NO_DEPRECATED) + || is_same::value, + one_buffer, multiple_buffers>::type {}; + +template +inline std::size_t buffer_size(one_buffer, + Iterator begin, Iterator) ASIO_NOEXCEPT +{ + return const_buffer(*begin).size(); +} + +template +inline std::size_t buffer_size(multiple_buffers, + Iterator begin, Iterator end) ASIO_NOEXCEPT +{ + std::size_t total_buffer_size = 0; + + Iterator iter = begin; + for (; iter != end; ++iter) + { + const_buffer b(*iter); + total_buffer_size += b.size(); + } + + return total_buffer_size; +} + +} // namespace detail + +/// Get the total number of bytes in a buffer sequence. +/** + * The @c buffer_size function determines the total size of all buffers in the + * buffer sequence, as if computed as follows: + * + * @code size_t total_size = 0; + * auto i = asio::buffer_sequence_begin(buffers); + * auto end = asio::buffer_sequence_end(buffers); + * for (; i != end; ++i) + * { + * const_buffer b(*i); + * total_size += b.size(); + * } + * return total_size; @endcode + * + * The @c BufferSequence template parameter may meet either of the @c + * ConstBufferSequence or @c MutableBufferSequence type requirements. + */ +template +inline std::size_t buffer_size(const BufferSequence& b) ASIO_NOEXCEPT +{ + return detail::buffer_size( + detail::buffer_sequence_cardinality(), + asio::buffer_sequence_begin(b), + asio::buffer_sequence_end(b)); +} + +#if !defined(ASIO_NO_DEPRECATED) + +/** @defgroup buffer_cast asio::buffer_cast + * + * @brief (Deprecated: Use the @c data() member function.) The + * asio::buffer_cast function is used to obtain a pointer to the + * underlying memory region associated with a buffer. + * + * @par Examples: + * + * To access the memory of a non-modifiable buffer, use: + * @code asio::const_buffer b1 = ...; + * const unsigned char* p1 = asio::buffer_cast(b1); + * @endcode + * + * To access the memory of a modifiable buffer, use: + * @code asio::mutable_buffer b2 = ...; + * unsigned char* p2 = asio::buffer_cast(b2); + * @endcode + * + * The asio::buffer_cast function permits violations of type safety, so + * uses of it in application code should be carefully considered. + */ +/*@{*/ + +/// Cast a non-modifiable buffer to a specified pointer to POD type. +template +inline PointerToPodType buffer_cast(const mutable_buffer& b) ASIO_NOEXCEPT +{ + return static_cast(b.data()); +} + +/// Cast a non-modifiable buffer to a specified pointer to POD type. +template +inline PointerToPodType buffer_cast(const const_buffer& b) ASIO_NOEXCEPT +{ + return static_cast(b.data()); +} + +/*@}*/ + +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Create a new modifiable buffer that is offset from the start of another. +/** + * @relates mutable_buffer + */ +inline mutable_buffer operator+(const mutable_buffer& b, + std::size_t n) ASIO_NOEXCEPT +{ + std::size_t offset = n < b.size() ? n : b.size(); + char* new_data = static_cast(b.data()) + offset; + std::size_t new_size = b.size() - offset; + return mutable_buffer(new_data, new_size +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , b.get_debug_check() +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new modifiable buffer that is offset from the start of another. +/** + * @relates mutable_buffer + */ +inline mutable_buffer operator+(std::size_t n, + const mutable_buffer& b) ASIO_NOEXCEPT +{ + return b + n; +} + +/// Create a new non-modifiable buffer that is offset from the start of another. +/** + * @relates const_buffer + */ +inline const_buffer operator+(const const_buffer& b, + std::size_t n) ASIO_NOEXCEPT +{ + std::size_t offset = n < b.size() ? n : b.size(); + const char* new_data = static_cast(b.data()) + offset; + std::size_t new_size = b.size() - offset; + return const_buffer(new_data, new_size +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , b.get_debug_check() +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that is offset from the start of another. +/** + * @relates const_buffer + */ +inline const_buffer operator+(std::size_t n, + const const_buffer& b) ASIO_NOEXCEPT +{ + return b + n; +} + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) +namespace detail { + +template +class buffer_debug_check +{ +public: + buffer_debug_check(Iterator iter) + : iter_(iter) + { + } + + ~buffer_debug_check() + { +#if defined(ASIO_MSVC) && (ASIO_MSVC == 1400) + // MSVC 8's string iterator checking may crash in a std::string::iterator + // object's destructor when the iterator points to an already-destroyed + // std::string object, unless the iterator is cleared first. + iter_ = Iterator(); +#endif // defined(ASIO_MSVC) && (ASIO_MSVC == 1400) + } + + void operator()() + { + (void)*iter_; + } + +private: + Iterator iter_; +}; + +} // namespace detail +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + +/** @defgroup buffer asio::buffer + * + * @brief The asio::buffer function is used to create a buffer object to + * represent raw memory, an array of POD elements, a vector of POD elements, + * or a std::string. + * + * A buffer object represents a contiguous region of memory as a 2-tuple + * consisting of a pointer and size in bytes. A tuple of the form {void*, + * size_t} specifies a mutable (modifiable) region of memory. Similarly, a + * tuple of the form {const void*, size_t} specifies a const + * (non-modifiable) region of memory. These two forms correspond to the classes + * mutable_buffer and const_buffer, respectively. To mirror C++'s conversion + * rules, a mutable_buffer is implicitly convertible to a const_buffer, and the + * opposite conversion is not permitted. + * + * The simplest use case involves reading or writing a single buffer of a + * specified size: + * + * @code sock.send(asio::buffer(data, size)); @endcode + * + * In the above example, the return value of asio::buffer meets the + * requirements of the ConstBufferSequence concept so that it may be directly + * passed to the socket's write function. A buffer created for modifiable + * memory also meets the requirements of the MutableBufferSequence concept. + * + * An individual buffer may be created from a builtin array, std::vector, + * std::array or boost::array of POD elements. This helps prevent buffer + * overruns by automatically determining the size of the buffer: + * + * @code char d1[128]; + * size_t bytes_transferred = sock.receive(asio::buffer(d1)); + * + * std::vector d2(128); + * bytes_transferred = sock.receive(asio::buffer(d2)); + * + * std::array d3; + * bytes_transferred = sock.receive(asio::buffer(d3)); + * + * boost::array d4; + * bytes_transferred = sock.receive(asio::buffer(d4)); @endcode + * + * In all three cases above, the buffers created are exactly 128 bytes long. + * Note that a vector is @e never automatically resized when creating or using + * a buffer. The buffer size is determined using the vector's size() + * member function, and not its capacity. + * + * @par Accessing Buffer Contents + * + * The contents of a buffer may be accessed using the @c data() and @c size() + * member functions: + * + * @code asio::mutable_buffer b1 = ...; + * std::size_t s1 = b1.size(); + * unsigned char* p1 = static_cast(b1.data()); + * + * asio::const_buffer b2 = ...; + * std::size_t s2 = b2.size(); + * const void* p2 = b2.data(); @endcode + * + * The @c data() member function permits violations of type safety, so + * uses of it in application code should be carefully considered. + * + * For convenience, a @ref buffer_size function is provided that works with + * both buffers and buffer sequences (that is, types meeting the + * ConstBufferSequence or MutableBufferSequence type requirements). In this + * case, the function returns the total size of all buffers in the sequence. + * + * @par Buffer Copying + * + * The @ref buffer_copy function may be used to copy raw bytes between + * individual buffers and buffer sequences. +* + * In particular, when used with the @ref buffer_size function, the @ref + * buffer_copy function can be used to linearise a sequence of buffers. For + * example: + * + * @code vector buffers = ...; + * + * vector data(asio::buffer_size(buffers)); + * asio::buffer_copy(asio::buffer(data), buffers); @endcode + * + * Note that @ref buffer_copy is implemented in terms of @c memcpy, and + * consequently it cannot be used to copy between overlapping memory regions. + * + * @par Buffer Invalidation + * + * A buffer object does not have any ownership of the memory it refers to. It + * is the responsibility of the application to ensure the memory region remains + * valid until it is no longer required for an I/O operation. When the memory + * is no longer available, the buffer is said to have been invalidated. + * + * For the asio::buffer overloads that accept an argument of type + * std::vector, the buffer objects returned are invalidated by any vector + * operation that also invalidates all references, pointers and iterators + * referring to the elements in the sequence (C++ Std, 23.2.4) + * + * For the asio::buffer overloads that accept an argument of type + * std::basic_string, the buffer objects returned are invalidated according to + * the rules defined for invalidation of references, pointers and iterators + * referring to elements of the sequence (C++ Std, 21.3). + * + * @par Buffer Arithmetic + * + * Buffer objects may be manipulated using simple arithmetic in a safe way + * which helps prevent buffer overruns. Consider an array initialised as + * follows: + * + * @code boost::array a = { 'a', 'b', 'c', 'd', 'e' }; @endcode + * + * A buffer object @c b1 created using: + * + * @code b1 = asio::buffer(a); @endcode + * + * represents the entire array, { 'a', 'b', 'c', 'd', 'e' }. An + * optional second argument to the asio::buffer function may be used to + * limit the size, in bytes, of the buffer: + * + * @code b2 = asio::buffer(a, 3); @endcode + * + * such that @c b2 represents the data { 'a', 'b', 'c' }. Even if the + * size argument exceeds the actual size of the array, the size of the buffer + * object created will be limited to the array size. + * + * An offset may be applied to an existing buffer to create a new one: + * + * @code b3 = b1 + 2; @endcode + * + * where @c b3 will set to represent { 'c', 'd', 'e' }. If the offset + * exceeds the size of the existing buffer, the newly created buffer will be + * empty. + * + * Both an offset and size may be specified to create a buffer that corresponds + * to a specific range of bytes within an existing buffer: + * + * @code b4 = asio::buffer(b1 + 1, 3); @endcode + * + * so that @c b4 will refer to the bytes { 'b', 'c', 'd' }. + * + * @par Buffers and Scatter-Gather I/O + * + * To read or write using multiple buffers (i.e. scatter-gather I/O), multiple + * buffer objects may be assigned into a container that supports the + * MutableBufferSequence (for read) or ConstBufferSequence (for write) concepts: + * + * @code + * char d1[128]; + * std::vector d2(128); + * boost::array d3; + * + * boost::array bufs1 = { + * asio::buffer(d1), + * asio::buffer(d2), + * asio::buffer(d3) }; + * bytes_transferred = sock.receive(bufs1); + * + * std::vector bufs2; + * bufs2.push_back(asio::buffer(d1)); + * bufs2.push_back(asio::buffer(d2)); + * bufs2.push_back(asio::buffer(d3)); + * bytes_transferred = sock.send(bufs2); @endcode + */ +/*@{*/ + +#if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +# define ASIO_MUTABLE_BUFFER mutable_buffer +# define ASIO_CONST_BUFFER const_buffer +#else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) +# define ASIO_MUTABLE_BUFFER mutable_buffers_1 +# define ASIO_CONST_BUFFER const_buffers_1 +#endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) + +/// Create a new modifiable buffer from an existing buffer. +/** + * @returns mutable_buffer(b). + */ +inline ASIO_MUTABLE_BUFFER buffer( + const mutable_buffer& b) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(b); +} + +/// Create a new modifiable buffer from an existing buffer. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * b.data(), + * min(b.size(), max_size_in_bytes)); @endcode + */ +inline ASIO_MUTABLE_BUFFER buffer(const mutable_buffer& b, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER( + mutable_buffer(b.data(), + b.size() < max_size_in_bytes + ? b.size() : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , b.get_debug_check() +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + )); +} + +/// Create a new non-modifiable buffer from an existing buffer. +/** + * @returns const_buffer(b). + */ +inline ASIO_CONST_BUFFER buffer( + const const_buffer& b) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(b); +} + +/// Create a new non-modifiable buffer from an existing buffer. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * b.data(), + * min(b.size(), max_size_in_bytes)); @endcode + */ +inline ASIO_CONST_BUFFER buffer(const const_buffer& b, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(b.data(), + b.size() < max_size_in_bytes + ? b.size() : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , b.get_debug_check() +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new modifiable buffer that represents the given memory range. +/** + * @returns mutable_buffer(data, size_in_bytes). + */ +inline ASIO_MUTABLE_BUFFER buffer(void* data, + std::size_t size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data, size_in_bytes); +} + +/// Create a new non-modifiable buffer that represents the given memory range. +/** + * @returns const_buffer(data, size_in_bytes). + */ +inline ASIO_CONST_BUFFER buffer(const void* data, + std::size_t size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data, size_in_bytes); +} + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * static_cast(data), + * N * sizeof(PodType)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer(PodType (&data)[N]) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data, N * sizeof(PodType)); +} + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * static_cast(data), + * min(N * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer(PodType (&data)[N], + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data, + N * sizeof(PodType) < max_size_in_bytes + ? N * sizeof(PodType) : max_size_in_bytes); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * static_cast(data), + * N * sizeof(PodType)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + const PodType (&data)[N]) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data, N * sizeof(PodType)); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * static_cast(data), + * min(N * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer(const PodType (&data)[N], + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data, + N * sizeof(PodType) < max_size_in_bytes + ? N * sizeof(PodType) : max_size_in_bytes); +} + +#if defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND) + +// Borland C++ and Sun Studio think the overloads: +// +// unspecified buffer(boost::array& array ...); +// +// and +// +// unspecified buffer(boost::array& array ...); +// +// are ambiguous. This will be worked around by using a buffer_types traits +// class that contains typedefs for the appropriate buffer and container +// classes, based on whether PodType is const or non-const. + +namespace detail { + +template +struct buffer_types_base; + +template <> +struct buffer_types_base +{ + typedef mutable_buffer buffer_type; + typedef ASIO_MUTABLE_BUFFER container_type; +}; + +template <> +struct buffer_types_base +{ + typedef const_buffer buffer_type; + typedef ASIO_CONST_BUFFER container_type; +}; + +template +struct buffer_types + : public buffer_types_base::value> +{ +}; + +} // namespace detail + +template +inline typename detail::buffer_types::container_type +buffer(boost::array& data) ASIO_NOEXCEPT +{ + typedef typename asio::detail::buffer_types::buffer_type + buffer_type; + typedef typename asio::detail::buffer_types::container_type + container_type; + return container_type( + buffer_type(data.c_array(), data.size() * sizeof(PodType))); +} + +template +inline typename detail::buffer_types::container_type +buffer(boost::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + typedef typename asio::detail::buffer_types::buffer_type + buffer_type; + typedef typename asio::detail::buffer_types::container_type + container_type; + return container_type( + buffer_type(data.c_array(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes)); +} + +#else // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND) + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer( + boost::array& data) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER( + data.c_array(), data.size() * sizeof(PodType)); +} + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer(boost::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.c_array(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + boost::array& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer(boost::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +#endif // defined(ASIO_ENABLE_ARRAY_BUFFER_WORKAROUND) + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + const boost::array& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer(const boost::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +#if defined(ASIO_HAS_STD_ARRAY) || defined(GENERATING_DOCUMENTATION) + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer( + std::array& data) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.data(), data.size() * sizeof(PodType)); +} + +/// Create a new modifiable buffer that represents the given POD array. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_MUTABLE_BUFFER buffer(std::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.data(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + std::array& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer(std::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * data.size() * sizeof(PodType)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + const std::array& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(PodType)); +} + +/// Create a new non-modifiable buffer that represents the given POD array. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer(const std::array& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes); +} + +#endif // defined(ASIO_HAS_STD_ARRAY) || defined(GENERATING_DOCUMENTATION) + +/// Create a new modifiable buffer that represents the given POD vector. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.size() ? &data[0] : 0, + * data.size() * sizeof(PodType)); @endcode + * + * @note The buffer is invalidated by any vector operation that would also + * invalidate iterators. + */ +template +inline ASIO_MUTABLE_BUFFER buffer( + std::vector& data) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER( + data.size() ? &data[0] : 0, data.size() * sizeof(PodType) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::vector::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new modifiable buffer that represents the given POD vector. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.size() ? &data[0] : 0, + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + * + * @note The buffer is invalidated by any vector operation that would also + * invalidate iterators. + */ +template +inline ASIO_MUTABLE_BUFFER buffer(std::vector& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::vector::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that represents the given POD vector. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.size() ? &data[0] : 0, + * data.size() * sizeof(PodType)); @endcode + * + * @note The buffer is invalidated by any vector operation that would also + * invalidate iterators. + */ +template +inline ASIO_CONST_BUFFER buffer( + const std::vector& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER( + data.size() ? &data[0] : 0, data.size() * sizeof(PodType) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::vector::const_iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that represents the given POD vector. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.size() ? &data[0] : 0, + * min(data.size() * sizeof(PodType), max_size_in_bytes)); @endcode + * + * @note The buffer is invalidated by any vector operation that would also + * invalidate iterators. + */ +template +inline ASIO_CONST_BUFFER buffer( + const std::vector& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(PodType) < max_size_in_bytes + ? data.size() * sizeof(PodType) : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::vector::const_iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new modifiable buffer that represents the given string. +/** + * @returns mutable_buffer(data.size() ? &data[0] : 0, + * data.size() * sizeof(Elem)). + * + * @note The buffer is invalidated by any non-const operation called on the + * given string object. + */ +template +inline ASIO_MUTABLE_BUFFER buffer( + std::basic_string& data) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(Elem) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::basic_string::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new modifiable buffer that represents the given string. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.size() ? &data[0] : 0, + * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode + * + * @note The buffer is invalidated by any non-const operation called on the + * given string object. + */ +template +inline ASIO_MUTABLE_BUFFER buffer( + std::basic_string& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_MUTABLE_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(Elem) < max_size_in_bytes + ? data.size() * sizeof(Elem) : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::basic_string::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that represents the given string. +/** + * @returns const_buffer(data.data(), data.size() * sizeof(Elem)). + * + * @note The buffer is invalidated by any non-const operation called on the + * given string object. + */ +template +inline ASIO_CONST_BUFFER buffer( + const std::basic_string& data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), data.size() * sizeof(Elem) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::basic_string::const_iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that represents the given string. +/** + * @returns A const_buffer value equivalent to: + * @code const_buffer( + * data.data(), + * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode + * + * @note The buffer is invalidated by any non-const operation called on the + * given string object. + */ +template +inline ASIO_CONST_BUFFER buffer( + const std::basic_string& data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.data(), + data.size() * sizeof(Elem) < max_size_in_bytes + ? data.size() * sizeof(Elem) : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename std::basic_string::const_iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create a new modifiable buffer that represents the given string_view. +/** + * @returns mutable_buffer(data.size() ? &data[0] : 0, + * data.size() * sizeof(Elem)). + */ +template +inline ASIO_CONST_BUFFER buffer( + basic_string_view data) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(Elem) +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename basic_string_view::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +/// Create a new non-modifiable buffer that represents the given string. +/** + * @returns A mutable_buffer value equivalent to: + * @code mutable_buffer( + * data.size() ? &data[0] : 0, + * min(data.size() * sizeof(Elem), max_size_in_bytes)); @endcode + */ +template +inline ASIO_CONST_BUFFER buffer( + basic_string_view data, + std::size_t max_size_in_bytes) ASIO_NOEXCEPT +{ + return ASIO_CONST_BUFFER(data.size() ? &data[0] : 0, + data.size() * sizeof(Elem) < max_size_in_bytes + ? data.size() * sizeof(Elem) : max_size_in_bytes +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + , detail::buffer_debug_check< + typename basic_string_view::iterator + >(data.begin()) +#endif // ASIO_ENABLE_BUFFER_DEBUGGING + ); +} + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +/*@}*/ + +/// Adapt a basic_string to the DynamicBuffer requirements. +/** + * Requires that sizeof(Elem) == 1. + */ +template +class dynamic_string_buffer +{ +public: + /// The type used to represent a sequence of constant buffers that refers to + /// the underlying memory. + typedef ASIO_CONST_BUFFER const_buffers_type; + + /// The type used to represent a sequence of mutable buffers that refers to + /// the underlying memory. + typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; + + /// Construct a dynamic buffer from a string. + /** + * @param s The string to be used as backing storage for the dynamic buffer. + * The object stores a reference to the string and the user is responsible + * for ensuring that the string object remains valid while the + * dynamic_string_buffer object, and copies of the object, are in use. + * + * @b DynamicBuffer_v1: Any existing data in the string is treated as the + * dynamic buffer's input sequence. + * + * @param maximum_size Specifies a maximum size for the buffer, in bytes. + */ + explicit dynamic_string_buffer(std::basic_string& s, + std::size_t maximum_size = + (std::numeric_limits::max)()) ASIO_NOEXCEPT + : string_(s), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_((std::numeric_limits::max)()), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(maximum_size) + { + } + + /// @b DynamicBuffer_v2: Copy construct a dynamic buffer. + dynamic_string_buffer(const dynamic_string_buffer& other) ASIO_NOEXCEPT + : string_(other.string_), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_(other.size_), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(other.max_size_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move construct a dynamic buffer. + dynamic_string_buffer(dynamic_string_buffer&& other) ASIO_NOEXCEPT + : string_(other.string_), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_(other.size_), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(other.max_size_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// @b DynamicBuffer_v1: Get the size of the input sequence. + /// @b DynamicBuffer_v2: Get the current size of the underlying memory. + /** + * @returns @b DynamicBuffer_v1 The current size of the input sequence. + * @b DynamicBuffer_v2: The current size of the underlying string if less than + * max_size(). Otherwise returns max_size(). + */ + std::size_t size() const ASIO_NOEXCEPT + { +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + if (size_ != (std::numeric_limits::max)()) + return size_; +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + return (std::min)(string_.size(), max_size()); + } + + /// Get the maximum size of the dynamic buffer. + /** + * @returns The allowed maximum size of the underlying memory. + */ + std::size_t max_size() const ASIO_NOEXCEPT + { + return max_size_; + } + + /// Get the maximum size that the buffer may grow to without triggering + /// reallocation. + /** + * @returns The current capacity of the underlying string if less than + * max_size(). Otherwise returns max_size(). + */ + std::size_t capacity() const ASIO_NOEXCEPT + { + return (std::min)(string_.capacity(), max_size()); + } + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + /// @b DynamicBuffer_v1: Get a list of buffers that represents the input + /// sequence. + /** + * @returns An object of type @c const_buffers_type that satisfies + * ConstBufferSequence requirements, representing the basic_string memory in + * the input sequence. + * + * @note The returned object is invalidated by any @c dynamic_string_buffer + * or @c basic_string member function that resizes or erases the string. + */ + const_buffers_type data() const ASIO_NOEXCEPT + { + return const_buffers_type(asio::buffer(string_, size_)); + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + + /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the + /// underlying memory. + /** + * @param pos Position of the first byte to represent in the buffer sequence + * + * @param n The number of bytes to return in the buffer sequence. If the + * underlying memory is shorter, the buffer sequence represents as many bytes + * as are available. + * + * @returns An object of type @c mutable_buffers_type that satisfies + * MutableBufferSequence requirements, representing the basic_string memory. + * + * @note The returned object is invalidated by any @c dynamic_string_buffer + * or @c basic_string member function that resizes or erases the string. + */ + mutable_buffers_type data(std::size_t pos, std::size_t n) ASIO_NOEXCEPT + { + return mutable_buffers_type(asio::buffer( + asio::buffer(string_, max_size_) + pos, n)); + } + + /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the + /// underlying memory. + /** + * @param pos Position of the first byte to represent in the buffer sequence + * + * @param n The number of bytes to return in the buffer sequence. If the + * underlying memory is shorter, the buffer sequence represents as many bytes + * as are available. + * + * @note The returned object is invalidated by any @c dynamic_string_buffer + * or @c basic_string member function that resizes or erases the string. + */ + const_buffers_type data(std::size_t pos, + std::size_t n) const ASIO_NOEXCEPT + { + return const_buffers_type(asio::buffer( + asio::buffer(string_, max_size_) + pos, n)); + } + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + /// @b DynamicBuffer_v1: Get a list of buffers that represents the output + /// sequence, with the given size. + /** + * Ensures that the output sequence can accommodate @c n bytes, resizing the + * basic_string object as necessary. + * + * @returns An object of type @c mutable_buffers_type that satisfies + * MutableBufferSequence requirements, representing basic_string memory + * at the start of the output sequence of size @c n. + * + * @throws std::length_error If size() + n > max_size(). + * + * @note The returned object is invalidated by any @c dynamic_string_buffer + * or @c basic_string member function that modifies the input sequence or + * output sequence. + */ + mutable_buffers_type prepare(std::size_t n) + { + if (size() > max_size() || max_size() - size() < n) + { + std::length_error ex("dynamic_string_buffer too long"); + asio::detail::throw_exception(ex); + } + + if (size_ == (std::numeric_limits::max)()) + size_ = string_.size(); // Enable v1 behaviour. + + string_.resize(size_ + n); + + return asio::buffer(asio::buffer(string_) + size_, n); + } + + /// @b DynamicBuffer_v1: Move bytes from the output sequence to the input + /// sequence. + /** + * @param n The number of bytes to append from the start of the output + * sequence to the end of the input sequence. The remainder of the output + * sequence is discarded. + * + * Requires a preceding call prepare(x) where x >= n, and + * no intervening operations that modify the input or output sequence. + * + * @note If @c n is greater than the size of the output sequence, the entire + * output sequence is moved to the input sequence and no error is issued. + */ + void commit(std::size_t n) + { + size_ += (std::min)(n, string_.size() - size_); + string_.resize(size_); + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + + /// @b DynamicBuffer_v2: Grow the underlying memory by the specified number of + /// bytes. + /** + * Resizes the string to accommodate an additional @c n bytes at the end. + * + * @throws std::length_error If size() + n > max_size(). + */ + void grow(std::size_t n) + { + if (size() > max_size() || max_size() - size() < n) + { + std::length_error ex("dynamic_string_buffer too long"); + asio::detail::throw_exception(ex); + } + + string_.resize(size() + n); + } + + /// @b DynamicBuffer_v2: Shrink the underlying memory by the specified number + /// of bytes. + /** + * Erases @c n bytes from the end of the string by resizing the basic_string + * object. If @c n is greater than the current size of the string, the string + * is emptied. + */ + void shrink(std::size_t n) + { + string_.resize(n > size() ? 0 : size() - n); + } + + /// @b DynamicBuffer_v1: Remove characters from the input sequence. + /// @b DynamicBuffer_v2: Consume the specified number of bytes from the + /// beginning of the underlying memory. + /** + * @b DynamicBuffer_v1: Removes @c n characters from the beginning of the + * input sequence. @note If @c n is greater than the size of the input + * sequence, the entire input sequence is consumed and no error is issued. + * + * @b DynamicBuffer_v2: Erases @c n bytes from the beginning of the string. + * If @c n is greater than the current size of the string, the string is + * emptied. + */ + void consume(std::size_t n) + { +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + if (size_ != (std::numeric_limits::max)()) + { + std::size_t consume_length = (std::min)(n, size_); + string_.erase(0, consume_length); + size_ -= consume_length; + return; + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + string_.erase(0, n); + } + +private: + std::basic_string& string_; +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + std::size_t size_; +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + const std::size_t max_size_; +}; + +/// Adapt a vector to the DynamicBuffer requirements. +/** + * Requires that sizeof(Elem) == 1. + */ +template +class dynamic_vector_buffer +{ +public: + /// The type used to represent a sequence of constant buffers that refers to + /// the underlying memory. + typedef ASIO_CONST_BUFFER const_buffers_type; + + /// The type used to represent a sequence of mutable buffers that refers to + /// the underlying memory. + typedef ASIO_MUTABLE_BUFFER mutable_buffers_type; + + /// Construct a dynamic buffer from a vector. + /** + * @param v The vector to be used as backing storage for the dynamic buffer. + * The object stores a reference to the vector and the user is responsible + * for ensuring that the vector object remains valid while the + * dynamic_vector_buffer object, and copies of the object, are in use. + * + * @param maximum_size Specifies a maximum size for the buffer, in bytes. + */ + explicit dynamic_vector_buffer(std::vector& v, + std::size_t maximum_size = + (std::numeric_limits::max)()) ASIO_NOEXCEPT + : vector_(v), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_((std::numeric_limits::max)()), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(maximum_size) + { + } + + /// @b DynamicBuffer_v2: Copy construct a dynamic buffer. + dynamic_vector_buffer(const dynamic_vector_buffer& other) ASIO_NOEXCEPT + : vector_(other.vector_), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_(other.size_), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(other.max_size_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move construct a dynamic buffer. + dynamic_vector_buffer(dynamic_vector_buffer&& other) ASIO_NOEXCEPT + : vector_(other.vector_), +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + size_(other.size_), +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + max_size_(other.max_size_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// @b DynamicBuffer_v1: Get the size of the input sequence. + /// @b DynamicBuffer_v2: Get the current size of the underlying memory. + /** + * @returns @b DynamicBuffer_v1 The current size of the input sequence. + * @b DynamicBuffer_v2: The current size of the underlying vector if less than + * max_size(). Otherwise returns max_size(). + */ + std::size_t size() const ASIO_NOEXCEPT + { +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + if (size_ != (std::numeric_limits::max)()) + return size_; +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + return (std::min)(vector_.size(), max_size()); + } + + /// Get the maximum size of the dynamic buffer. + /** + * @returns @b DynamicBuffer_v1: The allowed maximum of the sum of the sizes + * of the input sequence and output sequence. @b DynamicBuffer_v2: The allowed + * maximum size of the underlying memory. + */ + std::size_t max_size() const ASIO_NOEXCEPT + { + return max_size_; + } + + /// Get the maximum size that the buffer may grow to without triggering + /// reallocation. + /** + * @returns @b DynamicBuffer_v1: The current total capacity of the buffer, + * i.e. for both the input sequence and output sequence. @b DynamicBuffer_v2: + * The current capacity of the underlying vector if less than max_size(). + * Otherwise returns max_size(). + */ + std::size_t capacity() const ASIO_NOEXCEPT + { + return (std::min)(vector_.capacity(), max_size()); + } + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + /// @b DynamicBuffer_v1: Get a list of buffers that represents the input + /// sequence. + /** + * @returns An object of type @c const_buffers_type that satisfies + * ConstBufferSequence requirements, representing the vector memory in the + * input sequence. + * + * @note The returned object is invalidated by any @c dynamic_vector_buffer + * or @c vector member function that modifies the input sequence or output + * sequence. + */ + const_buffers_type data() const ASIO_NOEXCEPT + { + return const_buffers_type(asio::buffer(vector_, size_)); + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + + /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the + /// underlying memory. + /** + * @param pos Position of the first byte to represent in the buffer sequence + * + * @param n The number of bytes to return in the buffer sequence. If the + * underlying memory is shorter, the buffer sequence represents as many bytes + * as are available. + * + * @returns An object of type @c mutable_buffers_type that satisfies + * MutableBufferSequence requirements, representing the vector memory. + * + * @note The returned object is invalidated by any @c dynamic_vector_buffer + * or @c vector member function that resizes or erases the vector. + */ + mutable_buffers_type data(std::size_t pos, std::size_t n) ASIO_NOEXCEPT + { + return mutable_buffers_type(asio::buffer( + asio::buffer(vector_, max_size_) + pos, n)); + } + + /// @b DynamicBuffer_v2: Get a sequence of buffers that represents the + /// underlying memory. + /** + * @param pos Position of the first byte to represent in the buffer sequence + * + * @param n The number of bytes to return in the buffer sequence. If the + * underlying memory is shorter, the buffer sequence represents as many bytes + * as are available. + * + * @note The returned object is invalidated by any @c dynamic_vector_buffer + * or @c vector member function that resizes or erases the vector. + */ + const_buffers_type data(std::size_t pos, + std::size_t n) const ASIO_NOEXCEPT + { + return const_buffers_type(asio::buffer( + asio::buffer(vector_, max_size_) + pos, n)); + } + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + /// @b DynamicBuffer_v1: Get a list of buffers that represents the output + /// sequence, with the given size. + /** + * Ensures that the output sequence can accommodate @c n bytes, resizing the + * vector object as necessary. + * + * @returns An object of type @c mutable_buffers_type that satisfies + * MutableBufferSequence requirements, representing vector memory at the + * start of the output sequence of size @c n. + * + * @throws std::length_error If size() + n > max_size(). + * + * @note The returned object is invalidated by any @c dynamic_vector_buffer + * or @c vector member function that modifies the input sequence or output + * sequence. + */ + mutable_buffers_type prepare(std::size_t n) + { + if (size () > max_size() || max_size() - size() < n) + { + std::length_error ex("dynamic_vector_buffer too long"); + asio::detail::throw_exception(ex); + } + + if (size_ == (std::numeric_limits::max)()) + size_ = vector_.size(); // Enable v1 behaviour. + + vector_.resize(size_ + n); + + return asio::buffer(asio::buffer(vector_) + size_, n); + } + + /// @b DynamicBuffer_v1: Move bytes from the output sequence to the input + /// sequence. + /** + * @param n The number of bytes to append from the start of the output + * sequence to the end of the input sequence. The remainder of the output + * sequence is discarded. + * + * Requires a preceding call prepare(x) where x >= n, and + * no intervening operations that modify the input or output sequence. + * + * @note If @c n is greater than the size of the output sequence, the entire + * output sequence is moved to the input sequence and no error is issued. + */ + void commit(std::size_t n) + { + size_ += (std::min)(n, vector_.size() - size_); + vector_.resize(size_); + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + + /// @b DynamicBuffer_v2: Grow the underlying memory by the specified number of + /// bytes. + /** + * Resizes the vector to accommodate an additional @c n bytes at the end. + * + * @throws std::length_error If size() + n > max_size(). + */ + void grow(std::size_t n) + { + if (size() > max_size() || max_size() - size() < n) + { + std::length_error ex("dynamic_vector_buffer too long"); + asio::detail::throw_exception(ex); + } + + vector_.resize(size() + n); + } + + /// @b DynamicBuffer_v2: Shrink the underlying memory by the specified number + /// of bytes. + /** + * Erases @c n bytes from the end of the vector by resizing the vector + * object. If @c n is greater than the current size of the vector, the vector + * is emptied. + */ + void shrink(std::size_t n) + { + vector_.resize(n > size() ? 0 : size() - n); + } + + /// @b DynamicBuffer_v1: Remove characters from the input sequence. + /// @b DynamicBuffer_v2: Consume the specified number of bytes from the + /// beginning of the underlying memory. + /** + * @b DynamicBuffer_v1: Removes @c n characters from the beginning of the + * input sequence. @note If @c n is greater than the size of the input + * sequence, the entire input sequence is consumed and no error is issued. + * + * @b DynamicBuffer_v2: Erases @c n bytes from the beginning of the vector. + * If @c n is greater than the current size of the vector, the vector is + * emptied. + */ + void consume(std::size_t n) + { +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + if (size_ != (std::numeric_limits::max)()) + { + std::size_t consume_length = (std::min)(n, size_); + vector_.erase(vector_.begin(), vector_.begin() + consume_length); + size_ -= consume_length; + return; + } +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + vector_.erase(vector_.begin(), vector_.begin() + (std::min)(size(), n)); + } + +private: + std::vector& vector_; +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + std::size_t size_; +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + const std::size_t max_size_; +}; + +/** @defgroup dynamic_buffer asio::dynamic_buffer + * + * @brief The asio::dynamic_buffer function is used to create a + * dynamically resized buffer from a @c std::basic_string or @c std::vector. + */ +/*@{*/ + +/// Create a new dynamic buffer that represents the given string. +/** + * @returns dynamic_string_buffer(data). + */ +template +inline dynamic_string_buffer dynamic_buffer( + std::basic_string& data) ASIO_NOEXCEPT +{ + return dynamic_string_buffer(data); +} + +/// Create a new dynamic buffer that represents the given string. +/** + * @returns dynamic_string_buffer(data, + * max_size). + */ +template +inline dynamic_string_buffer dynamic_buffer( + std::basic_string& data, + std::size_t max_size) ASIO_NOEXCEPT +{ + return dynamic_string_buffer(data, max_size); +} + +/// Create a new dynamic buffer that represents the given vector. +/** + * @returns dynamic_vector_buffer(data). + */ +template +inline dynamic_vector_buffer dynamic_buffer( + std::vector& data) ASIO_NOEXCEPT +{ + return dynamic_vector_buffer(data); +} + +/// Create a new dynamic buffer that represents the given vector. +/** + * @returns dynamic_vector_buffer(data, max_size). + */ +template +inline dynamic_vector_buffer dynamic_buffer( + std::vector& data, + std::size_t max_size) ASIO_NOEXCEPT +{ + return dynamic_vector_buffer(data, max_size); +} + +/*@}*/ + +/** @defgroup buffer_copy asio::buffer_copy + * + * @brief The asio::buffer_copy function is used to copy bytes from a + * source buffer (or buffer sequence) to a target buffer (or buffer sequence). + * + * The @c buffer_copy function is available in two forms: + * + * @li A 2-argument form: @c buffer_copy(target, source) + * + * @li A 3-argument form: @c buffer_copy(target, source, max_bytes_to_copy) + * + * Both forms return the number of bytes actually copied. The number of bytes + * copied is the lesser of: + * + * @li @c buffer_size(target) + * + * @li @c buffer_size(source) + * + * @li @c If specified, @c max_bytes_to_copy. + * + * This prevents buffer overflow, regardless of the buffer sizes used in the + * copy operation. + * + * Note that @ref buffer_copy is implemented in terms of @c memcpy, and + * consequently it cannot be used to copy between overlapping memory regions. + */ +/*@{*/ + +namespace detail { + +inline std::size_t buffer_copy_1(const mutable_buffer& target, + const const_buffer& source) +{ + using namespace std; // For memcpy. + std::size_t target_size = target.size(); + std::size_t source_size = source.size(); + std::size_t n = target_size < source_size ? target_size : source_size; + if (n > 0) + memcpy(target.data(), source.data(), n); + return n; +} + +template +inline std::size_t buffer_copy(one_buffer, one_buffer, + TargetIterator target_begin, TargetIterator, + SourceIterator source_begin, SourceIterator) ASIO_NOEXCEPT +{ + return (buffer_copy_1)(*target_begin, *source_begin); +} + +template +inline std::size_t buffer_copy(one_buffer, one_buffer, + TargetIterator target_begin, TargetIterator, + SourceIterator source_begin, SourceIterator, + std::size_t max_bytes_to_copy) ASIO_NOEXCEPT +{ + return (buffer_copy_1)(*target_begin, + asio::buffer(*source_begin, max_bytes_to_copy)); +} + +template +std::size_t buffer_copy(one_buffer, multiple_buffers, + TargetIterator target_begin, TargetIterator, + SourceIterator source_begin, SourceIterator source_end, + std::size_t max_bytes_to_copy + = (std::numeric_limits::max)()) ASIO_NOEXCEPT +{ + std::size_t total_bytes_copied = 0; + SourceIterator source_iter = source_begin; + + for (mutable_buffer target_buffer( + asio::buffer(*target_begin, max_bytes_to_copy)); + target_buffer.size() && source_iter != source_end; ++source_iter) + { + const_buffer source_buffer(*source_iter); + std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); + total_bytes_copied += bytes_copied; + target_buffer += bytes_copied; + } + + return total_bytes_copied; +} + +template +std::size_t buffer_copy(multiple_buffers, one_buffer, + TargetIterator target_begin, TargetIterator target_end, + SourceIterator source_begin, SourceIterator, + std::size_t max_bytes_to_copy + = (std::numeric_limits::max)()) ASIO_NOEXCEPT +{ + std::size_t total_bytes_copied = 0; + TargetIterator target_iter = target_begin; + + for (const_buffer source_buffer( + asio::buffer(*source_begin, max_bytes_to_copy)); + source_buffer.size() && target_iter != target_end; ++target_iter) + { + mutable_buffer target_buffer(*target_iter); + std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); + total_bytes_copied += bytes_copied; + source_buffer += bytes_copied; + } + + return total_bytes_copied; +} + +template +std::size_t buffer_copy(multiple_buffers, multiple_buffers, + TargetIterator target_begin, TargetIterator target_end, + SourceIterator source_begin, SourceIterator source_end) ASIO_NOEXCEPT +{ + std::size_t total_bytes_copied = 0; + + TargetIterator target_iter = target_begin; + std::size_t target_buffer_offset = 0; + + SourceIterator source_iter = source_begin; + std::size_t source_buffer_offset = 0; + + while (target_iter != target_end && source_iter != source_end) + { + mutable_buffer target_buffer = + mutable_buffer(*target_iter) + target_buffer_offset; + + const_buffer source_buffer = + const_buffer(*source_iter) + source_buffer_offset; + + std::size_t bytes_copied = (buffer_copy_1)(target_buffer, source_buffer); + total_bytes_copied += bytes_copied; + + if (bytes_copied == target_buffer.size()) + { + ++target_iter; + target_buffer_offset = 0; + } + else + target_buffer_offset += bytes_copied; + + if (bytes_copied == source_buffer.size()) + { + ++source_iter; + source_buffer_offset = 0; + } + else + source_buffer_offset += bytes_copied; + } + + return total_bytes_copied; +} + +template +std::size_t buffer_copy(multiple_buffers, multiple_buffers, + TargetIterator target_begin, TargetIterator target_end, + SourceIterator source_begin, SourceIterator source_end, + std::size_t max_bytes_to_copy) ASIO_NOEXCEPT +{ + std::size_t total_bytes_copied = 0; + + TargetIterator target_iter = target_begin; + std::size_t target_buffer_offset = 0; + + SourceIterator source_iter = source_begin; + std::size_t source_buffer_offset = 0; + + while (total_bytes_copied != max_bytes_to_copy + && target_iter != target_end && source_iter != source_end) + { + mutable_buffer target_buffer = + mutable_buffer(*target_iter) + target_buffer_offset; + + const_buffer source_buffer = + const_buffer(*source_iter) + source_buffer_offset; + + std::size_t bytes_copied = (buffer_copy_1)( + target_buffer, asio::buffer(source_buffer, + max_bytes_to_copy - total_bytes_copied)); + total_bytes_copied += bytes_copied; + + if (bytes_copied == target_buffer.size()) + { + ++target_iter; + target_buffer_offset = 0; + } + else + target_buffer_offset += bytes_copied; + + if (bytes_copied == source_buffer.size()) + { + ++source_iter; + source_buffer_offset = 0; + } + else + source_buffer_offset += bytes_copied; + } + + return total_bytes_copied; +} + +} // namespace detail + +/// Copies bytes from a source buffer sequence to a target buffer sequence. +/** + * @param target A modifiable buffer sequence representing the memory regions to + * which the bytes will be copied. + * + * @param source A non-modifiable buffer sequence representing the memory + * regions from which the bytes will be copied. + * + * @returns The number of bytes copied. + * + * @note The number of bytes copied is the lesser of: + * + * @li @c buffer_size(target) + * + * @li @c buffer_size(source) + * + * This function is implemented in terms of @c memcpy, and consequently it + * cannot be used to copy between overlapping memory regions. + */ +template +inline std::size_t buffer_copy(const MutableBufferSequence& target, + const ConstBufferSequence& source) ASIO_NOEXCEPT +{ + return detail::buffer_copy( + detail::buffer_sequence_cardinality(), + detail::buffer_sequence_cardinality(), + asio::buffer_sequence_begin(target), + asio::buffer_sequence_end(target), + asio::buffer_sequence_begin(source), + asio::buffer_sequence_end(source)); +} + +/// Copies a limited number of bytes from a source buffer sequence to a target +/// buffer sequence. +/** + * @param target A modifiable buffer sequence representing the memory regions to + * which the bytes will be copied. + * + * @param source A non-modifiable buffer sequence representing the memory + * regions from which the bytes will be copied. + * + * @param max_bytes_to_copy The maximum number of bytes to be copied. + * + * @returns The number of bytes copied. + * + * @note The number of bytes copied is the lesser of: + * + * @li @c buffer_size(target) + * + * @li @c buffer_size(source) + * + * @li @c max_bytes_to_copy + * + * This function is implemented in terms of @c memcpy, and consequently it + * cannot be used to copy between overlapping memory regions. + */ +template +inline std::size_t buffer_copy(const MutableBufferSequence& target, + const ConstBufferSequence& source, + std::size_t max_bytes_to_copy) ASIO_NOEXCEPT +{ + return detail::buffer_copy( + detail::buffer_sequence_cardinality(), + detail::buffer_sequence_cardinality(), + asio::buffer_sequence_begin(target), + asio::buffer_sequence_end(target), + asio::buffer_sequence_begin(source), + asio::buffer_sequence_end(source), max_bytes_to_copy); +} + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" +#include "asio/detail/is_buffer_sequence.hpp" +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Trait to determine whether a type satisfies the MutableBufferSequence +/// requirements. +template +struct is_mutable_buffer_sequence +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_buffer_sequence +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; + +/// Trait to determine whether a type satisfies the ConstBufferSequence +/// requirements. +template +struct is_const_buffer_sequence +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_buffer_sequence +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) +/// Trait to determine whether a type satisfies the DynamicBuffer_v1 +/// requirements. +template +struct is_dynamic_buffer_v1 +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_dynamic_buffer_v1 +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Trait to determine whether a type satisfies the DynamicBuffer_v2 +/// requirements. +template +struct is_dynamic_buffer_v2 +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_dynamic_buffer_v2 +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; + +/// Trait to determine whether a type satisfies the DynamicBuffer requirements. +/** + * If @c ASIO_NO_DYNAMIC_BUFFER_V1 is not defined, determines whether the + * type satisfies the DynamicBuffer_v1 requirements. Otherwise, if @c + * ASIO_NO_DYNAMIC_BUFFER_V1 is defined, determines whether the type + * satisfies the DynamicBuffer_v2 requirements. + */ +template +struct is_dynamic_buffer +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#elif defined(ASIO_NO_DYNAMIC_BUFFER_V1) + : asio::is_dynamic_buffer_v2 +#else // defined(ASIO_NO_DYNAMIC_BUFFER_V1) + : asio::is_dynamic_buffer_v1 +#endif // defined(ASIO_NO_DYNAMIC_BUFFER_V1) +{ +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BUFFER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream.hpp new file mode 100644 index 00000000..a1cece62 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream.hpp @@ -0,0 +1,253 @@ +// +// buffered_read_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_READ_STREAM_HPP +#define ASIO_BUFFERED_READ_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/buffered_read_stream_fwd.hpp" +#include "asio/buffer.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_resize_guard.hpp" +#include "asio/detail/buffered_stream_storage.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Adds buffering to the read-related operations of a stream. +/** + * The buffered_read_stream class template can be used to add buffering to the + * synchronous and asynchronous read operations of a stream. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class buffered_read_stream + : private noncopyable +{ +public: + /// The type of the next layer. + typedef typename remove_reference::type next_layer_type; + + /// The type of the lowest layer. + typedef typename next_layer_type::lowest_layer_type lowest_layer_type; + + /// The type of the executor associated with the object. + typedef typename lowest_layer_type::executor_type executor_type; + +#if defined(GENERATING_DOCUMENTATION) + /// The default buffer size. + static const std::size_t default_buffer_size = implementation_defined; +#else + ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024); +#endif + + /// Construct, passing the specified argument to initialise the next layer. + template + explicit buffered_read_stream(Arg& a) + : next_layer_(a), + storage_(default_buffer_size) + { + } + + /// Construct, passing the specified argument to initialise the next layer. + template + buffered_read_stream(Arg& a, std::size_t buffer_size) + : next_layer_(a), + storage_(buffer_size) + { + } + + /// Get a reference to the next layer. + next_layer_type& next_layer() + { + return next_layer_; + } + + /// Get a reference to the lowest layer. + lowest_layer_type& lowest_layer() + { + return next_layer_.lowest_layer(); + } + + /// Get a const reference to the lowest layer. + const lowest_layer_type& lowest_layer() const + { + return next_layer_.lowest_layer(); + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + /// Close the stream. + void close() + { + next_layer_.close(); + } + + /// Close the stream. + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + next_layer_.close(ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Write the given data to the stream. Returns the number of bytes written. + /// Throws an exception on failure. + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + return next_layer_.write_some(buffers); + } + + /// Write the given data to the stream. Returns the number of bytes written, + /// or 0 if an error occurred. + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return next_layer_.write_some(buffers, ec); + } + + /// Start an asynchronous write. The data being written must be valid for the + /// lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return next_layer_.async_write_some(buffers, + ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// Fill the buffer with some data. Returns the number of bytes placed in the + /// buffer as a result of the operation. Throws an exception on failure. + std::size_t fill(); + + /// Fill the buffer with some data. Returns the number of bytes placed in the + /// buffer as a result of the operation, or 0 if an error occurred. + std::size_t fill(asio::error_code& ec); + + /// Start an asynchronous fill. + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) ReadHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_fill( + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)); + + /// Read some data from the stream. Returns the number of bytes read. Throws + /// an exception on failure. + template + std::size_t read_some(const MutableBufferSequence& buffers); + + /// Read some data from the stream. Returns the number of bytes read or 0 if + /// an error occurred. + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec); + + /// Start an asynchronous read. The buffer into which the data will be read + /// must be valid for the lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)); + + /// Peek at the incoming data on the stream. Returns the number of bytes read. + /// Throws an exception on failure. + template + std::size_t peek(const MutableBufferSequence& buffers); + + /// Peek at the incoming data on the stream. Returns the number of bytes read, + /// or 0 if an error occurred. + template + std::size_t peek(const MutableBufferSequence& buffers, + asio::error_code& ec); + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail() + { + return storage_.size(); + } + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail(asio::error_code& ec) + { + ec = asio::error_code(); + return storage_.size(); + } + +private: + /// Copy data out of the internal buffer to the specified target buffer. + /// Returns the number of bytes copied. + template + std::size_t copy(const MutableBufferSequence& buffers) + { + std::size_t bytes_copied = asio::buffer_copy( + buffers, storage_.data(), storage_.size()); + storage_.consume(bytes_copied); + return bytes_copied; + } + + /// Copy data from the internal buffer to the specified target buffer, without + /// removing the data from the internal buffer. Returns the number of bytes + /// copied. + template + std::size_t peek_copy(const MutableBufferSequence& buffers) + { + return asio::buffer_copy(buffers, storage_.data(), storage_.size()); + } + + /// The next layer. + Stream next_layer_; + + // The data in the buffer. + detail::buffered_stream_storage storage_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/buffered_read_stream.hpp" + +#endif // ASIO_BUFFERED_READ_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream_fwd.hpp new file mode 100644 index 00000000..666c18fa --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_read_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_read_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_READ_STREAM_FWD_HPP +#define ASIO_BUFFERED_READ_STREAM_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +namespace asio { + +template +class buffered_read_stream; + +} // namespace asio + +#endif // ASIO_BUFFERED_READ_STREAM_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream.hpp new file mode 100644 index 00000000..6643ff83 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream.hpp @@ -0,0 +1,279 @@ +// +// buffered_stream.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_STREAM_HPP +#define ASIO_BUFFERED_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/buffered_read_stream.hpp" +#include "asio/buffered_write_stream.hpp" +#include "asio/buffered_stream_fwd.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Adds buffering to the read- and write-related operations of a stream. +/** + * The buffered_stream class template can be used to add buffering to the + * synchronous and asynchronous read and write operations of a stream. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class buffered_stream + : private noncopyable +{ +public: + /// The type of the next layer. + typedef typename remove_reference::type next_layer_type; + + /// The type of the lowest layer. + typedef typename next_layer_type::lowest_layer_type lowest_layer_type; + + /// The type of the executor associated with the object. + typedef typename lowest_layer_type::executor_type executor_type; + + /// Construct, passing the specified argument to initialise the next layer. + template + explicit buffered_stream(Arg& a) + : inner_stream_impl_(a), + stream_impl_(inner_stream_impl_) + { + } + + /// Construct, passing the specified argument to initialise the next layer. + template + explicit buffered_stream(Arg& a, std::size_t read_buffer_size, + std::size_t write_buffer_size) + : inner_stream_impl_(a, write_buffer_size), + stream_impl_(inner_stream_impl_, read_buffer_size) + { + } + + /// Get a reference to the next layer. + next_layer_type& next_layer() + { + return stream_impl_.next_layer().next_layer(); + } + + /// Get a reference to the lowest layer. + lowest_layer_type& lowest_layer() + { + return stream_impl_.lowest_layer(); + } + + /// Get a const reference to the lowest layer. + const lowest_layer_type& lowest_layer() const + { + return stream_impl_.lowest_layer(); + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return stream_impl_.lowest_layer().get_executor(); + } + + /// Close the stream. + void close() + { + stream_impl_.close(); + } + + /// Close the stream. + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + stream_impl_.close(ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Flush all data from the buffer to the next layer. Returns the number of + /// bytes written to the next layer on the last write operation. Throws an + /// exception on failure. + std::size_t flush() + { + return stream_impl_.next_layer().flush(); + } + + /// Flush all data from the buffer to the next layer. Returns the number of + /// bytes written to the next layer on the last write operation, or 0 if an + /// error occurred. + std::size_t flush(asio::error_code& ec) + { + return stream_impl_.next_layer().flush(ec); + } + + /// Start an asynchronous flush. + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) WriteHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_flush( + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return stream_impl_.next_layer().async_flush( + ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// Write the given data to the stream. Returns the number of bytes written. + /// Throws an exception on failure. + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + return stream_impl_.write_some(buffers); + } + + /// Write the given data to the stream. Returns the number of bytes written, + /// or 0 if an error occurred. + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return stream_impl_.write_some(buffers, ec); + } + + /// Start an asynchronous write. The data being written must be valid for the + /// lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return stream_impl_.async_write_some(buffers, + ASIO_MOVE_CAST(WriteHandler)(handler)); + } + + /// Fill the buffer with some data. Returns the number of bytes placed in the + /// buffer as a result of the operation. Throws an exception on failure. + std::size_t fill() + { + return stream_impl_.fill(); + } + + /// Fill the buffer with some data. Returns the number of bytes placed in the + /// buffer as a result of the operation, or 0 if an error occurred. + std::size_t fill(asio::error_code& ec) + { + return stream_impl_.fill(ec); + } + + /// Start an asynchronous fill. + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) ReadHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_fill( + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return stream_impl_.async_fill(ASIO_MOVE_CAST(ReadHandler)(handler)); + } + + /// Read some data from the stream. Returns the number of bytes read. Throws + /// an exception on failure. + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + return stream_impl_.read_some(buffers); + } + + /// Read some data from the stream. Returns the number of bytes read or 0 if + /// an error occurred. + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return stream_impl_.read_some(buffers, ec); + } + + /// Start an asynchronous read. The buffer into which the data will be read + /// must be valid for the lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return stream_impl_.async_read_some(buffers, + ASIO_MOVE_CAST(ReadHandler)(handler)); + } + + /// Peek at the incoming data on the stream. Returns the number of bytes read. + /// Throws an exception on failure. + template + std::size_t peek(const MutableBufferSequence& buffers) + { + return stream_impl_.peek(buffers); + } + + /// Peek at the incoming data on the stream. Returns the number of bytes read, + /// or 0 if an error occurred. + template + std::size_t peek(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return stream_impl_.peek(buffers, ec); + } + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail() + { + return stream_impl_.in_avail(); + } + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail(asio::error_code& ec) + { + return stream_impl_.in_avail(ec); + } + +private: + // The buffered write stream. + typedef buffered_write_stream write_stream_type; + write_stream_type inner_stream_impl_; + + // The buffered read stream. + typedef buffered_read_stream read_stream_type; + read_stream_type stream_impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BUFFERED_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream_fwd.hpp new file mode 100644 index 00000000..86dfcbc1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_STREAM_FWD_HPP +#define ASIO_BUFFERED_STREAM_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +namespace asio { + +template +class buffered_stream; + +} // namespace asio + +#endif // ASIO_BUFFERED_STREAM_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream.hpp new file mode 100644 index 00000000..66401b44 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream.hpp @@ -0,0 +1,245 @@ +// +// buffered_write_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_WRITE_STREAM_HPP +#define ASIO_BUFFERED_WRITE_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/buffered_write_stream_fwd.hpp" +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffered_stream_storage.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" +#include "asio/write.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Adds buffering to the write-related operations of a stream. +/** + * The buffered_write_stream class template can be used to add buffering to the + * synchronous and asynchronous write operations of a stream. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class buffered_write_stream + : private noncopyable +{ +public: + /// The type of the next layer. + typedef typename remove_reference::type next_layer_type; + + /// The type of the lowest layer. + typedef typename next_layer_type::lowest_layer_type lowest_layer_type; + + /// The type of the executor associated with the object. + typedef typename lowest_layer_type::executor_type executor_type; + +#if defined(GENERATING_DOCUMENTATION) + /// The default buffer size. + static const std::size_t default_buffer_size = implementation_defined; +#else + ASIO_STATIC_CONSTANT(std::size_t, default_buffer_size = 1024); +#endif + + /// Construct, passing the specified argument to initialise the next layer. + template + explicit buffered_write_stream(Arg& a) + : next_layer_(a), + storage_(default_buffer_size) + { + } + + /// Construct, passing the specified argument to initialise the next layer. + template + buffered_write_stream(Arg& a, std::size_t buffer_size) + : next_layer_(a), + storage_(buffer_size) + { + } + + /// Get a reference to the next layer. + next_layer_type& next_layer() + { + return next_layer_; + } + + /// Get a reference to the lowest layer. + lowest_layer_type& lowest_layer() + { + return next_layer_.lowest_layer(); + } + + /// Get a const reference to the lowest layer. + const lowest_layer_type& lowest_layer() const + { + return next_layer_.lowest_layer(); + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + /// Close the stream. + void close() + { + next_layer_.close(); + } + + /// Close the stream. + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + next_layer_.close(ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Flush all data from the buffer to the next layer. Returns the number of + /// bytes written to the next layer on the last write operation. Throws an + /// exception on failure. + std::size_t flush(); + + /// Flush all data from the buffer to the next layer. Returns the number of + /// bytes written to the next layer on the last write operation, or 0 if an + /// error occurred. + std::size_t flush(asio::error_code& ec); + + /// Start an asynchronous flush. + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) WriteHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_flush( + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)); + + /// Write the given data to the stream. Returns the number of bytes written. + /// Throws an exception on failure. + template + std::size_t write_some(const ConstBufferSequence& buffers); + + /// Write the given data to the stream. Returns the number of bytes written, + /// or 0 if an error occurred and the error handler did not throw. + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec); + + /// Start an asynchronous write. The data being written must be valid for the + /// lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)); + + /// Read some data from the stream. Returns the number of bytes read. Throws + /// an exception on failure. + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + return next_layer_.read_some(buffers); + } + + /// Read some data from the stream. Returns the number of bytes read or 0 if + /// an error occurred. + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return next_layer_.read_some(buffers, ec); + } + + /// Start an asynchronous read. The buffer into which the data will be read + /// must be valid for the lifetime of the asynchronous operation. + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return next_layer_.async_read_some(buffers, + ASIO_MOVE_CAST(ReadHandler)(handler)); + } + + /// Peek at the incoming data on the stream. Returns the number of bytes read. + /// Throws an exception on failure. + template + std::size_t peek(const MutableBufferSequence& buffers) + { + return next_layer_.peek(buffers); + } + + /// Peek at the incoming data on the stream. Returns the number of bytes read, + /// or 0 if an error occurred. + template + std::size_t peek(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return next_layer_.peek(buffers, ec); + } + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail() + { + return next_layer_.in_avail(); + } + + /// Determine the amount of data that may be read without blocking. + std::size_t in_avail(asio::error_code& ec) + { + return next_layer_.in_avail(ec); + } + +private: + /// Copy data into the internal buffer from the specified source buffer. + /// Returns the number of bytes copied. + template + std::size_t copy(const ConstBufferSequence& buffers); + + /// The next layer. + Stream next_layer_; + + // The data in the buffer. + detail::buffered_stream_storage storage_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/buffered_write_stream.hpp" + +#endif // ASIO_BUFFERED_WRITE_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream_fwd.hpp new file mode 100644 index 00000000..370273ce --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffered_write_stream_fwd.hpp @@ -0,0 +1,25 @@ +// +// buffered_write_stream_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERED_WRITE_STREAM_FWD_HPP +#define ASIO_BUFFERED_WRITE_STREAM_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +namespace asio { + +template +class buffered_write_stream; + +} // namespace asio + +#endif // ASIO_BUFFERED_WRITE_STREAM_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffers_iterator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffers_iterator.hpp new file mode 100644 index 00000000..57aeadd6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/buffers_iterator.hpp @@ -0,0 +1,521 @@ +// +// buffers_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_BUFFERS_ITERATOR_HPP +#define ASIO_BUFFERS_ITERATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/buffer.hpp" +#include "asio/detail/assert.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + struct buffers_iterator_types_helper; + + template <> + struct buffers_iterator_types_helper + { + typedef const_buffer buffer_type; + template + struct byte_type + { + typedef typename add_const::type type; + }; + }; + + template <> + struct buffers_iterator_types_helper + { + typedef mutable_buffer buffer_type; + template + struct byte_type + { + typedef ByteType type; + }; + }; + + template + struct buffers_iterator_types + { + enum + { + is_mutable = is_convertible< + typename BufferSequence::value_type, + mutable_buffer>::value + }; + typedef buffers_iterator_types_helper helper; + typedef typename helper::buffer_type buffer_type; + typedef typename helper::template byte_type::type byte_type; + typedef typename BufferSequence::const_iterator const_iterator; + }; + + template + struct buffers_iterator_types + { + typedef mutable_buffer buffer_type; + typedef ByteType byte_type; + typedef const mutable_buffer* const_iterator; + }; + + template + struct buffers_iterator_types + { + typedef const_buffer buffer_type; + typedef typename add_const::type byte_type; + typedef const const_buffer* const_iterator; + }; + +#if !defined(ASIO_NO_DEPRECATED) + + template + struct buffers_iterator_types + { + typedef mutable_buffer buffer_type; + typedef ByteType byte_type; + typedef const mutable_buffer* const_iterator; + }; + + template + struct buffers_iterator_types + { + typedef const_buffer buffer_type; + typedef typename add_const::type byte_type; + typedef const const_buffer* const_iterator; + }; + +#endif // !defined(ASIO_NO_DEPRECATED) +} + +/// A random access iterator over the bytes in a buffer sequence. +template +class buffers_iterator +{ +private: + typedef typename detail::buffers_iterator_types< + BufferSequence, ByteType>::buffer_type buffer_type; + + typedef typename detail::buffers_iterator_types::const_iterator buffer_sequence_iterator_type; + +public: + /// The type used for the distance between two iterators. + typedef std::ptrdiff_t difference_type; + + /// The type of the value pointed to by the iterator. + typedef ByteType value_type; + +#if defined(GENERATING_DOCUMENTATION) + /// The type of the result of applying operator->() to the iterator. + /** + * If the buffer sequence stores buffer objects that are convertible to + * mutable_buffer, this is a pointer to a non-const ByteType. Otherwise, a + * pointer to a const ByteType. + */ + typedef const_or_non_const_ByteType* pointer; +#else // defined(GENERATING_DOCUMENTATION) + typedef typename detail::buffers_iterator_types< + BufferSequence, ByteType>::byte_type* pointer; +#endif // defined(GENERATING_DOCUMENTATION) + +#if defined(GENERATING_DOCUMENTATION) + /// The type of the result of applying operator*() to the iterator. + /** + * If the buffer sequence stores buffer objects that are convertible to + * mutable_buffer, this is a reference to a non-const ByteType. Otherwise, a + * reference to a const ByteType. + */ + typedef const_or_non_const_ByteType& reference; +#else // defined(GENERATING_DOCUMENTATION) + typedef typename detail::buffers_iterator_types< + BufferSequence, ByteType>::byte_type& reference; +#endif // defined(GENERATING_DOCUMENTATION) + + /// The iterator category. + typedef std::random_access_iterator_tag iterator_category; + + /// Default constructor. Creates an iterator in an undefined state. + buffers_iterator() + : current_buffer_(), + current_buffer_position_(0), + begin_(), + current_(), + end_(), + position_(0) + { + } + + /// Construct an iterator representing the beginning of the buffers' data. + static buffers_iterator begin(const BufferSequence& buffers) +#if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) + __attribute__ ((__noinline__)) +#endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) + { + buffers_iterator new_iter; + new_iter.begin_ = asio::buffer_sequence_begin(buffers); + new_iter.current_ = asio::buffer_sequence_begin(buffers); + new_iter.end_ = asio::buffer_sequence_end(buffers); + while (new_iter.current_ != new_iter.end_) + { + new_iter.current_buffer_ = *new_iter.current_; + if (new_iter.current_buffer_.size() > 0) + break; + ++new_iter.current_; + } + return new_iter; + } + + /// Construct an iterator representing the end of the buffers' data. + static buffers_iterator end(const BufferSequence& buffers) +#if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) + __attribute__ ((__noinline__)) +#endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) + { + buffers_iterator new_iter; + new_iter.begin_ = asio::buffer_sequence_begin(buffers); + new_iter.current_ = asio::buffer_sequence_begin(buffers); + new_iter.end_ = asio::buffer_sequence_end(buffers); + while (new_iter.current_ != new_iter.end_) + { + buffer_type buffer = *new_iter.current_; + new_iter.position_ += buffer.size(); + ++new_iter.current_; + } + return new_iter; + } + + /// Dereference an iterator. + reference operator*() const + { + return dereference(); + } + + /// Dereference an iterator. + pointer operator->() const + { + return &dereference(); + } + + /// Access an individual element. + reference operator[](std::ptrdiff_t difference) const + { + buffers_iterator tmp(*this); + tmp.advance(difference); + return *tmp; + } + + /// Increment operator (prefix). + buffers_iterator& operator++() + { + increment(); + return *this; + } + + /// Increment operator (postfix). + buffers_iterator operator++(int) + { + buffers_iterator tmp(*this); + ++*this; + return tmp; + } + + /// Decrement operator (prefix). + buffers_iterator& operator--() + { + decrement(); + return *this; + } + + /// Decrement operator (postfix). + buffers_iterator operator--(int) + { + buffers_iterator tmp(*this); + --*this; + return tmp; + } + + /// Addition operator. + buffers_iterator& operator+=(std::ptrdiff_t difference) + { + advance(difference); + return *this; + } + + /// Subtraction operator. + buffers_iterator& operator-=(std::ptrdiff_t difference) + { + advance(-difference); + return *this; + } + + /// Addition operator. + friend buffers_iterator operator+(const buffers_iterator& iter, + std::ptrdiff_t difference) + { + buffers_iterator tmp(iter); + tmp.advance(difference); + return tmp; + } + + /// Addition operator. + friend buffers_iterator operator+(std::ptrdiff_t difference, + const buffers_iterator& iter) + { + buffers_iterator tmp(iter); + tmp.advance(difference); + return tmp; + } + + /// Subtraction operator. + friend buffers_iterator operator-(const buffers_iterator& iter, + std::ptrdiff_t difference) + { + buffers_iterator tmp(iter); + tmp.advance(-difference); + return tmp; + } + + /// Subtraction operator. + friend std::ptrdiff_t operator-(const buffers_iterator& a, + const buffers_iterator& b) + { + return b.distance_to(a); + } + + /// Test two iterators for equality. + friend bool operator==(const buffers_iterator& a, const buffers_iterator& b) + { + return a.equal(b); + } + + /// Test two iterators for inequality. + friend bool operator!=(const buffers_iterator& a, const buffers_iterator& b) + { + return !a.equal(b); + } + + /// Compare two iterators. + friend bool operator<(const buffers_iterator& a, const buffers_iterator& b) + { + return a.distance_to(b) > 0; + } + + /// Compare two iterators. + friend bool operator<=(const buffers_iterator& a, const buffers_iterator& b) + { + return !(b < a); + } + + /// Compare two iterators. + friend bool operator>(const buffers_iterator& a, const buffers_iterator& b) + { + return b < a; + } + + /// Compare two iterators. + friend bool operator>=(const buffers_iterator& a, const buffers_iterator& b) + { + return !(a < b); + } + +private: + // Dereference the iterator. + reference dereference() const + { + return static_cast( + current_buffer_.data())[current_buffer_position_]; + } + + // Compare two iterators for equality. + bool equal(const buffers_iterator& other) const + { + return position_ == other.position_; + } + + // Increment the iterator. + void increment() + { + ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); + ++position_; + + // Check if the increment can be satisfied by the current buffer. + ++current_buffer_position_; + if (current_buffer_position_ != current_buffer_.size()) + return; + + // Find the next non-empty buffer. + ++current_; + current_buffer_position_ = 0; + while (current_ != end_) + { + current_buffer_ = *current_; + if (current_buffer_.size() > 0) + return; + ++current_; + } + } + + // Decrement the iterator. + void decrement() + { + ASIO_ASSERT(position_ > 0 && "iterator out of bounds"); + --position_; + + // Check if the decrement can be satisfied by the current buffer. + if (current_buffer_position_ != 0) + { + --current_buffer_position_; + return; + } + + // Find the previous non-empty buffer. + buffer_sequence_iterator_type iter = current_; + while (iter != begin_) + { + --iter; + buffer_type buffer = *iter; + std::size_t buffer_size = buffer.size(); + if (buffer_size > 0) + { + current_ = iter; + current_buffer_ = buffer; + current_buffer_position_ = buffer_size - 1; + return; + } + } + } + + // Advance the iterator by the specified distance. + void advance(std::ptrdiff_t n) + { + if (n > 0) + { + ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); + for (;;) + { + std::ptrdiff_t current_buffer_balance + = current_buffer_.size() - current_buffer_position_; + + // Check if the advance can be satisfied by the current buffer. + if (current_buffer_balance > n) + { + position_ += n; + current_buffer_position_ += n; + return; + } + + // Update position. + n -= current_buffer_balance; + position_ += current_buffer_balance; + + // Move to next buffer. If it is empty then it will be skipped on the + // next iteration of this loop. + if (++current_ == end_) + { + ASIO_ASSERT(n == 0 && "iterator out of bounds"); + current_buffer_ = buffer_type(); + current_buffer_position_ = 0; + return; + } + current_buffer_ = *current_; + current_buffer_position_ = 0; + } + } + else if (n < 0) + { + std::size_t abs_n = -n; + ASIO_ASSERT(position_ >= abs_n && "iterator out of bounds"); + for (;;) + { + // Check if the advance can be satisfied by the current buffer. + if (current_buffer_position_ >= abs_n) + { + position_ -= abs_n; + current_buffer_position_ -= abs_n; + return; + } + + // Update position. + abs_n -= current_buffer_position_; + position_ -= current_buffer_position_; + + // Check if we've reached the beginning of the buffers. + if (current_ == begin_) + { + ASIO_ASSERT(abs_n == 0 && "iterator out of bounds"); + current_buffer_position_ = 0; + return; + } + + // Find the previous non-empty buffer. + buffer_sequence_iterator_type iter = current_; + while (iter != begin_) + { + --iter; + buffer_type buffer = *iter; + std::size_t buffer_size = buffer.size(); + if (buffer_size > 0) + { + current_ = iter; + current_buffer_ = buffer; + current_buffer_position_ = buffer_size; + break; + } + } + } + } + } + + // Determine the distance between two iterators. + std::ptrdiff_t distance_to(const buffers_iterator& other) const + { + return other.position_ - position_; + } + + buffer_type current_buffer_; + std::size_t current_buffer_position_; + buffer_sequence_iterator_type begin_; + buffer_sequence_iterator_type current_; + buffer_sequence_iterator_type end_; + std::size_t position_; +}; + +/// Construct an iterator representing the beginning of the buffers' data. +template +inline buffers_iterator buffers_begin( + const BufferSequence& buffers) +{ + return buffers_iterator::begin(buffers); +} + +/// Construct an iterator representing the end of the buffers' data. +template +inline buffers_iterator buffers_end( + const BufferSequence& buffers) +{ + return buffers_iterator::end(buffers); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_BUFFERS_ITERATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/co_spawn.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/co_spawn.hpp new file mode 100644 index 00000000..7afd8ea8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/co_spawn.hpp @@ -0,0 +1,100 @@ +// +// co_spawn.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_CO_SPAWN_HPP +#define ASIO_CO_SPAWN_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#include "asio/awaitable.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct awaitable_signature; + +template +struct awaitable_signature> +{ + typedef void type(std::exception_ptr, T); +}; + +template +struct awaitable_signature> +{ + typedef void type(std::exception_ptr); +}; + +} // namespace detail + +/// Spawn a new thread of execution. +/** + * The entry point function object @c f must have the signature: + * + * @code awaitable f(); @endcode + * + * where @c E is convertible from @c Executor. + */ +template ::type>::type) CompletionToken + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(Executor)> +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, + typename detail::awaitable_signature::type>::type) +co_spawn(const Executor& ex, F&& f, + CompletionToken&& token + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if< + is_executor::value + >::type* = 0); + +/// Spawn a new thread of execution. +/** + * The entry point function object @c f must have the signature: + * + * @code awaitable f(); @endcode + * + * where @c E is convertible from @c ExecutionContext::executor_type. + */ +template ::type>::type) CompletionToken + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE( + typename ExecutionContext::executor_type)> +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, + typename detail::awaitable_signature::type>::type) +co_spawn(ExecutionContext& ctx, F&& f, + CompletionToken&& token + ASIO_DEFAULT_COMPLETION_TOKEN( + typename ExecutionContext::executor_type), + typename enable_if< + is_convertible::value + >::type* = 0); + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/co_spawn.hpp" + +#endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_CO_SPAWN_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/completion_condition.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/completion_condition.hpp new file mode 100644 index 00000000..526c034f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/completion_condition.hpp @@ -0,0 +1,218 @@ +// +// completion_condition.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_COMPLETION_CONDITION_HPP +#define ASIO_COMPLETION_CONDITION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail { + +// The default maximum number of bytes to transfer in a single operation. +enum default_max_transfer_size_t { default_max_transfer_size = 65536 }; + +// Adapt result of old-style completion conditions (which had a bool result +// where true indicated that the operation was complete). +inline std::size_t adapt_completion_condition_result(bool result) +{ + return result ? 0 : default_max_transfer_size; +} + +// Adapt result of current completion conditions (which have a size_t result +// where 0 means the operation is complete, and otherwise the result is the +// maximum number of bytes to transfer on the next underlying operation). +inline std::size_t adapt_completion_condition_result(std::size_t result) +{ + return result; +} + +class transfer_all_t +{ +public: + typedef std::size_t result_type; + + template + std::size_t operator()(const Error& err, std::size_t) + { + return !!err ? 0 : default_max_transfer_size; + } +}; + +class transfer_at_least_t +{ +public: + typedef std::size_t result_type; + + explicit transfer_at_least_t(std::size_t minimum) + : minimum_(minimum) + { + } + + template + std::size_t operator()(const Error& err, std::size_t bytes_transferred) + { + return (!!err || bytes_transferred >= minimum_) + ? 0 : default_max_transfer_size; + } + +private: + std::size_t minimum_; +}; + +class transfer_exactly_t +{ +public: + typedef std::size_t result_type; + + explicit transfer_exactly_t(std::size_t size) + : size_(size) + { + } + + template + std::size_t operator()(const Error& err, std::size_t bytes_transferred) + { + return (!!err || bytes_transferred >= size_) ? 0 : + (size_ - bytes_transferred < default_max_transfer_size + ? size_ - bytes_transferred : std::size_t(default_max_transfer_size)); + } + +private: + std::size_t size_; +}; + +} // namespace detail + +/** + * @defgroup completion_condition Completion Condition Function Objects + * + * Function objects used for determining when a read or write operation should + * complete. + */ +/*@{*/ + +/// Return a completion condition function object that indicates that a read or +/// write operation should continue until all of the data has been transferred, +/// or until an error occurs. +/** + * This function is used to create an object, of unspecified type, that meets + * CompletionCondition requirements. + * + * @par Example + * Reading until a buffer is full: + * @code + * boost::array buf; + * asio::error_code ec; + * std::size_t n = asio::read( + * sock, asio::buffer(buf), + * asio::transfer_all(), ec); + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * // n == 128 + * } + * @endcode + */ +#if defined(GENERATING_DOCUMENTATION) +unspecified transfer_all(); +#else +inline detail::transfer_all_t transfer_all() +{ + return detail::transfer_all_t(); +} +#endif + +/// Return a completion condition function object that indicates that a read or +/// write operation should continue until a minimum number of bytes has been +/// transferred, or until an error occurs. +/** + * This function is used to create an object, of unspecified type, that meets + * CompletionCondition requirements. + * + * @par Example + * Reading until a buffer is full or contains at least 64 bytes: + * @code + * boost::array buf; + * asio::error_code ec; + * std::size_t n = asio::read( + * sock, asio::buffer(buf), + * asio::transfer_at_least(64), ec); + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * // n >= 64 && n <= 128 + * } + * @endcode + */ +#if defined(GENERATING_DOCUMENTATION) +unspecified transfer_at_least(std::size_t minimum); +#else +inline detail::transfer_at_least_t transfer_at_least(std::size_t minimum) +{ + return detail::transfer_at_least_t(minimum); +} +#endif + +/// Return a completion condition function object that indicates that a read or +/// write operation should continue until an exact number of bytes has been +/// transferred, or until an error occurs. +/** + * This function is used to create an object, of unspecified type, that meets + * CompletionCondition requirements. + * + * @par Example + * Reading until a buffer is full or contains exactly 64 bytes: + * @code + * boost::array buf; + * asio::error_code ec; + * std::size_t n = asio::read( + * sock, asio::buffer(buf), + * asio::transfer_exactly(64), ec); + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * // n == 64 + * } + * @endcode + */ +#if defined(GENERATING_DOCUMENTATION) +unspecified transfer_exactly(std::size_t size); +#else +inline detail::transfer_exactly_t transfer_exactly(std::size_t size) +{ + return detail::transfer_exactly_t(size); +} +#endif + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_COMPLETION_CONDITION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/compose.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/compose.hpp new file mode 100644 index 00000000..9d7b6722 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/compose.hpp @@ -0,0 +1,136 @@ +// +// compose.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_COMPOSE_HPP +#define ASIO_COMPOSE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) \ + || defined(GENERATING_DOCUMENTATION) + +/// Launch an asynchronous operation with a stateful implementation. +/** + * The async_compose function simplifies the implementation of composed + * asynchronous operations automatically wrapping a stateful function object + * with a conforming intermediate completion handler. + * + * @param implementation A function object that contains the implementation of + * the composed asynchronous operation. The first argument to the function + * object is a non-const reference to the enclosing intermediate completion + * handler. The remaining arguments are any arguments that originate from the + * completion handlers of any asynchronous operations performed by the + * implementation. + + * @param token The completion token. + * + * @param io_objects_or_executors Zero or more I/O objects or I/O executors for + * which outstanding work must be maintained. + * + * @par Example: + * + * @code struct async_echo_implementation + * { + * tcp::socket& socket_; + * asio::mutable_buffer buffer_; + * enum { starting, reading, writing } state_; + * + * template + * void operator()(Self& self, + * asio::error_code error = {}, + * std::size_t n = 0) + * { + * switch (state_) + * { + * case starting: + * state_ = reading; + * socket_.async_read_some( + * buffer_, std::move(self)); + * break; + * case reading: + * if (error) + * { + * self.complete(error, 0); + * } + * else + * { + * state_ = writing; + * asio::async_write(socket_, buffer_, + * asio::transfer_exactly(n), + * std::move(self)); + * } + * break; + * case writing: + * self.complete(error, n); + * break; + * } + * } + * }; + * + * template + * auto async_echo(tcp::socket& socket, + * asio::mutable_buffer buffer, + * CompletionToken&& token) -> + * typename asio::async_result< + * typename std::decay::type, + * void(asio::error_code, std::size_t)>::return_type + * { + * return asio::async_compose( + * async_echo_implementation{socket, buffer, + * async_echo_implementation::starting}, + * token, socket); + * } @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) +async_compose(ASIO_MOVE_ARG(Implementation) implementation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, + ASIO_MOVE_ARG(IoObjectsOrExecutors)... io_objects_or_executors); + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + // || defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) +async_compose(ASIO_MOVE_ARG(Implementation) implementation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token); + +#define ASIO_PRIVATE_ASYNC_COMPOSE_DEF(n) \ + template \ + ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) \ + async_compose(ASIO_MOVE_ARG(Implementation) implementation, \ + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)); + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_ASYNC_COMPOSE_DEF) +#undef ASIO_PRIVATE_ASYNC_COMPOSE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + // || defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/compose.hpp" + +#endif // ASIO_COMPOSE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/connect.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/connect.hpp new file mode 100644 index 00000000..7175f4b5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/connect.hpp @@ -0,0 +1,1076 @@ +// +// connect.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_CONNECT_HPP +#define ASIO_CONNECT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/basic_socket.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + char (&has_iterator_helper(...))[2]; + + template + char has_iterator_helper(T*, typename T::iterator* = 0); + + template + struct has_iterator_typedef + { + enum { value = (sizeof((has_iterator_helper)((T*)(0))) == 1) }; + }; +} // namespace detail + +/// Type trait used to determine whether a type is an endpoint sequence that can +/// be used with with @c connect and @c async_connect. +template +struct is_endpoint_sequence +{ +#if defined(GENERATING_DOCUMENTATION) + /// The value member is true if the type may be used as an endpoint sequence. + static const bool value; +#else + enum + { + value = detail::has_iterator_typedef::value + }; +#endif +}; + +/** + * @defgroup connect asio::connect + * + * @brief The @c connect function is a composed operation that establishes a + * socket connection by trying each endpoint in a sequence. + */ +/*@{*/ + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @returns The successfully connected endpoint. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @par Example + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * asio::connect(s, r.resolve(q)); @endcode + */ +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, + typename enable_if::value>::type* = 0); + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, the successfully connected endpoint. Otherwise, a + * default-constructed endpoint. + * + * @par Example + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * asio::error_code ec; + * asio::connect(s, r.resolve(q), ec); + * if (ec) + * { + * // An error occurred. + * } @endcode + */ +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, asio::error_code& ec, + typename enable_if::value>::type* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (Deprecated: Use range overload.) Establishes a socket connection by trying +/// each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +Iterator connect(basic_socket& s, Iterator begin, + typename enable_if::value>::type* = 0); + +/// (Deprecated: Use range overload.) Establishes a socket connection by trying +/// each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +Iterator connect(basic_socket& s, + Iterator begin, asio::error_code& ec, + typename enable_if::value>::type* = 0); +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @returns An iterator denoting the successfully connected endpoint. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @par Example + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(my_context); + * asio::connect(s, e.begin(), e.end()); @endcode + */ +template +Iterator connect(basic_socket& s, + Iterator begin, Iterator end); + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @par Example + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(my_context); + * asio::error_code ec; + * asio::connect(s, e.begin(), e.end(), ec); + * if (ec) + * { + * // An error occurred. + * } @endcode + */ +template +Iterator connect(basic_socket& s, + Iterator begin, Iterator end, asio::error_code& ec); + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @returns The successfully connected endpoint. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * tcp::endpoint e = asio::connect(s, + * r.resolve(q), my_connect_condition()); + * std::cout << "Connected to: " << e << std::endl; @endcode + */ +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + typename enable_if::value>::type* = 0); + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, the successfully connected endpoint. Otherwise, a + * default-constructed endpoint. + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * asio::error_code ec; + * tcp::endpoint e = asio::connect(s, + * r.resolve(q), my_connect_condition(), ec); + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * std::cout << "Connected to: " << e << std::endl; + * } @endcode + */ +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + asio::error_code& ec, + typename enable_if::value>::type* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (Deprecated: Use range overload.) Establishes a socket connection by trying +/// each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +Iterator connect(basic_socket& s, + Iterator begin, ConnectCondition connect_condition, + typename enable_if::value>::type* = 0); + +/// (Deprecated: Use range overload.) Establishes a socket connection by trying +/// each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +Iterator connect(basic_socket& s, Iterator begin, + ConnectCondition connect_condition, asio::error_code& ec, + typename enable_if::value>::type* = 0); +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @returns An iterator denoting the successfully connected endpoint. + * + * @throws asio::system_error Thrown on failure. If the sequence is + * empty, the associated @c error_code is asio::error::not_found. + * Otherwise, contains the error from the last connection attempt. + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(my_context); + * tcp::resolver::results_type::iterator i = asio::connect( + * s, e.begin(), e.end(), my_connect_condition()); + * std::cout << "Connected to: " << i->endpoint() << std::endl; @endcode + */ +template +Iterator connect(basic_socket& s, Iterator begin, + Iterator end, ConnectCondition connect_condition); + +/// Establishes a socket connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c connect member + * function, once for each endpoint in the sequence, until a connection is + * successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param ec Set to indicate what error occurred, if any. If the sequence is + * empty, set to asio::error::not_found. Otherwise, contains the error + * from the last connection attempt. + * + * @returns On success, an iterator denoting the successfully connected + * endpoint. Otherwise, the end iterator. + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::resolver::results_type e = r.resolve(q); + * tcp::socket s(my_context); + * asio::error_code ec; + * tcp::resolver::results_type::iterator i = asio::connect( + * s, e.begin(), e.end(), my_connect_condition()); + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * std::cout << "Connected to: " << i->endpoint() << std::endl; + * } @endcode + */ +template +Iterator connect(basic_socket& s, + Iterator begin, Iterator end, ConnectCondition connect_condition, + asio::error_code& ec); + +/*@}*/ + +/** + * @defgroup async_connect asio::async_connect + * + * @brief The @c async_connect function is a composed asynchronous operation + * that establishes a socket connection by trying each endpoint in a sequence. + */ +/*@{*/ + +/// Asynchronously establishes a socket connection by trying each endpoint in a +/// sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, the successfully connected endpoint. + * // Otherwise, a default-constructed endpoint. + * const typename Protocol::endpoint& endpoint + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * + * // ... + * + * r.async_resolve(q, resolve_handler); + * + * // ... + * + * void resolve_handler( + * const asio::error_code& ec, + * tcp::resolver::results_type results) + * { + * if (!ec) + * { + * asio::async_connect(s, results, connect_handler); + * } + * } + * + * // ... + * + * void connect_handler( + * const asio::error_code& ec, + * const tcp::endpoint& endpoint) + * { + * // ... + * } @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(RangeConnectHandler, + void (asio::error_code, typename Protocol::endpoint)) +async_connect(basic_socket& s, + const EndpointSequence& endpoints, + ASIO_MOVE_ARG(RangeConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (Deprecated: Use range overload.) Asynchronously establishes a socket +/// connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, an iterator denoting the successfully + * // connected endpoint. Otherwise, the end iterator. + * Iterator iterator + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + ASIO_MOVE_ARG(IteratorConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Asynchronously establishes a socket connection by trying each endpoint in a +/// sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, an iterator denoting the successfully + * // connected endpoint. Otherwise, the end iterator. + * Iterator iterator + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code std::vector endpoints = ...; + * tcp::socket s(my_context); + * asio::async_connect(s, + * endpoints.begin(), endpoints.end(), + * connect_handler); + * + * // ... + * + * void connect_handler( + * const asio::error_code& ec, + * std::vector::iterator i) + * { + * // ... + * } @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, Iterator end, + ASIO_MOVE_ARG(IteratorConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor)); + +/// Asynchronously establishes a socket connection by trying each endpoint in a +/// sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param endpoints A sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, an iterator denoting the successfully + * // connected endpoint. Otherwise, the end iterator. + * Iterator iterator + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * + * // ... + * + * r.async_resolve(q, resolve_handler); + * + * // ... + * + * void resolve_handler( + * const asio::error_code& ec, + * tcp::resolver::results_type results) + * { + * if (!ec) + * { + * asio::async_connect(s, results, + * my_connect_condition(), + * connect_handler); + * } + * } + * + * // ... + * + * void connect_handler( + * const asio::error_code& ec, + * const tcp::endpoint& endpoint) + * { + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * std::cout << "Connected to: " << endpoint << std::endl; + * } + * } @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(RangeConnectHandler, + void (asio::error_code, typename Protocol::endpoint)) +async_connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + ASIO_MOVE_ARG(RangeConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); + +#if !defined(ASIO_NO_DEPRECATED) +/// (Deprecated: Use range overload.) Asynchronously establishes a socket +/// connection by trying each endpoint in a sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, an iterator denoting the successfully + * // connected endpoint. Otherwise, the end iterator. + * Iterator iterator + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload assumes that a default constructed object of type @c + * Iterator represents the end of the sequence. This is a valid assumption for + * iterator types such as @c asio::ip::tcp::resolver::iterator. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + ConnectCondition connect_condition, + ASIO_MOVE_ARG(IteratorConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Asynchronously establishes a socket connection by trying each endpoint in a +/// sequence. +/** + * This function attempts to connect a socket to one of a sequence of + * endpoints. It does this by repeated calls to the socket's @c async_connect + * member function, once for each endpoint in the sequence, until a connection + * is successfully established. + * + * @param s The socket to be connected. If the socket is already open, it will + * be closed. + * + * @param begin An iterator pointing to the start of a sequence of endpoints. + * + * @param end An iterator pointing to the end of a sequence of endpoints. + * + * @param connect_condition A function object that is called prior to each + * connection attempt. The signature of the function object must be: + * @code bool connect_condition( + * const asio::error_code& ec, + * const typename Protocol::endpoint& next); @endcode + * The @c ec parameter contains the result from the most recent connect + * operation. Before the first connection attempt, @c ec is always set to + * indicate success. The @c next parameter is the next endpoint to be tried. + * The function object should return true if the next endpoint should be tried, + * and false if it should be skipped. + * + * @param handler The handler to be called when the connect operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * // Result of operation. if the sequence is empty, set to + * // asio::error::not_found. Otherwise, contains the + * // error from the last connection attempt. + * const asio::error_code& error, + * + * // On success, an iterator denoting the successfully + * // connected endpoint. Otherwise, the end iterator. + * Iterator iterator + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * The following connect condition function object can be used to output + * information about the individual connection attempts: + * @code struct my_connect_condition + * { + * bool operator()( + * const asio::error_code& ec, + * const::tcp::endpoint& next) + * { + * if (ec) std::cout << "Error: " << ec.message() << std::endl; + * std::cout << "Trying: " << next << std::endl; + * return true; + * } + * }; @endcode + * It would be used with the asio::connect function as follows: + * @code tcp::resolver r(my_context); + * tcp::resolver::query q("host", "service"); + * tcp::socket s(my_context); + * + * // ... + * + * r.async_resolve(q, resolve_handler); + * + * // ... + * + * void resolve_handler( + * const asio::error_code& ec, + * tcp::resolver::iterator i) + * { + * if (!ec) + * { + * tcp::resolver::iterator end; + * asio::async_connect(s, i, end, + * my_connect_condition(), + * connect_handler); + * } + * } + * + * // ... + * + * void connect_handler( + * const asio::error_code& ec, + * tcp::resolver::iterator i) + * { + * if (ec) + * { + * // An error occurred. + * } + * else + * { + * std::cout << "Connected to: " << i->endpoint() << std::endl; + * } + * } @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + Iterator end, ConnectCondition connect_condition, + ASIO_MOVE_ARG(IteratorConnectHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(Executor)); + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/connect.hpp" + +#endif diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/coroutine.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/coroutine.hpp new file mode 100644 index 00000000..7c8e5799 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/coroutine.hpp @@ -0,0 +1,328 @@ +// +// coroutine.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_COROUTINE_HPP +#define ASIO_COROUTINE_HPP + +namespace asio { +namespace detail { + +class coroutine_ref; + +} // namespace detail + +/// Provides support for implementing stackless coroutines. +/** + * The @c coroutine class may be used to implement stackless coroutines. The + * class itself is used to store the current state of the coroutine. + * + * Coroutines are copy-constructible and assignable, and the space overhead is + * a single int. They can be used as a base class: + * + * @code class session : coroutine + * { + * ... + * }; @endcode + * + * or as a data member: + * + * @code class session + * { + * ... + * coroutine coro_; + * }; @endcode + * + * or even bound in as a function argument using lambdas or @c bind(). The + * important thing is that as the application maintains a copy of the object + * for as long as the coroutine must be kept alive. + * + * @par Pseudo-keywords + * + * A coroutine is used in conjunction with certain "pseudo-keywords", which + * are implemented as macros. These macros are defined by a header file: + * + * @code #include @endcode + * + * and may conversely be undefined as follows: + * + * @code #include @endcode + * + * reenter + * + * The @c reenter macro is used to define the body of a coroutine. It takes a + * single argument: a pointer or reference to a coroutine object. For example, + * if the base class is a coroutine object you may write: + * + * @code reenter (this) + * { + * ... coroutine body ... + * } @endcode + * + * and if a data member or other variable you can write: + * + * @code reenter (coro_) + * { + * ... coroutine body ... + * } @endcode + * + * When @c reenter is executed at runtime, control jumps to the location of the + * last @c yield or @c fork. + * + * The coroutine body may also be a single statement, such as: + * + * @code reenter (this) for (;;) + * { + * ... + * } @endcode + * + * @b Limitation: The @c reenter macro is implemented using a switch. This + * means that you must take care when using local variables within the + * coroutine body. The local variable is not allowed in a position where + * reentering the coroutine could bypass the variable definition. + * + * yield statement + * + * This form of the @c yield keyword is often used with asynchronous operations: + * + * @code yield socket_->async_read_some(buffer(*buffer_), *this); @endcode + * + * This divides into four logical steps: + * + * @li @c yield saves the current state of the coroutine. + * @li The statement initiates the asynchronous operation. + * @li The resume point is defined immediately following the statement. + * @li Control is transferred to the end of the coroutine body. + * + * When the asynchronous operation completes, the function object is invoked + * and @c reenter causes control to transfer to the resume point. It is + * important to remember to carry the coroutine state forward with the + * asynchronous operation. In the above snippet, the current class is a + * function object object with a coroutine object as base class or data member. + * + * The statement may also be a compound statement, and this permits us to + * define local variables with limited scope: + * + * @code yield + * { + * mutable_buffers_1 b = buffer(*buffer_); + * socket_->async_read_some(b, *this); + * } @endcode + * + * yield return expression ; + * + * This form of @c yield is often used in generators or coroutine-based parsers. + * For example, the function object: + * + * @code struct interleave : coroutine + * { + * istream& is1; + * istream& is2; + * char operator()(char c) + * { + * reenter (this) for (;;) + * { + * yield return is1.get(); + * yield return is2.get(); + * } + * } + * }; @endcode + * + * defines a trivial coroutine that interleaves the characters from two input + * streams. + * + * This type of @c yield divides into three logical steps: + * + * @li @c yield saves the current state of the coroutine. + * @li The resume point is defined immediately following the semicolon. + * @li The value of the expression is returned from the function. + * + * yield ; + * + * This form of @c yield is equivalent to the following steps: + * + * @li @c yield saves the current state of the coroutine. + * @li The resume point is defined immediately following the semicolon. + * @li Control is transferred to the end of the coroutine body. + * + * This form might be applied when coroutines are used for cooperative + * threading and scheduling is explicitly managed. For example: + * + * @code struct task : coroutine + * { + * ... + * void operator()() + * { + * reenter (this) + * { + * while (... not finished ...) + * { + * ... do something ... + * yield; + * ... do some more ... + * yield; + * } + * } + * } + * ... + * }; + * ... + * task t1, t2; + * for (;;) + * { + * t1(); + * t2(); + * } @endcode + * + * yield break ; + * + * The final form of @c yield is used to explicitly terminate the coroutine. + * This form is comprised of two steps: + * + * @li @c yield sets the coroutine state to indicate termination. + * @li Control is transferred to the end of the coroutine body. + * + * Once terminated, calls to is_complete() return true and the coroutine cannot + * be reentered. + * + * Note that a coroutine may also be implicitly terminated if the coroutine + * body is exited without a yield, e.g. by return, throw or by running to the + * end of the body. + * + * fork statement + * + * The @c fork pseudo-keyword is used when "forking" a coroutine, i.e. splitting + * it into two (or more) copies. One use of @c fork is in a server, where a new + * coroutine is created to handle each client connection: + * + * @code reenter (this) + * { + * do + * { + * socket_.reset(new tcp::socket(my_context_)); + * yield acceptor->async_accept(*socket_, *this); + * fork server(*this)(); + * } while (is_parent()); + * ... client-specific handling follows ... + * } @endcode + * + * The logical steps involved in a @c fork are: + * + * @li @c fork saves the current state of the coroutine. + * @li The statement creates a copy of the coroutine and either executes it + * immediately or schedules it for later execution. + * @li The resume point is defined immediately following the semicolon. + * @li For the "parent", control immediately continues from the next line. + * + * The functions is_parent() and is_child() can be used to differentiate + * between parent and child. You would use these functions to alter subsequent + * control flow. + * + * Note that @c fork doesn't do the actual forking by itself. It is the + * application's responsibility to create a clone of the coroutine and call it. + * The clone can be called immediately, as above, or scheduled for delayed + * execution using something like asio::post(). + * + * @par Alternate macro names + * + * If preferred, an application can use macro names that follow a more typical + * naming convention, rather than the pseudo-keywords. These are: + * + * @li @c ASIO_CORO_REENTER instead of @c reenter + * @li @c ASIO_CORO_YIELD instead of @c yield + * @li @c ASIO_CORO_FORK instead of @c fork + */ +class coroutine +{ +public: + /// Constructs a coroutine in its initial state. + coroutine() : value_(0) {} + + /// Returns true if the coroutine is the child of a fork. + bool is_child() const { return value_ < 0; } + + /// Returns true if the coroutine is the parent of a fork. + bool is_parent() const { return !is_child(); } + + /// Returns true if the coroutine has reached its terminal state. + bool is_complete() const { return value_ == -1; } + +private: + friend class detail::coroutine_ref; + int value_; +}; + + +namespace detail { + +class coroutine_ref +{ +public: + coroutine_ref(coroutine& c) : value_(c.value_), modified_(false) {} + coroutine_ref(coroutine* c) : value_(c->value_), modified_(false) {} + ~coroutine_ref() { if (!modified_) value_ = -1; } + operator int() const { return value_; } + int& operator=(int v) { modified_ = true; return value_ = v; } +private: + void operator=(const coroutine_ref&); + int& value_; + bool modified_; +}; + +} // namespace detail +} // namespace asio + +#define ASIO_CORO_REENTER(c) \ + switch (::asio::detail::coroutine_ref _coro_value = c) \ + case -1: if (_coro_value) \ + { \ + goto terminate_coroutine; \ + terminate_coroutine: \ + _coro_value = -1; \ + goto bail_out_of_coroutine; \ + bail_out_of_coroutine: \ + break; \ + } \ + else /* fall-through */ case 0: + +#define ASIO_CORO_YIELD_IMPL(n) \ + for (_coro_value = (n);;) \ + if (_coro_value == 0) \ + { \ + case (n): ; \ + break; \ + } \ + else \ + switch (_coro_value ? 0 : 1) \ + for (;;) \ + /* fall-through */ case -1: if (_coro_value) \ + goto terminate_coroutine; \ + else for (;;) \ + /* fall-through */ case 1: if (_coro_value) \ + goto bail_out_of_coroutine; \ + else /* fall-through */ case 0: + +#define ASIO_CORO_FORK_IMPL(n) \ + for (_coro_value = -(n);; _coro_value = (n)) \ + if (_coro_value == (n)) \ + { \ + case -(n): ; \ + break; \ + } \ + else + +#if defined(_MSC_VER) +# define ASIO_CORO_YIELD ASIO_CORO_YIELD_IMPL(__COUNTER__ + 1) +# define ASIO_CORO_FORK ASIO_CORO_FORK_IMPL(__COUNTER__ + 1) +#else // defined(_MSC_VER) +# define ASIO_CORO_YIELD ASIO_CORO_YIELD_IMPL(__LINE__) +# define ASIO_CORO_FORK ASIO_CORO_FORK_IMPL(__LINE__) +#endif // defined(_MSC_VER) + +#endif // ASIO_COROUTINE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/deadline_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/deadline_timer.hpp new file mode 100644 index 00000000..3f837da4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/deadline_timer.hpp @@ -0,0 +1,38 @@ +// +// deadline_timer.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DEADLINE_TIMER_HPP +#define ASIO_DEADLINE_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/socket_types.hpp" // Must come before posix_time. +#include "asio/basic_deadline_timer.hpp" + +#include + +namespace asio { + +/// Typedef for the typical usage of timer. Uses a UTC clock. +typedef basic_deadline_timer deadline_timer; + +} // namespace asio + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_DEADLINE_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/defer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/defer.hpp new file mode 100644 index 00000000..dd5275e4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/defer.hpp @@ -0,0 +1,127 @@ +// +// defer.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DEFER_HPP +#define ASIO_DEFER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the object's associated + * executor. The function object is queued for execution, and is never called + * from the current thread prior to returning from defer(). + * + * The use of @c defer(), rather than @ref post(), indicates the caller's + * preference that the executor defer the queueing of the function object. This + * may allow the executor to optimise queueing for cases when the function + * object represents a continuation of the current call context. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex by performing + * get_associated_executor(handler). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Performs ex.defer(std::move(handler), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + ASIO_MOVE_ARG(CompletionToken) token); + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the specified executor. + * The function object is queued for execution, and is never called from the + * current thread prior to returning from defer(). + * + * The use of @c defer(), rather than @ref post(), indicates the caller's + * preference that the executor defer the queueing of the function object. This + * may allow the executor to optimise queueing for cases when the function + * object represents a continuation of the current call context. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex1 by performing + * get_associated_executor(handler). + * + * @li Creates a work object @c w by performing make_work(ex1). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Constructs a function object @c f with a function call operator that + * performs ex1.dispatch(std::move(handler), alloc) followed by + * w.reset(). + * + * @li Performs Executor(ex).defer(std::move(f), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + const Executor& ex, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); + +/// Submits a completion token or function object for execution. +/** + * @returns defer(ctx.get_executor(), forward(token)). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + ExecutionContext& ctx, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN( + typename ExecutionContext::executor_type), + typename enable_if::value>::type* = 0); + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/defer.hpp" + +#endif // ASIO_DEFER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detached.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detached.hpp new file mode 100644 index 00000000..332ed24f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detached.hpp @@ -0,0 +1,62 @@ +// +// detached.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETACHED_HPP +#define ASIO_DETACHED_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Class used to specify that an asynchronous operation is detached. +/** + + * The detached_t class is used to indicate that an asynchronous operation is + * detached. That is, there is no completion handler waiting for the + * operation's result. A detached_t object may be passed as a handler to an + * asynchronous operation, typically using the special value + * @c asio::detached. For example: + + * @code my_socket.async_send(my_buffer, asio::detached); + * @endcode + */ +class detached_t +{ +public: + /// Constructor. + ASIO_CONSTEXPR detached_t() + { + } +}; + +/// A special value, similar to std::nothrow. +/** + * See the documentation for asio::detached_t for a usage example. + */ +#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) +constexpr detached_t detached; +#elif defined(ASIO_MSVC) +__declspec(selectany) detached_t detached; +#endif + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/detached.hpp" + +#endif // ASIO_DETACHED_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array.hpp new file mode 100644 index 00000000..4c63f981 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array.hpp @@ -0,0 +1,38 @@ +// +// detail/array.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_ARRAY_HPP +#define ASIO_DETAIL_ARRAY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_ARRAY) +# include +#else // defined(ASIO_HAS_STD_ARRAY) +# include +#endif // defined(ASIO_HAS_STD_ARRAY) + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_STD_ARRAY) +using std::array; +#else // defined(ASIO_HAS_STD_ARRAY) +using boost::array; +#endif // defined(ASIO_HAS_STD_ARRAY) + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_ARRAY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array_fwd.hpp new file mode 100644 index 00000000..e44b001d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/array_fwd.hpp @@ -0,0 +1,34 @@ +// +// detail/array_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_ARRAY_FWD_HPP +#define ASIO_DETAIL_ARRAY_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +namespace boost { + +template +class array; + +} // namespace boost + +// Standard library components can't be forward declared, so we'll have to +// include the array header. Fortunately, it's fairly lightweight and doesn't +// add significantly to the compile time. +#if defined(ASIO_HAS_STD_ARRAY) +# include +#endif // defined(ASIO_HAS_STD_ARRAY) + +#endif // ASIO_DETAIL_ARRAY_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/assert.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/assert.hpp new file mode 100644 index 00000000..72a96bb9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/assert.hpp @@ -0,0 +1,32 @@ +// +// detail/assert.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_ASSERT_HPP +#define ASIO_DETAIL_ASSERT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_ASSERT) +# include +#else // defined(ASIO_HAS_BOOST_ASSERT) +# include +#endif // defined(ASIO_HAS_BOOST_ASSERT) + +#if defined(ASIO_HAS_BOOST_ASSERT) +# define ASIO_ASSERT(expr) BOOST_ASSERT(expr) +#else // defined(ASIO_HAS_BOOST_ASSERT) +# define ASIO_ASSERT(expr) assert(expr) +#endif // defined(ASIO_HAS_BOOST_ASSERT) + +#endif // ASIO_DETAIL_ASSERT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/atomic_count.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/atomic_count.hpp new file mode 100644 index 00000000..be7b151a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/atomic_count.hpp @@ -0,0 +1,45 @@ +// +// detail/atomic_count.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_ATOMIC_COUNT_HPP +#define ASIO_DETAIL_ATOMIC_COUNT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +// Nothing to include. +#elif defined(ASIO_HAS_STD_ATOMIC) +# include +#else // defined(ASIO_HAS_STD_ATOMIC) +# include +#endif // defined(ASIO_HAS_STD_ATOMIC) + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) +typedef long atomic_count; +inline void increment(atomic_count& a, long b) { a += b; } +#elif defined(ASIO_HAS_STD_ATOMIC) +typedef std::atomic atomic_count; +inline void increment(atomic_count& a, long b) { a += b; } +#else // defined(ASIO_HAS_STD_ATOMIC) +typedef boost::detail::atomic_count atomic_count; +inline void increment(atomic_count& a, long b) { while (b > 0) ++a, --b; } +#endif // defined(ASIO_HAS_STD_ATOMIC) + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_ATOMIC_COUNT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/base_from_completion_cond.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/base_from_completion_cond.hpp new file mode 100644 index 00000000..9f695f10 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/base_from_completion_cond.hpp @@ -0,0 +1,69 @@ +// +// detail/base_from_completion_cond.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_BASE_FROM_COMPLETION_COND_HPP +#define ASIO_DETAIL_BASE_FROM_COMPLETION_COND_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/completion_condition.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class base_from_completion_cond +{ +protected: + explicit base_from_completion_cond(CompletionCondition& completion_condition) + : completion_condition_( + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)) + { + } + + std::size_t check_for_completion( + const asio::error_code& ec, + std::size_t total_transferred) + { + return detail::adapt_completion_condition_result( + completion_condition_(ec, total_transferred)); + } + +private: + CompletionCondition completion_condition_; +}; + +template <> +class base_from_completion_cond +{ +protected: + explicit base_from_completion_cond(transfer_all_t) + { + } + + static std::size_t check_for_completion( + const asio::error_code& ec, + std::size_t total_transferred) + { + return transfer_all_t()(ec, total_transferred); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_BASE_FROM_COMPLETION_COND_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/bind_handler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/bind_handler.hpp new file mode 100644 index 00000000..feb333c2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/bind_handler.hpp @@ -0,0 +1,816 @@ +// +// detail/bind_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_BIND_HANDLER_HPP +#define ASIO_DETAIL_BIND_HANDLER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class binder1 +{ +public: + template + binder1(int, ASIO_MOVE_ARG(T) handler, const Arg1& arg1) + : handler_(ASIO_MOVE_CAST(T)(handler)), + arg1_(arg1) + { + } + + binder1(Handler& handler, const Arg1& arg1) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1) + { + } + +#if defined(ASIO_HAS_MOVE) + binder1(const binder1& other) + : handler_(other.handler_), + arg1_(other.arg1_) + { + } + + binder1(binder1&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(static_cast(arg1_)); + } + + void operator()() const + { + handler_(arg1_); + } + +//private: + Handler handler_; + Arg1 arg1_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + binder1* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + binder1* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + binder1* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + binder1* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + binder1* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline binder1::type, Arg1> bind_handler( + ASIO_MOVE_ARG(Handler) handler, const Arg1& arg1) +{ + return binder1::type, Arg1>(0, + ASIO_MOVE_CAST(Handler)(handler), arg1); +} + +template +class binder2 +{ +public: + template + binder2(int, ASIO_MOVE_ARG(T) handler, + const Arg1& arg1, const Arg2& arg2) + : handler_(ASIO_MOVE_CAST(T)(handler)), + arg1_(arg1), + arg2_(arg2) + { + } + + binder2(Handler& handler, const Arg1& arg1, const Arg2& arg2) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1), + arg2_(arg2) + { + } + +#if defined(ASIO_HAS_MOVE) + binder2(const binder2& other) + : handler_(other.handler_), + arg1_(other.arg1_), + arg2_(other.arg2_) + { + } + + binder2(binder2&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)), + arg2_(ASIO_MOVE_CAST(Arg2)(other.arg2_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(static_cast(arg1_), + static_cast(arg2_)); + } + + void operator()() const + { + handler_(arg1_, arg2_); + } + +//private: + Handler handler_; + Arg1 arg1_; + Arg2 arg2_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + binder2* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + binder2* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + binder2* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + binder2* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + binder2* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline binder2::type, Arg1, Arg2> bind_handler( + ASIO_MOVE_ARG(Handler) handler, const Arg1& arg1, const Arg2& arg2) +{ + return binder2::type, Arg1, Arg2>(0, + ASIO_MOVE_CAST(Handler)(handler), arg1, arg2); +} + +template +class binder3 +{ +public: + template + binder3(int, ASIO_MOVE_ARG(T) handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3) + : handler_(ASIO_MOVE_CAST(T)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3) + { + } + + binder3(Handler& handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3) + { + } + +#if defined(ASIO_HAS_MOVE) + binder3(const binder3& other) + : handler_(other.handler_), + arg1_(other.arg1_), + arg2_(other.arg2_), + arg3_(other.arg3_) + { + } + + binder3(binder3&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)), + arg2_(ASIO_MOVE_CAST(Arg2)(other.arg2_)), + arg3_(ASIO_MOVE_CAST(Arg3)(other.arg3_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(static_cast(arg1_), + static_cast(arg2_), static_cast(arg3_)); + } + + void operator()() const + { + handler_(arg1_, arg2_, arg3_); + } + +//private: + Handler handler_; + Arg1 arg1_; + Arg2 arg2_; + Arg3 arg3_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + binder3* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + binder3* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + binder3* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + binder3* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + binder3* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline binder3::type, Arg1, Arg2, Arg3> bind_handler( + ASIO_MOVE_ARG(Handler) handler, const Arg1& arg1, const Arg2& arg2, + const Arg3& arg3) +{ + return binder3::type, Arg1, Arg2, Arg3>(0, + ASIO_MOVE_CAST(Handler)(handler), arg1, arg2, arg3); +} + +template +class binder4 +{ +public: + template + binder4(int, ASIO_MOVE_ARG(T) handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) + : handler_(ASIO_MOVE_CAST(T)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3), + arg4_(arg4) + { + } + + binder4(Handler& handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3), + arg4_(arg4) + { + } + +#if defined(ASIO_HAS_MOVE) + binder4(const binder4& other) + : handler_(other.handler_), + arg1_(other.arg1_), + arg2_(other.arg2_), + arg3_(other.arg3_), + arg4_(other.arg4_) + { + } + + binder4(binder4&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)), + arg2_(ASIO_MOVE_CAST(Arg2)(other.arg2_)), + arg3_(ASIO_MOVE_CAST(Arg3)(other.arg3_)), + arg4_(ASIO_MOVE_CAST(Arg4)(other.arg4_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(static_cast(arg1_), + static_cast(arg2_), static_cast(arg3_), + static_cast(arg4_)); + } + + void operator()() const + { + handler_(arg1_, arg2_, arg3_, arg4_); + } + +//private: + Handler handler_; + Arg1 arg1_; + Arg2 arg2_; + Arg3 arg3_; + Arg4 arg4_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + binder4* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + binder4* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + binder4* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + binder4* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + binder4* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline binder4::type, Arg1, Arg2, Arg3, Arg4> +bind_handler(ASIO_MOVE_ARG(Handler) handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) +{ + return binder4::type, Arg1, Arg2, Arg3, Arg4>(0, + ASIO_MOVE_CAST(Handler)(handler), arg1, arg2, arg3, arg4); +} + +template +class binder5 +{ +public: + template + binder5(int, ASIO_MOVE_ARG(T) handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) + : handler_(ASIO_MOVE_CAST(T)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3), + arg4_(arg4), + arg5_(arg5) + { + } + + binder5(Handler& handler, const Arg1& arg1, const Arg2& arg2, + const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1), + arg2_(arg2), + arg3_(arg3), + arg4_(arg4), + arg5_(arg5) + { + } + +#if defined(ASIO_HAS_MOVE) + binder5(const binder5& other) + : handler_(other.handler_), + arg1_(other.arg1_), + arg2_(other.arg2_), + arg3_(other.arg3_), + arg4_(other.arg4_), + arg5_(other.arg5_) + { + } + + binder5(binder5&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)), + arg2_(ASIO_MOVE_CAST(Arg2)(other.arg2_)), + arg3_(ASIO_MOVE_CAST(Arg3)(other.arg3_)), + arg4_(ASIO_MOVE_CAST(Arg4)(other.arg4_)), + arg5_(ASIO_MOVE_CAST(Arg5)(other.arg5_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(static_cast(arg1_), + static_cast(arg2_), static_cast(arg3_), + static_cast(arg4_), static_cast(arg5_)); + } + + void operator()() const + { + handler_(arg1_, arg2_, arg3_, arg4_, arg5_); + } + +//private: + Handler handler_; + Arg1 arg1_; + Arg2 arg2_; + Arg3 arg3_; + Arg4 arg4_; + Arg5 arg5_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + binder5* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + binder5* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + binder5* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + binder5* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + binder5* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline binder5::type, Arg1, Arg2, Arg3, Arg4, Arg5> +bind_handler(ASIO_MOVE_ARG(Handler) handler, const Arg1& arg1, + const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) +{ + return binder5::type, Arg1, Arg2, Arg3, Arg4, Arg5>(0, + ASIO_MOVE_CAST(Handler)(handler), arg1, arg2, arg3, arg4, arg5); +} + +#if defined(ASIO_HAS_MOVE) + +template +class move_binder1 +{ +public: + move_binder1(int, ASIO_MOVE_ARG(Handler) handler, + ASIO_MOVE_ARG(Arg1) arg1) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(ASIO_MOVE_CAST(Arg1)(arg1)) + { + } + + move_binder1(move_binder1&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)) + { + } + + void operator()() + { + handler_(ASIO_MOVE_CAST(Arg1)(arg1_)); + } + +//private: + Handler handler_; + Arg1 arg1_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + move_binder1* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + move_binder1* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + move_binder1* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(ASIO_MOVE_ARG(Function) function, + move_binder1* this_handler) +{ + asio_handler_invoke_helpers::invoke( + ASIO_MOVE_CAST(Function)(function), this_handler->handler_); +} + +template +class move_binder2 +{ +public: + move_binder2(int, ASIO_MOVE_ARG(Handler) handler, + const Arg1& arg1, ASIO_MOVE_ARG(Arg2) arg2) + : handler_(ASIO_MOVE_CAST(Handler)(handler)), + arg1_(arg1), + arg2_(ASIO_MOVE_CAST(Arg2)(arg2)) + { + } + + move_binder2(move_binder2&& other) + : handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + arg1_(ASIO_MOVE_CAST(Arg1)(other.arg1_)), + arg2_(ASIO_MOVE_CAST(Arg2)(other.arg2_)) + { + } + + void operator()() + { + handler_(static_cast(arg1_), + ASIO_MOVE_CAST(Arg2)(arg2_)); + } + +//private: + Handler handler_; + Arg1 arg1_; + Arg2 arg2_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + move_binder2* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + move_binder2* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + move_binder2* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(ASIO_MOVE_ARG(Function) function, + move_binder2* this_handler) +{ + asio_handler_invoke_helpers::invoke( + ASIO_MOVE_CAST(Function)(function), this_handler->handler_); +} + +#endif // defined(ASIO_HAS_MOVE) + +} // namespace detail + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::binder1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::binder2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::binder1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::binder2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#if defined(ASIO_HAS_MOVE) + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::move_binder1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_allocator< + detail::move_binder2, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::move_binder2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::move_binder1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::move_binder2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // defined(ASIO_HAS_MOVE) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_BIND_HANDLER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_resize_guard.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_resize_guard.hpp new file mode 100644 index 00000000..c0bb949d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_resize_guard.hpp @@ -0,0 +1,66 @@ +// +// detail/buffer_resize_guard.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP +#define ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/limits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper class to manage buffer resizing in an exception safe way. +template +class buffer_resize_guard +{ +public: + // Constructor. + buffer_resize_guard(Buffer& buffer) + : buffer_(buffer), + old_size_(buffer.size()) + { + } + + // Destructor rolls back the buffer resize unless commit was called. + ~buffer_resize_guard() + { + if (old_size_ != (std::numeric_limits::max)()) + { + buffer_.resize(old_size_); + } + } + + // Commit the resize transaction. + void commit() + { + old_size_ = (std::numeric_limits::max)(); + } + +private: + // The buffer being managed. + Buffer& buffer_; + + // The size of the buffer at the time the guard was constructed. + size_t old_size_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_BUFFER_RESIZE_GUARD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_sequence_adapter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_sequence_adapter.hpp new file mode 100644 index 00000000..d979726a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffer_sequence_adapter.hpp @@ -0,0 +1,544 @@ +// +// detail/buffer_sequence_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP +#define ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/buffer.hpp" +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class buffer_sequence_adapter_base +{ +#if defined(ASIO_WINDOWS_RUNTIME) +public: + // The maximum number of buffers to support in a single operation. + enum { max_buffers = 1 }; + +protected: + typedef Windows::Storage::Streams::IBuffer^ native_buffer_type; + + ASIO_DECL static void init_native_buffer( + native_buffer_type& buf, + const asio::mutable_buffer& buffer); + + ASIO_DECL static void init_native_buffer( + native_buffer_type& buf, + const asio::const_buffer& buffer); +#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) +public: + // The maximum number of buffers to support in a single operation. + enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; + +protected: + typedef WSABUF native_buffer_type; + + static void init_native_buffer(WSABUF& buf, + const asio::mutable_buffer& buffer) + { + buf.buf = static_cast(buffer.data()); + buf.len = static_cast(buffer.size()); + } + + static void init_native_buffer(WSABUF& buf, + const asio::const_buffer& buffer) + { + buf.buf = const_cast(static_cast(buffer.data())); + buf.len = static_cast(buffer.size()); + } +#else // defined(ASIO_WINDOWS) || defined(__CYGWIN__) +public: + // The maximum number of buffers to support in a single operation. + enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; + +protected: + typedef iovec native_buffer_type; + + static void init_iov_base(void*& base, void* addr) + { + base = addr; + } + + template + static void init_iov_base(T& base, void* addr) + { + base = static_cast(addr); + } + + static void init_native_buffer(iovec& iov, + const asio::mutable_buffer& buffer) + { + init_iov_base(iov.iov_base, buffer.data()); + iov.iov_len = buffer.size(); + } + + static void init_native_buffer(iovec& iov, + const asio::const_buffer& buffer) + { + init_iov_base(iov.iov_base, const_cast(buffer.data())); + iov.iov_len = buffer.size(); + } +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) +}; + +// Helper class to translate buffers into the native buffer representation. +template +class buffer_sequence_adapter + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter(const Buffers& buffer_sequence) + : count_(0), total_buffer_size_(0) + { + buffer_sequence_adapter::init( + asio::buffer_sequence_begin(buffer_sequence), + asio::buffer_sequence_end(buffer_sequence)); + } + + native_buffer_type* buffers() + { + return buffers_; + } + + std::size_t count() const + { + return count_; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const Buffers& buffer_sequence) + { + return buffer_sequence_adapter::all_empty( + asio::buffer_sequence_begin(buffer_sequence), + asio::buffer_sequence_end(buffer_sequence)); + } + + static void validate(const Buffers& buffer_sequence) + { + buffer_sequence_adapter::validate( + asio::buffer_sequence_begin(buffer_sequence), + asio::buffer_sequence_end(buffer_sequence)); + } + + static Buffer first(const Buffers& buffer_sequence) + { + return buffer_sequence_adapter::first( + asio::buffer_sequence_begin(buffer_sequence), + asio::buffer_sequence_end(buffer_sequence)); + } + +private: + template + void init(Iterator begin, Iterator end) + { + Iterator iter = begin; + for (; iter != end && count_ < max_buffers; ++iter, ++count_) + { + Buffer buffer(*iter); + init_native_buffer(buffers_[count_], buffer); + total_buffer_size_ += buffer.size(); + } + } + + template + static bool all_empty(Iterator begin, Iterator end) + { + Iterator iter = begin; + std::size_t i = 0; + for (; iter != end && i < max_buffers; ++iter, ++i) + if (Buffer(*iter).size() > 0) + return false; + return true; + } + + template + static void validate(Iterator begin, Iterator end) + { + Iterator iter = begin; + for (; iter != end; ++iter) + { + Buffer buffer(*iter); + buffer.data(); + } + } + + template + static Buffer first(Iterator begin, Iterator end) + { + Iterator iter = begin; + for (; iter != end; ++iter) + { + Buffer buffer(*iter); + if (buffer.size() != 0) + return buffer; + } + return Buffer(); + } + + native_buffer_type buffers_[max_buffers]; + std::size_t count_; + std::size_t total_buffer_size_; +}; + +template +class buffer_sequence_adapter + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const asio::mutable_buffer& buffer_sequence) + { + init_native_buffer(buffer_, Buffer(buffer_sequence)); + total_buffer_size_ = buffer_sequence.size(); + } + + native_buffer_type* buffers() + { + return &buffer_; + } + + std::size_t count() const + { + return 1; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const asio::mutable_buffer& buffer_sequence) + { + return buffer_sequence.size() == 0; + } + + static void validate(const asio::mutable_buffer& buffer_sequence) + { + buffer_sequence.data(); + } + + static Buffer first(const asio::mutable_buffer& buffer_sequence) + { + return Buffer(buffer_sequence); + } + +private: + native_buffer_type buffer_; + std::size_t total_buffer_size_; +}; + +template +class buffer_sequence_adapter + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const asio::const_buffer& buffer_sequence) + { + init_native_buffer(buffer_, Buffer(buffer_sequence)); + total_buffer_size_ = buffer_sequence.size(); + } + + native_buffer_type* buffers() + { + return &buffer_; + } + + std::size_t count() const + { + return 1; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const asio::const_buffer& buffer_sequence) + { + return buffer_sequence.size() == 0; + } + + static void validate(const asio::const_buffer& buffer_sequence) + { + buffer_sequence.data(); + } + + static Buffer first(const asio::const_buffer& buffer_sequence) + { + return Buffer(buffer_sequence); + } + +private: + native_buffer_type buffer_; + std::size_t total_buffer_size_; +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template +class buffer_sequence_adapter + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const asio::mutable_buffers_1& buffer_sequence) + { + init_native_buffer(buffer_, Buffer(buffer_sequence)); + total_buffer_size_ = buffer_sequence.size(); + } + + native_buffer_type* buffers() + { + return &buffer_; + } + + std::size_t count() const + { + return 1; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const asio::mutable_buffers_1& buffer_sequence) + { + return buffer_sequence.size() == 0; + } + + static void validate(const asio::mutable_buffers_1& buffer_sequence) + { + buffer_sequence.data(); + } + + static Buffer first(const asio::mutable_buffers_1& buffer_sequence) + { + return Buffer(buffer_sequence); + } + +private: + native_buffer_type buffer_; + std::size_t total_buffer_size_; +}; + +template +class buffer_sequence_adapter + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const asio::const_buffers_1& buffer_sequence) + { + init_native_buffer(buffer_, Buffer(buffer_sequence)); + total_buffer_size_ = buffer_sequence.size(); + } + + native_buffer_type* buffers() + { + return &buffer_; + } + + std::size_t count() const + { + return 1; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const asio::const_buffers_1& buffer_sequence) + { + return buffer_sequence.size() == 0; + } + + static void validate(const asio::const_buffers_1& buffer_sequence) + { + buffer_sequence.data(); + } + + static Buffer first(const asio::const_buffers_1& buffer_sequence) + { + return Buffer(buffer_sequence); + } + +private: + native_buffer_type buffer_; + std::size_t total_buffer_size_; +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +class buffer_sequence_adapter > + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const boost::array& buffer_sequence) + { + init_native_buffer(buffers_[0], Buffer(buffer_sequence[0])); + init_native_buffer(buffers_[1], Buffer(buffer_sequence[1])); + total_buffer_size_ = buffer_sequence[0].size() + buffer_sequence[1].size(); + } + + native_buffer_type* buffers() + { + return buffers_; + } + + std::size_t count() const + { + return 2; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const boost::array& buffer_sequence) + { + return buffer_sequence[0].size() == 0 && buffer_sequence[1].size() == 0; + } + + static void validate(const boost::array& buffer_sequence) + { + buffer_sequence[0].data(); + buffer_sequence[1].data(); + } + + static Buffer first(const boost::array& buffer_sequence) + { + return Buffer(buffer_sequence[0].size() != 0 + ? buffer_sequence[0] : buffer_sequence[1]); + } + +private: + native_buffer_type buffers_[2]; + std::size_t total_buffer_size_; +}; + +#if defined(ASIO_HAS_STD_ARRAY) + +template +class buffer_sequence_adapter > + : buffer_sequence_adapter_base +{ +public: + explicit buffer_sequence_adapter( + const std::array& buffer_sequence) + { + init_native_buffer(buffers_[0], Buffer(buffer_sequence[0])); + init_native_buffer(buffers_[1], Buffer(buffer_sequence[1])); + total_buffer_size_ = buffer_sequence[0].size() + buffer_sequence[1].size(); + } + + native_buffer_type* buffers() + { + return buffers_; + } + + std::size_t count() const + { + return 2; + } + + std::size_t total_size() const + { + return total_buffer_size_; + } + + bool all_empty() const + { + return total_buffer_size_ == 0; + } + + static bool all_empty(const std::array& buffer_sequence) + { + return buffer_sequence[0].size() == 0 && buffer_sequence[1].size() == 0; + } + + static void validate(const std::array& buffer_sequence) + { + buffer_sequence[0].data(); + buffer_sequence[1].data(); + } + + static Buffer first(const std::array& buffer_sequence) + { + return Buffer(buffer_sequence[0].size() != 0 + ? buffer_sequence[0] : buffer_sequence[1]); + } + +private: + native_buffer_type buffers_[2]; + std::size_t total_buffer_size_; +}; + +#endif // defined(ASIO_HAS_STD_ARRAY) + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/buffer_sequence_adapter.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffered_stream_storage.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffered_stream_storage.hpp new file mode 100644 index 00000000..9223434d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/buffered_stream_storage.hpp @@ -0,0 +1,126 @@ +// +// detail/buffered_stream_storage.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_BUFFERED_STREAM_STORAGE_HPP +#define ASIO_DETAIL_BUFFERED_STREAM_STORAGE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/buffer.hpp" +#include "asio/detail/assert.hpp" +#include +#include +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class buffered_stream_storage +{ +public: + // The type of the bytes stored in the buffer. + typedef unsigned char byte_type; + + // The type used for offsets into the buffer. + typedef std::size_t size_type; + + // Constructor. + explicit buffered_stream_storage(std::size_t buffer_capacity) + : begin_offset_(0), + end_offset_(0), + buffer_(buffer_capacity) + { + } + + /// Clear the buffer. + void clear() + { + begin_offset_ = 0; + end_offset_ = 0; + } + + // Return a pointer to the beginning of the unread data. + mutable_buffer data() + { + return asio::buffer(buffer_) + begin_offset_; + } + + // Return a pointer to the beginning of the unread data. + const_buffer data() const + { + return asio::buffer(buffer_) + begin_offset_; + } + + // Is there no unread data in the buffer. + bool empty() const + { + return begin_offset_ == end_offset_; + } + + // Return the amount of unread data the is in the buffer. + size_type size() const + { + return end_offset_ - begin_offset_; + } + + // Resize the buffer to the specified length. + void resize(size_type length) + { + ASIO_ASSERT(length <= capacity()); + if (begin_offset_ + length <= capacity()) + { + end_offset_ = begin_offset_ + length; + } + else + { + using namespace std; // For memmove. + memmove(&buffer_[0], &buffer_[0] + begin_offset_, size()); + end_offset_ = length; + begin_offset_ = 0; + } + } + + // Return the maximum size for data in the buffer. + size_type capacity() const + { + return buffer_.size(); + } + + // Consume multiple bytes from the beginning of the buffer. + void consume(size_type count) + { + ASIO_ASSERT(begin_offset_ + count <= end_offset_); + begin_offset_ += count; + if (empty()) + clear(); + } + +private: + // The offset to the beginning of the unread data. + size_type begin_offset_; + + // The offset to the end of the unread data. + size_type end_offset_; + + // The data in the buffer. + std::vector buffer_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_BUFFERED_STREAM_STORAGE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/call_stack.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/call_stack.hpp new file mode 100644 index 00000000..fae9ce64 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/call_stack.hpp @@ -0,0 +1,125 @@ +// +// detail/call_stack.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CALL_STACK_HPP +#define ASIO_DETAIL_CALL_STACK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/tss_ptr.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper class to determine whether or not the current thread is inside an +// invocation of io_context::run() for a specified io_context object. +template +class call_stack +{ +public: + // Context class automatically pushes the key/value pair on to the stack. + class context + : private noncopyable + { + public: + // Push the key on to the stack. + explicit context(Key* k) + : key_(k), + next_(call_stack::top_) + { + value_ = reinterpret_cast(this); + call_stack::top_ = this; + } + + // Push the key/value pair on to the stack. + context(Key* k, Value& v) + : key_(k), + value_(&v), + next_(call_stack::top_) + { + call_stack::top_ = this; + } + + // Pop the key/value pair from the stack. + ~context() + { + call_stack::top_ = next_; + } + + // Find the next context with the same key. + Value* next_by_key() const + { + context* elem = next_; + while (elem) + { + if (elem->key_ == key_) + return elem->value_; + elem = elem->next_; + } + return 0; + } + + private: + friend class call_stack; + + // The key associated with the context. + Key* key_; + + // The value associated with the context. + Value* value_; + + // The next element in the stack. + context* next_; + }; + + friend class context; + + // Determine whether the specified owner is on the stack. Returns address of + // key if present, 0 otherwise. + static Value* contains(Key* k) + { + context* elem = top_; + while (elem) + { + if (elem->key_ == k) + return elem->value_; + elem = elem->next_; + } + return 0; + } + + // Obtain the value at the top of the stack. + static Value* top() + { + context* elem = top_; + return elem ? elem->value_ : 0; + } + +private: + // The top of the stack of calls for the current thread. + static tss_ptr top_; +}; + +template +tss_ptr::context> +call_stack::top_; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_CALL_STACK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono.hpp new file mode 100644 index 00000000..7e30b0da --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono.hpp @@ -0,0 +1,66 @@ +// +// detail/chrono.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CHRONO_HPP +#define ASIO_DETAIL_CHRONO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_CHRONO) +# include +#elif defined(ASIO_HAS_BOOST_CHRONO) +# include +#endif // defined(ASIO_HAS_BOOST_CHRONO) + +namespace asio { +namespace chrono { + +#if defined(ASIO_HAS_STD_CHRONO) +using std::chrono::duration; +using std::chrono::time_point; +using std::chrono::duration_cast; +using std::chrono::nanoseconds; +using std::chrono::microseconds; +using std::chrono::milliseconds; +using std::chrono::seconds; +using std::chrono::minutes; +using std::chrono::hours; +using std::chrono::time_point_cast; +#if defined(ASIO_HAS_STD_CHRONO_MONOTONIC_CLOCK) +typedef std::chrono::monotonic_clock steady_clock; +#else // defined(ASIO_HAS_STD_CHRONO_MONOTONIC_CLOCK) +using std::chrono::steady_clock; +#endif // defined(ASIO_HAS_STD_CHRONO_MONOTONIC_CLOCK) +using std::chrono::system_clock; +using std::chrono::high_resolution_clock; +#elif defined(ASIO_HAS_BOOST_CHRONO) +using boost::chrono::duration; +using boost::chrono::time_point; +using boost::chrono::duration_cast; +using boost::chrono::nanoseconds; +using boost::chrono::microseconds; +using boost::chrono::milliseconds; +using boost::chrono::seconds; +using boost::chrono::minutes; +using boost::chrono::hours; +using boost::chrono::time_point_cast; +using boost::chrono::system_clock; +using boost::chrono::steady_clock; +using boost::chrono::high_resolution_clock; +#endif // defined(ASIO_HAS_BOOST_CHRONO) + +} // namespace chrono +} // namespace asio + +#endif // ASIO_DETAIL_CHRONO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono_time_traits.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono_time_traits.hpp new file mode 100644 index 00000000..bd421a47 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/chrono_time_traits.hpp @@ -0,0 +1,190 @@ +// +// detail/chrono_time_traits.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP +#define ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/cstdint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper template to compute the greatest common divisor. +template +struct gcd { enum { value = gcd::value }; }; + +template +struct gcd { enum { value = v1 }; }; + +// Adapts std::chrono clocks for use with a deadline timer. +template +struct chrono_time_traits +{ + // The clock type. + typedef Clock clock_type; + + // The duration type of the clock. + typedef typename clock_type::duration duration_type; + + // The time point type of the clock. + typedef typename clock_type::time_point time_type; + + // The period of the clock. + typedef typename duration_type::period period_type; + + // Get the current time. + static time_type now() + { + return clock_type::now(); + } + + // Add a duration to a time. + static time_type add(const time_type& t, const duration_type& d) + { + const time_type epoch; + if (t >= epoch) + { + if ((time_type::max)() - t < d) + return (time_type::max)(); + } + else // t < epoch + { + if (-(t - (time_type::min)()) > d) + return (time_type::min)(); + } + + return t + d; + } + + // Subtract one time from another. + static duration_type subtract(const time_type& t1, const time_type& t2) + { + const time_type epoch; + if (t1 >= epoch) + { + if (t2 >= epoch) + { + return t1 - t2; + } + else if (t2 == (time_type::min)()) + { + return (duration_type::max)(); + } + else if ((time_type::max)() - t1 < epoch - t2) + { + return (duration_type::max)(); + } + else + { + return t1 - t2; + } + } + else // t1 < epoch + { + if (t2 < epoch) + { + return t1 - t2; + } + else if (t1 == (time_type::min)()) + { + return (duration_type::min)(); + } + else if ((time_type::max)() - t2 < epoch - t1) + { + return (duration_type::min)(); + } + else + { + return -(t2 - t1); + } + } + } + + // Test whether one time is less than another. + static bool less_than(const time_type& t1, const time_type& t2) + { + return t1 < t2; + } + + // Implement just enough of the posix_time::time_duration interface to supply + // what the timer_queue requires. + class posix_time_duration + { + public: + explicit posix_time_duration(const duration_type& d) + : d_(d) + { + } + + int64_t ticks() const + { + return d_.count(); + } + + int64_t total_seconds() const + { + return duration_cast<1, 1>(); + } + + int64_t total_milliseconds() const + { + return duration_cast<1, 1000>(); + } + + int64_t total_microseconds() const + { + return duration_cast<1, 1000000>(); + } + + private: + template + int64_t duration_cast() const + { + const int64_t num1 = period_type::num / gcd::value; + const int64_t num2 = Num / gcd::value; + + const int64_t den1 = period_type::den / gcd::value; + const int64_t den2 = Den / gcd::value; + + const int64_t num = num1 * den2; + const int64_t den = num2 * den1; + + if (num == 1 && den == 1) + return ticks(); + else if (num != 1 && den == 1) + return ticks() * num; + else if (num == 1 && period_type::den != 1) + return ticks() / den; + else + return ticks() * num / den; + } + + duration_type d_; + }; + + // Convert to POSIX duration type. + static posix_time_duration to_posix_duration(const duration_type& d) + { + return posix_time_duration(WaitTraits::to_wait_duration(d)); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/completion_handler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/completion_handler.hpp new file mode 100644 index 00000000..fef3e767 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/completion_handler.hpp @@ -0,0 +1,83 @@ +// +// detail/completion_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_COMPLETION_HANDLER_HPP +#define ASIO_DETAIL_COMPLETION_HANDLER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_work.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class completion_handler : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(completion_handler); + + completion_handler(Handler& h) + : operation(&completion_handler::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(h)) + { + handler_work::start(handler_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + completion_handler* h(static_cast(base)); + ptr p = { asio::detail::addressof(h->handler_), h, h }; + handler_work w(h->handler_); + + ASIO_HANDLER_COMPLETION((*h)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + Handler handler(ASIO_MOVE_CAST(Handler)(h->handler_)); + p.h = asio::detail::addressof(handler); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN(()); + w.complete(handler, handler); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_COMPLETION_HANDLER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/concurrency_hint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/concurrency_hint.hpp new file mode 100644 index 00000000..31cfeb07 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/concurrency_hint.hpp @@ -0,0 +1,94 @@ +// +// detail/concurrency_hint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CONCURRENCY_HINT_HPP +#define ASIO_DETAIL_CONCURRENCY_HINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" + +// The concurrency hint ID and mask are used to identify when a "well-known" +// concurrency hint value has been passed to the io_context. +#define ASIO_CONCURRENCY_HINT_ID 0xA5100000u +#define ASIO_CONCURRENCY_HINT_ID_MASK 0xFFFF0000u + +// If set, this bit indicates that the scheduler should perform locking. +#define ASIO_CONCURRENCY_HINT_LOCKING_SCHEDULER 0x1u + +// If set, this bit indicates that the reactor should perform locking when +// managing descriptor registrations. +#define ASIO_CONCURRENCY_HINT_LOCKING_REACTOR_REGISTRATION 0x2u + +// If set, this bit indicates that the reactor should perform locking for I/O. +#define ASIO_CONCURRENCY_HINT_LOCKING_REACTOR_IO 0x4u + +// Helper macro to determine if we have a special concurrency hint. +#define ASIO_CONCURRENCY_HINT_IS_SPECIAL(hint) \ + ((static_cast(hint) \ + & ASIO_CONCURRENCY_HINT_ID_MASK) \ + == ASIO_CONCURRENCY_HINT_ID) + +// Helper macro to determine if locking is enabled for a given facility. +#define ASIO_CONCURRENCY_HINT_IS_LOCKING(facility, hint) \ + (((static_cast(hint) \ + & (ASIO_CONCURRENCY_HINT_ID_MASK \ + | ASIO_CONCURRENCY_HINT_LOCKING_ ## facility)) \ + ^ ASIO_CONCURRENCY_HINT_ID) != 0) + +// This special concurrency hint disables locking in both the scheduler and +// reactor I/O. This hint has the following restrictions: +// +// - Care must be taken to ensure that all operations on the io_context and any +// of its associated I/O objects (such as sockets and timers) occur in only +// one thread at a time. +// +// - Asynchronous resolve operations fail with operation_not_supported. +// +// - If a signal_set is used with the io_context, signal_set objects cannot be +// used with any other io_context in the program. +#define ASIO_CONCURRENCY_HINT_UNSAFE \ + static_cast(ASIO_CONCURRENCY_HINT_ID) + +// This special concurrency hint disables locking in the reactor I/O. This hint +// has the following restrictions: +// +// - Care must be taken to ensure that run functions on the io_context, and all +// operations on the io_context's associated I/O objects (such as sockets and +// timers), occur in only one thread at a time. +#define ASIO_CONCURRENCY_HINT_UNSAFE_IO \ + static_cast(ASIO_CONCURRENCY_HINT_ID \ + | ASIO_CONCURRENCY_HINT_LOCKING_SCHEDULER \ + | ASIO_CONCURRENCY_HINT_LOCKING_REACTOR_REGISTRATION) + +// The special concurrency hint provides full thread safety. +#define ASIO_CONCURRENCY_HINT_SAFE \ + static_cast(ASIO_CONCURRENCY_HINT_ID \ + | ASIO_CONCURRENCY_HINT_LOCKING_SCHEDULER \ + | ASIO_CONCURRENCY_HINT_LOCKING_REACTOR_REGISTRATION \ + | ASIO_CONCURRENCY_HINT_LOCKING_REACTOR_IO) + +// This #define may be overridden at compile time to specify a program-wide +// default concurrency hint, used by the zero-argument io_context constructor. +#if !defined(ASIO_CONCURRENCY_HINT_DEFAULT) +# define ASIO_CONCURRENCY_HINT_DEFAULT -1 +#endif // !defined(ASIO_CONCURRENCY_HINT_DEFAULT) + +// This #define may be overridden at compile time to specify a program-wide +// concurrency hint, used by the one-argument io_context constructor when +// passed a value of 1. +#if !defined(ASIO_CONCURRENCY_HINT_1) +# define ASIO_CONCURRENCY_HINT_1 1 +#endif // !defined(ASIO_CONCURRENCY_HINT_DEFAULT) + +#endif // ASIO_DETAIL_CONCURRENCY_HINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_event.hpp new file mode 100644 index 00000000..7b9c924a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_event.hpp @@ -0,0 +1,112 @@ +// +// detail/conditionally_enabled_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CONDITIONALLY_ENABLED_EVENT_HPP +#define ASIO_DETAIL_CONDITIONALLY_ENABLED_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/conditionally_enabled_mutex.hpp" +#include "asio/detail/event.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/null_event.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Mutex adapter used to conditionally enable or disable locking. +class conditionally_enabled_event + : private noncopyable +{ +public: + // Constructor. + conditionally_enabled_event() + { + } + + // Destructor. + ~conditionally_enabled_event() + { + } + + // Signal the event. (Retained for backward compatibility.) + void signal(conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + event_.signal(lock); + } + + // Signal all waiters. + void signal_all(conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + event_.signal_all(lock); + } + + // Unlock the mutex and signal one waiter. + void unlock_and_signal_one( + conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + event_.unlock_and_signal_one(lock); + } + + // If there's a waiter, unlock the mutex and signal it. + bool maybe_unlock_and_signal_one( + conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + return event_.maybe_unlock_and_signal_one(lock); + else + return false; + } + + // Reset the event. + void clear(conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + event_.clear(lock); + } + + // Wait for the event to become signalled. + void wait(conditionally_enabled_mutex::scoped_lock& lock) + { + if (lock.mutex_.enabled_) + event_.wait(lock); + else + null_event().wait(lock); + } + + // Timed wait for the event to become signalled. + bool wait_for_usec( + conditionally_enabled_mutex::scoped_lock& lock, long usec) + { + if (lock.mutex_.enabled_) + return event_.wait_for_usec(lock, usec); + else + return null_event().wait_for_usec(lock, usec); + } + +private: + asio::detail::event event_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_CONDITIONALLY_ENABLED_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_mutex.hpp new file mode 100644 index 00000000..a3c3ee74 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/conditionally_enabled_mutex.hpp @@ -0,0 +1,149 @@ +// +// detail/conditionally_enabled_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP +#define ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Mutex adapter used to conditionally enable or disable locking. +class conditionally_enabled_mutex + : private noncopyable +{ +public: + // Helper class to lock and unlock a mutex automatically. + class scoped_lock + : private noncopyable + { + public: + // Tag type used to distinguish constructors. + enum adopt_lock_t { adopt_lock }; + + // Constructor adopts a lock that is already held. + scoped_lock(conditionally_enabled_mutex& m, adopt_lock_t) + : mutex_(m), + locked_(m.enabled_) + { + } + + // Constructor acquires the lock. + explicit scoped_lock(conditionally_enabled_mutex& m) + : mutex_(m) + { + if (m.enabled_) + { + mutex_.mutex_.lock(); + locked_ = true; + } + else + locked_ = false; + } + + // Destructor releases the lock. + ~scoped_lock() + { + if (locked_) + mutex_.mutex_.unlock(); + } + + // Explicitly acquire the lock. + void lock() + { + if (mutex_.enabled_ && !locked_) + { + mutex_.mutex_.lock(); + locked_ = true; + } + } + + // Explicitly release the lock. + void unlock() + { + if (locked_) + { + mutex_.unlock(); + locked_ = false; + } + } + + // Test whether the lock is held. + bool locked() const + { + return locked_; + } + + // Get the underlying mutex. + asio::detail::mutex& mutex() + { + return mutex_.mutex_; + } + + private: + friend class conditionally_enabled_event; + conditionally_enabled_mutex& mutex_; + bool locked_; + }; + + // Constructor. + explicit conditionally_enabled_mutex(bool enabled) + : enabled_(enabled) + { + } + + // Destructor. + ~conditionally_enabled_mutex() + { + } + + // Determine whether locking is enabled. + bool enabled() const + { + return enabled_; + } + + // Lock the mutex. + void lock() + { + if (enabled_) + mutex_.lock(); + } + + // Unlock the mutex. + void unlock() + { + if (enabled_) + mutex_.unlock(); + } + +private: + friend class scoped_lock; + friend class conditionally_enabled_event; + asio::detail::mutex mutex_; + const bool enabled_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_CONDITIONALLY_ENABLED_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/config.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/config.hpp new file mode 100644 index 00000000..530e7666 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/config.hpp @@ -0,0 +1,1495 @@ +// +// detail/config.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CONFIG_HPP +#define ASIO_DETAIL_CONFIG_HPP + +#if defined(ESP_PLATFORM) +# include "esp_asio_config.h" +#endif // defined(ESP_PLATFORM) + +// boostify: non-boost code starts here +#if !defined(ASIO_STANDALONE) +# if !defined(ASIO_ENABLE_BOOST) +# if (__cplusplus >= 201103) +# define ASIO_STANDALONE 1 +# elif defined(_MSC_VER) && defined(_MSVC_LANG) +# if (_MSC_VER >= 1900) && (_MSVC_LANG >= 201103) +# define ASIO_STANDALONE 1 +# endif // (_MSC_VER >= 1900) && (_MSVC_LANG >= 201103) +# endif // defined(_MSC_VER) && defined(_MSVC_LANG) +# endif // !defined(ASIO_ENABLE_BOOST) +#endif // !defined(ASIO_STANDALONE) + +// boostify: non-boost code ends here + +#if defined(ASIO_STANDALONE) +# define ASIO_DISABLE_BOOST_ARRAY 1 +# define ASIO_DISABLE_BOOST_ASSERT 1 +# define ASIO_DISABLE_BOOST_BIND 1 +# define ASIO_DISABLE_BOOST_CHRONO 1 +# define ASIO_DISABLE_BOOST_DATE_TIME 1 +# define ASIO_DISABLE_BOOST_LIMITS 1 +# define ASIO_DISABLE_BOOST_REGEX 1 +# define ASIO_DISABLE_BOOST_STATIC_CONSTANT 1 +# define ASIO_DISABLE_BOOST_THROW_EXCEPTION 1 +# define ASIO_DISABLE_BOOST_WORKAROUND 1 +#else // defined(ASIO_STANDALONE) +# include +# include +# define ASIO_HAS_BOOST_CONFIG 1 +#endif // defined(ASIO_STANDALONE) + +// Default to a header-only implementation. The user must specifically request +// separate compilation by defining either ASIO_SEPARATE_COMPILATION or +// ASIO_DYN_LINK (as a DLL/shared library implies separate compilation). +#if !defined(ASIO_HEADER_ONLY) +# if !defined(ASIO_SEPARATE_COMPILATION) +# if !defined(ASIO_DYN_LINK) +# define ASIO_HEADER_ONLY 1 +# endif // !defined(ASIO_DYN_LINK) +# endif // !defined(ASIO_SEPARATE_COMPILATION) +#endif // !defined(ASIO_HEADER_ONLY) + +#if defined(ASIO_HEADER_ONLY) +# define ASIO_DECL inline +#else // defined(ASIO_HEADER_ONLY) +# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CODEGEARC__) +// We need to import/export our code only if the user has specifically asked +// for it by defining ASIO_DYN_LINK. +# if defined(ASIO_DYN_LINK) +// Export if this is our own source, otherwise import. +# if defined(ASIO_SOURCE) +# define ASIO_DECL __declspec(dllexport) +# else // defined(ASIO_SOURCE) +# define ASIO_DECL __declspec(dllimport) +# endif // defined(ASIO_SOURCE) +# endif // defined(ASIO_DYN_LINK) +# endif // defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CODEGEARC__) +#endif // defined(ASIO_HEADER_ONLY) + +// If ASIO_DECL isn't defined yet define it now. +#if !defined(ASIO_DECL) +# define ASIO_DECL +#endif // !defined(ASIO_DECL) + +// Microsoft Visual C++ detection. +#if !defined(ASIO_MSVC) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_MSVC) +# define ASIO_MSVC BOOST_MSVC +# elif defined(_MSC_VER) && (defined(__INTELLISENSE__) \ + || (!defined(__MWERKS__) && !defined(__EDG_VERSION__))) +# define ASIO_MSVC _MSC_VER +# endif // defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_MSVC) +#endif // !defined(ASIO_MSVC) + +// Clang / libc++ detection. +#if defined(__clang__) +# if (__cplusplus >= 201103) +# if __has_include(<__config>) +# include <__config> +# if defined(_LIBCPP_VERSION) +# define ASIO_HAS_CLANG_LIBCXX 1 +# endif // defined(_LIBCPP_VERSION) +# endif // __has_include(<__config>) +# endif // (__cplusplus >= 201103) +#endif // defined(__clang__) + +// Android platform detection. +#if defined(__ANDROID__) +# include +#endif // defined(__ANDROID__) + +// Support move construction and assignment on compilers known to allow it. +#if !defined(ASIO_HAS_MOVE) +# if !defined(ASIO_DISABLE_MOVE) +# if defined(__clang__) +# if __has_feature(__cxx_rvalue_references__) +# define ASIO_HAS_MOVE 1 +# endif // __has_feature(__cxx_rvalue_references__) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_MOVE 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_MOVE 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# if defined(__INTEL_CXX11_MODE__) +# if defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1500) +# define BOOST_ASIO_HAS_MOVE 1 +# endif // defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1500) +# if defined(__ICL) && (__ICL >= 1500) +# define BOOST_ASIO_HAS_MOVE 1 +# endif // defined(__ICL) && (__ICL >= 1500) +# endif // defined(__INTEL_CXX11_MODE__) +# endif // !defined(ASIO_DISABLE_MOVE) +#endif // !defined(ASIO_HAS_MOVE) + +// If ASIO_MOVE_CAST isn't defined, and move support is available, define +// * ASIO_MOVE_ARG, +// * ASIO_NONDEDUCED_MOVE_ARG, and +// * ASIO_MOVE_CAST +// to take advantage of rvalue references and perfect forwarding. +#if defined(ASIO_HAS_MOVE) && !defined(ASIO_MOVE_CAST) +# define ASIO_MOVE_ARG(type) type&& +# define ASIO_MOVE_ARG2(type1, type2) type1, type2&& +# define ASIO_NONDEDUCED_MOVE_ARG(type) type& +# define ASIO_MOVE_CAST(type) static_cast +# define ASIO_MOVE_CAST2(type1, type2) static_cast +#endif // defined(ASIO_HAS_MOVE) && !defined(ASIO_MOVE_CAST) + +// If ASIO_MOVE_CAST still isn't defined, default to a C++03-compatible +// implementation. Note that older g++ and MSVC versions don't like it when you +// pass a non-member function through a const reference, so for most compilers +// we'll play it safe and stick with the old approach of passing the handler by +// value. +#if !defined(ASIO_MOVE_CAST) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ > 4) +# define ASIO_MOVE_ARG(type) const type& +# else // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ > 4) +# define ASIO_MOVE_ARG(type) type +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1)) || (__GNUC__ > 4) +# elif defined(ASIO_MSVC) +# if (_MSC_VER >= 1400) +# define ASIO_MOVE_ARG(type) const type& +# else // (_MSC_VER >= 1400) +# define ASIO_MOVE_ARG(type) type +# endif // (_MSC_VER >= 1400) +# else +# define ASIO_MOVE_ARG(type) type +# endif +# define ASIO_NONDEDUCED_MOVE_ARG(type) const type& +# define ASIO_MOVE_CAST(type) static_cast +# define ASIO_MOVE_CAST2(type1, type2) static_cast +#endif // !defined(ASIO_MOVE_CAST) + +// Support variadic templates on compilers known to allow it. +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) +# if !defined(ASIO_DISABLE_VARIADIC_TEMPLATES) +# if defined(__clang__) +# if __has_feature(__cxx_variadic_templates__) +# define ASIO_HAS_VARIADIC_TEMPLATES 1 +# endif // __has_feature(__cxx_variadic_templates__) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_VARIADIC_TEMPLATES 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_HAS_VARIADIC_TEMPLATES 1 +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_VARIADIC_TEMPLATES) +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +// Support deleted functions on compilers known to allow it. +#if !defined(ASIO_DELETED) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_DELETED = delete +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(__clang__) +# if __has_feature(__cxx_deleted_functions__) +# define ASIO_DELETED = delete +# endif // __has_feature(__cxx_deleted_functions__) +# endif // defined(__clang__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_DELETED = delete +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# if !defined(ASIO_DELETED) +# define ASIO_DELETED +# endif // !defined(ASIO_DELETED) +#endif // !defined(ASIO_DELETED) + +// Support constexpr on compilers known to allow it. +#if !defined(ASIO_HAS_CONSTEXPR) +# if !defined(ASIO_DISABLE_CONSTEXPR) +# if defined(__clang__) +# if __has_feature(__cxx_constexpr__) +# define ASIO_HAS_CONSTEXPR 1 +# endif // __has_feature(__cxx_constexr__) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_CONSTEXPR 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_HAS_CONSTEXPR 1 +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_CONSTEXPR) +#endif // !defined(ASIO_HAS_CONSTEXPR) +#if !defined(ASIO_CONSTEXPR) +# if defined(ASIO_HAS_CONSTEXPR) +# define ASIO_CONSTEXPR constexpr +# else // defined(ASIO_HAS_CONSTEXPR) +# define ASIO_CONSTEXPR +# endif // defined(ASIO_HAS_CONSTEXPR) +#endif // !defined(ASIO_CONSTEXPR) + +// Support noexcept on compilers known to allow it. +#if !defined(ASIO_NOEXCEPT) +# if !defined(ASIO_DISABLE_NOEXCEPT) +# if defined(ASIO_HAS_BOOST_CONFIG) && (BOOST_VERSION >= 105300) +# define ASIO_NOEXCEPT BOOST_NOEXCEPT +# define ASIO_NOEXCEPT_OR_NOTHROW BOOST_NOEXCEPT_OR_NOTHROW +# elif defined(__clang__) +# if __has_feature(__cxx_noexcept__) +# define ASIO_NOEXCEPT noexcept(true) +# define ASIO_NOEXCEPT_OR_NOTHROW noexcept(true) +# endif // __has_feature(__cxx_noexcept__) +# elif defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_NOEXCEPT noexcept(true) +# define ASIO_NOEXCEPT_OR_NOTHROW noexcept(true) +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# elif defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_NOEXCEPT noexcept(true) +# define ASIO_NOEXCEPT_OR_NOTHROW noexcept(true) +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_NOEXCEPT) +# if !defined(ASIO_NOEXCEPT) +# define ASIO_NOEXCEPT +# endif // !defined(ASIO_NOEXCEPT) +# if !defined(ASIO_NOEXCEPT_OR_NOTHROW) +# define ASIO_NOEXCEPT_OR_NOTHROW throw() +# endif // !defined(ASIO_NOEXCEPT_OR_NOTHROW) +#endif // !defined(ASIO_NOEXCEPT) + +// Support automatic type deduction on compilers known to support it. +#if !defined(ASIO_HAS_DECLTYPE) +# if !defined(ASIO_DISABLE_DECLTYPE) +# if defined(__clang__) +# if __has_feature(__cxx_decltype__) +# define ASIO_HAS_DECLTYPE 1 +# endif // __has_feature(__cxx_decltype__) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_DECLTYPE 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1800) +# define ASIO_HAS_DECLTYPE 1 +# endif // (_MSC_VER >= 1800) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_DECLTYPE) +#endif // !defined(ASIO_HAS_DECLTYPE) + +// Support alias templates on compilers known to allow it. +#if !defined(ASIO_HAS_ALIAS_TEMPLATES) +# if !defined(ASIO_DISABLE_ALIAS_TEMPLATES) +# if defined(__clang__) +# if __has_feature(__cxx_alias_templates__) +# define ASIO_HAS_ALIAS_TEMPLATES 1 +# endif // __has_feature(__cxx_alias_templates__) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_ALIAS_TEMPLATES 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_HAS_ALIAS_TEMPLATES 1 +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_ALIAS_TEMPLATES) +#endif // !defined(ASIO_HAS_ALIAS_TEMPLATES) + +// Support return type deduction on compilers known to allow it. +#if !defined(ASIO_HAS_RETURN_TYPE_DEDUCTION) +# if !defined(ASIO_DISABLE_RETURN_TYPE_DEDUCTION) +# if defined(__clang__) +# if __has_feature(__cxx_return_type_deduction__) +# define ASIO_HAS_RETURN_TYPE_DEDUCTION 1 +# endif // __has_feature(__cxx_alias_templates__) +# elif (__cplusplus >= 201402) +# define ASIO_HAS_RETURN_TYPE_DEDUCTION 1 +# endif // (__cplusplus >= 201402) +# endif // !defined(ASIO_DISABLE_RETURN_TYPE_DEDUCTION) +#endif // !defined(ASIO_HAS_RETURN_TYPE_DEDUCTION) + +// Support default function template arguments on compilers known to allow it. +#if !defined(ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) +# if !defined(ASIO_DISABLE_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) +# if (__cplusplus >= 201103) +# define ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS 1 +# endif // (__cplusplus >= 201103) +# endif // !defined(ASIO_DISABLE_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) +#endif // !defined(ASIO_HAS_DEFAULT_FUNCTION_TEMPLATE_ARGUMENTS) + +// Support concepts on compilers known to allow them. +#if !defined(ASIO_HAS_CONCEPTS) +# if !defined(ASIO_DISABLE_CONCEPTS) +# if __cpp_concepts +# define ASIO_HAS_CONCEPTS 1 +# define ASIO_CONCEPT concept bool +# endif // __cpp_concepts +# endif // !defined(ASIO_DISABLE_CONCEPTS) +#endif // !defined(ASIO_HAS_CONCEPTS) + +// Standard library support for system errors. +#if !defined(ASIO_HAS_STD_SYSTEM_ERROR) +# if !defined(ASIO_DISABLE_STD_SYSTEM_ERROR) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_SYSTEM_ERROR 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_SYSTEM_ERROR 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_SYSTEM_ERROR 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_SYSTEM_ERROR 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_SYSTEM_ERROR) +#endif // !defined(ASIO_HAS_STD_SYSTEM_ERROR) + +// Compliant C++11 compilers put noexcept specifiers on error_category members. +#if !defined(ASIO_ERROR_CATEGORY_NOEXCEPT) +# if defined(ASIO_HAS_BOOST_CONFIG) && (BOOST_VERSION >= 105300) +# define ASIO_ERROR_CATEGORY_NOEXCEPT BOOST_NOEXCEPT +# elif defined(__clang__) +# if __has_feature(__cxx_noexcept__) +# define ASIO_ERROR_CATEGORY_NOEXCEPT noexcept(true) +# endif // __has_feature(__cxx_noexcept__) +# elif defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_ERROR_CATEGORY_NOEXCEPT noexcept(true) +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# elif defined(ASIO_MSVC) +# if (_MSC_VER >= 1900) +# define ASIO_ERROR_CATEGORY_NOEXCEPT noexcept(true) +# endif // (_MSC_VER >= 1900) +# endif // defined(ASIO_MSVC) +# if !defined(ASIO_ERROR_CATEGORY_NOEXCEPT) +# define ASIO_ERROR_CATEGORY_NOEXCEPT +# endif // !defined(ASIO_ERROR_CATEGORY_NOEXCEPT) +#endif // !defined(ASIO_ERROR_CATEGORY_NOEXCEPT) + +// Standard library support for arrays. +#if !defined(ASIO_HAS_STD_ARRAY) +# if !defined(ASIO_DISABLE_STD_ARRAY) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_ARRAY 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_ARRAY 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_ARRAY 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1600) +# define ASIO_HAS_STD_ARRAY 1 +# endif // (_MSC_VER >= 1600) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_ARRAY) +#endif // !defined(ASIO_HAS_STD_ARRAY) + +// Standard library support for shared_ptr and weak_ptr. +#if !defined(ASIO_HAS_STD_SHARED_PTR) +# if !defined(ASIO_DISABLE_STD_SHARED_PTR) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_SHARED_PTR 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_STD_SHARED_PTR 1 +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_SHARED_PTR 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1600) +# define ASIO_HAS_STD_SHARED_PTR 1 +# endif // (_MSC_VER >= 1600) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_SHARED_PTR) +#endif // !defined(ASIO_HAS_STD_SHARED_PTR) + +// Standard library support for allocator_arg_t. +#if !defined(ASIO_HAS_STD_ALLOCATOR_ARG) +# if !defined(ASIO_DISABLE_STD_ALLOCATOR_ARG) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_ALLOCATOR_ARG 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_STD_ALLOCATOR_ARG 1 +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_ALLOCATOR_ARG 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1600) +# define ASIO_HAS_STD_ALLOCATOR_ARG 1 +# endif // (_MSC_VER >= 1600) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_ALLOCATOR_ARG) +#endif // !defined(ASIO_HAS_STD_ALLOCATOR_ARG) + +// Standard library support for atomic operations. +#if !defined(ASIO_HAS_STD_ATOMIC) +# if !defined(ASIO_DISABLE_STD_ATOMIC) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_ATOMIC 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_ATOMIC 1 +# endif // __has_include() +# elif defined(__apple_build_version__) && defined(_LIBCPP_VERSION) +# if (__clang_major__ >= 10) +# if __has_include() +# define ASIO_HAS_STD_ATOMIC 1 +# endif // __has_include() +# endif // (__clang_major__ >= 10) +# endif /// defined(__apple_build_version__) && defined(_LIBCPP_VERSION) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_ATOMIC 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_ATOMIC 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_ATOMIC) +#endif // !defined(ASIO_HAS_STD_ATOMIC) + +// Standard library support for chrono. Some standard libraries (such as the +// libstdc++ shipped with gcc 4.6) provide monotonic_clock as per early C++0x +// drafts, rather than the eventually standardised name of steady_clock. +#if !defined(ASIO_HAS_STD_CHRONO) +# if !defined(ASIO_DISABLE_STD_CHRONO) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_CHRONO 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_CHRONO 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_CHRONO 1 +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ == 6)) +# define ASIO_HAS_STD_CHRONO_MONOTONIC_CLOCK 1 +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ == 6)) +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_CHRONO 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_CHRONO) +#endif // !defined(ASIO_HAS_STD_CHRONO) + +// Boost support for chrono. +#if !defined(ASIO_HAS_BOOST_CHRONO) +# if !defined(ASIO_DISABLE_BOOST_CHRONO) +# if defined(ASIO_HAS_BOOST_CONFIG) && (BOOST_VERSION >= 104700) +# define ASIO_HAS_BOOST_CHRONO 1 +# endif // defined(ASIO_HAS_BOOST_CONFIG) && (BOOST_VERSION >= 104700) +# endif // !defined(ASIO_DISABLE_BOOST_CHRONO) +#endif // !defined(ASIO_HAS_BOOST_CHRONO) + +// Some form of chrono library is available. +#if !defined(ASIO_HAS_CHRONO) +# if defined(ASIO_HAS_STD_CHRONO) \ + || defined(ASIO_HAS_BOOST_CHRONO) +# define ASIO_HAS_CHRONO 1 +# endif // defined(ASIO_HAS_STD_CHRONO) + // || defined(ASIO_HAS_BOOST_CHRONO) +#endif // !defined(ASIO_HAS_CHRONO) + +// Boost support for the DateTime library. +#if !defined(ASIO_HAS_BOOST_DATE_TIME) +# if !defined(ASIO_DISABLE_BOOST_DATE_TIME) +# define ASIO_HAS_BOOST_DATE_TIME 1 +# endif // !defined(ASIO_DISABLE_BOOST_DATE_TIME) +#endif // !defined(ASIO_HAS_BOOST_DATE_TIME) + +// Standard library support for addressof. +#if !defined(ASIO_HAS_STD_ADDRESSOF) +# if !defined(ASIO_DISABLE_STD_ADDRESSOF) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_ADDRESSOF 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_STD_ADDRESSOF 1 +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_ADDRESSOF 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_ADDRESSOF 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_ADDRESSOF) +#endif // !defined(ASIO_HAS_STD_ADDRESSOF) + +// Standard library support for the function class. +#if !defined(ASIO_HAS_STD_FUNCTION) +# if !defined(ASIO_DISABLE_STD_FUNCTION) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_FUNCTION 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_STD_FUNCTION 1 +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_FUNCTION 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_FUNCTION 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_FUNCTION) +#endif // !defined(ASIO_HAS_STD_FUNCTION) + +// Standard library support for type traits. +#if !defined(ASIO_HAS_STD_TYPE_TRAITS) +# if !defined(ASIO_DISABLE_STD_TYPE_TRAITS) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_TYPE_TRAITS 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_TYPE_TRAITS 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_TYPE_TRAITS 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_TYPE_TRAITS 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_TYPE_TRAITS) +#endif // !defined(ASIO_HAS_STD_TYPE_TRAITS) + +// Standard library support for the nullptr_t type. +#if !defined(ASIO_HAS_NULLPTR) +# if !defined(ASIO_DISABLE_NULLPTR) +# if defined(__clang__) +# if __has_feature(__cxx_nullptr__) +# define ASIO_HAS_NULLPTR 1 +# endif // __has_feature(__cxx_rvalue_references__) +# elif defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_NULLPTR 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_NULLPTR 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_NULLPTR) +#endif // !defined(ASIO_HAS_NULLPTR) + +// Standard library support for the C++11 allocator additions. +#if !defined(ASIO_HAS_CXX11_ALLOCATORS) +# if !defined(ASIO_DISABLE_CXX11_ALLOCATORS) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_CXX11_ALLOCATORS 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_CXX11_ALLOCATORS 1 +# endif // (__cplusplus >= 201103) +# elif defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_CXX11_ALLOCATORS 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1800) +# define ASIO_HAS_CXX11_ALLOCATORS 1 +# endif // (_MSC_VER >= 1800) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_CXX11_ALLOCATORS) +#endif // !defined(ASIO_HAS_CXX11_ALLOCATORS) + +// Standard library support for the cstdint header. +#if !defined(ASIO_HAS_CSTDINT) +# if !defined(ASIO_DISABLE_CSTDINT) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_CSTDINT 1 +# elif (__cplusplus >= 201103) +# define ASIO_HAS_CSTDINT 1 +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_CSTDINT 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_CSTDINT 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_CSTDINT) +#endif // !defined(ASIO_HAS_CSTDINT) + +// Standard library support for the thread class. +#if !defined(ASIO_HAS_STD_THREAD) +# if !defined(ASIO_DISABLE_STD_THREAD) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_THREAD 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_THREAD 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_THREAD 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_THREAD 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_THREAD) +#endif // !defined(ASIO_HAS_STD_THREAD) + +// Standard library support for the mutex and condition variable classes. +#if !defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +# if !defined(ASIO_DISABLE_STD_MUTEX_AND_CONDVAR) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_MUTEX_AND_CONDVAR 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_MUTEX_AND_CONDVAR 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_MUTEX_AND_CONDVAR 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_MUTEX_AND_CONDVAR 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_MUTEX_AND_CONDVAR) +#endif // !defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +// Standard library support for the call_once function. +#if !defined(ASIO_HAS_STD_CALL_ONCE) +# if !defined(ASIO_DISABLE_STD_CALL_ONCE) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_CALL_ONCE 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_CALL_ONCE 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_CALL_ONCE 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_CALL_ONCE 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_CALL_ONCE) +#endif // !defined(ASIO_HAS_STD_CALL_ONCE) + +// Standard library support for futures. +#if !defined(ASIO_HAS_STD_FUTURE) +# if !defined(ASIO_DISABLE_STD_FUTURE) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_FUTURE 1 +# elif (__cplusplus >= 201103) +# if __has_include() +# define ASIO_HAS_STD_FUTURE 1 +# endif // __has_include() +# endif // (__cplusplus >= 201103) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_FUTURE 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_FUTURE 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_FUTURE) +#endif // !defined(ASIO_HAS_STD_FUTURE) + +// Standard library support for std::string_view. +#if !defined(ASIO_HAS_STD_STRING_VIEW) +# if !defined(ASIO_DISABLE_STD_STRING_VIEW) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# if (__cplusplus >= 201402) +# if __has_include() +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201402) +# else // defined(ASIO_HAS_CLANG_LIBCXX) +# if (__cplusplus >= 201703) +# if __has_include() +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201703) +# endif // defined(ASIO_HAS_CLANG_LIBCXX) +# elif defined(__GNUC__) +# if (__GNUC__ >= 7) +# if (__cplusplus >= 201703) +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // (__cplusplus >= 201703) +# endif // (__GNUC__ >= 7) +# elif defined(ASIO_MSVC) +# if (_MSC_VER >= 1910 && _MSVC_LANG >= 201703) +# define ASIO_HAS_STD_STRING_VIEW 1 +# endif // (_MSC_VER >= 1910 && _MSVC_LANG >= 201703) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_STRING_VIEW) +#endif // !defined(ASIO_HAS_STD_STRING_VIEW) + +// Standard library support for std::experimental::string_view. +#if !defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +# if !defined(ASIO_DISABLE_STD_EXPERIMENTAL_STRING_VIEW) +# if defined(__clang__) +# if defined(ASIO_HAS_CLANG_LIBCXX) +# if (_LIBCPP_VERSION < 7000) +# if (__cplusplus >= 201402) +# if __has_include() +# define ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201402) +# endif // (_LIBCPP_VERSION < 7000) +# else // defined(ASIO_HAS_CLANG_LIBCXX) +# if (__cplusplus >= 201402) +# if __has_include() +# define ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW 1 +# endif // __has_include() +# endif // (__cplusplus >= 201402) +# endif // // defined(ASIO_HAS_CLANG_LIBCXX) +# endif // defined(__clang__) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 9)) || (__GNUC__ > 4) +# if (__cplusplus >= 201402) +# define ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW 1 +# endif // (__cplusplus >= 201402) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 9)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# endif // !defined(ASIO_DISABLE_STD_EXPERIMENTAL_STRING_VIEW) +#endif // !defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) + +// Standard library has a string_view that we can use. +#if !defined(ASIO_HAS_STRING_VIEW) +# if !defined(ASIO_DISABLE_STRING_VIEW) +# if defined(ASIO_HAS_STD_STRING_VIEW) +# define ASIO_HAS_STRING_VIEW 1 +# elif defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +# define ASIO_HAS_STRING_VIEW 1 +# endif // defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +# endif // !defined(ASIO_DISABLE_STRING_VIEW) +#endif // !defined(ASIO_HAS_STRING_VIEW) + +// Standard library support for iostream move construction and assignment. +#if !defined(ASIO_HAS_STD_IOSTREAM_MOVE) +# if !defined(ASIO_DISABLE_STD_IOSTREAM_MOVE) +# if defined(__GNUC__) +# if (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_HAS_STD_IOSTREAM_MOVE 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_STD_IOSTREAM_MOVE 1 +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_IOSTREAM_MOVE) +#endif // !defined(ASIO_HAS_STD_IOSTREAM_MOVE) + +// Standard library has invoke_result (which supersedes result_of). +#if !defined(ASIO_HAS_STD_INVOKE_RESULT) +# if !defined(ASIO_DISABLE_STD_INVOKE_RESULT) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1911 && _MSVC_LANG >= 201703) +# define ASIO_HAS_STD_INVOKE_RESULT 1 +# endif // (_MSC_VER >= 1911 && _MSVC_LANG >= 201703) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_STD_INVOKE_RESULT) +#endif // !defined(ASIO_HAS_STD_INVOKE_RESULT) + +// Windows App target. Windows but with a limited API. +#if !defined(ASIO_WINDOWS_APP) +# if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0603) +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) \ + && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define ASIO_WINDOWS_APP 1 +# endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + // && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# endif // defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0603) +#endif // !defined(ASIO_WINDOWS_APP) + +// Legacy WinRT target. Windows App is preferred. +#if !defined(ASIO_WINDOWS_RUNTIME) +# if !defined(ASIO_WINDOWS_APP) +# if defined(__cplusplus_winrt) +# include +# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) \ + && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# define ASIO_WINDOWS_RUNTIME 1 +# endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) + // && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) +# endif // defined(__cplusplus_winrt) +# endif // !defined(ASIO_WINDOWS_APP) +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +// Windows target. Excludes WinRT but includes Windows App targets. +#if !defined(ASIO_WINDOWS) +# if !defined(ASIO_WINDOWS_RUNTIME) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_WINDOWS) +# define ASIO_WINDOWS 1 +# elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) +# define ASIO_WINDOWS 1 +# elif defined(ASIO_WINDOWS_APP) +# define ASIO_WINDOWS 1 +# endif // defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_WINDOWS) +# endif // !defined(ASIO_WINDOWS_RUNTIME) +#endif // !defined(ASIO_WINDOWS) + +// Windows: target OS version. +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if !defined(_WIN32_WINNT) && !defined(_WIN32_WINDOWS) +# if defined(_MSC_VER) || defined(__BORLANDC__) +# pragma message( \ + "Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. For example:\n"\ + "- add -D_WIN32_WINNT=0x0601 to the compiler command line; or\n"\ + "- add _WIN32_WINNT=0x0601 to your project's Preprocessor Definitions.\n"\ + "Assuming _WIN32_WINNT=0x0601 (i.e. Windows 7 target).") +# else // defined(_MSC_VER) || defined(__BORLANDC__) +# warning Please define _WIN32_WINNT or _WIN32_WINDOWS appropriately. +# warning For example, add -D_WIN32_WINNT=0x0601 to the compiler command line. +# warning Assuming _WIN32_WINNT=0x0601 (i.e. Windows 7 target). +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +# define _WIN32_WINNT 0x0601 +# endif // !defined(_WIN32_WINNT) && !defined(_WIN32_WINDOWS) +# if defined(_MSC_VER) +# if defined(_WIN32) && !defined(WIN32) +# if !defined(_WINSOCK2API_) +# define WIN32 // Needed for correct types in winsock2.h +# else // !defined(_WINSOCK2API_) +# error Please define the macro WIN32 in your compiler options +# endif // !defined(_WINSOCK2API_) +# endif // defined(_WIN32) && !defined(WIN32) +# endif // defined(_MSC_VER) +# if defined(__BORLANDC__) +# if defined(__WIN32__) && !defined(WIN32) +# if !defined(_WINSOCK2API_) +# define WIN32 // Needed for correct types in winsock2.h +# else // !defined(_WINSOCK2API_) +# error Please define the macro WIN32 in your compiler options +# endif // !defined(_WINSOCK2API_) +# endif // defined(__WIN32__) && !defined(WIN32) +# endif // defined(__BORLANDC__) +# if defined(__CYGWIN__) +# if !defined(__USE_W32_SOCKETS) +# error You must add -D__USE_W32_SOCKETS to your compiler options. +# endif // !defined(__USE_W32_SOCKETS) +# endif // defined(__CYGWIN__) +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +// Windows: minimise header inclusion. +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if !defined(ASIO_NO_WIN32_LEAN_AND_MEAN) +# if !defined(WIN32_LEAN_AND_MEAN) +# define WIN32_LEAN_AND_MEAN +# endif // !defined(WIN32_LEAN_AND_MEAN) +# endif // !defined(ASIO_NO_WIN32_LEAN_AND_MEAN) +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +// Windows: suppress definition of "min" and "max" macros. +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if !defined(ASIO_NO_NOMINMAX) +# if !defined(NOMINMAX) +# define NOMINMAX 1 +# endif // !defined(NOMINMAX) +# endif // !defined(ASIO_NO_NOMINMAX) +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +// Windows: IO Completion Ports. +#if !defined(ASIO_HAS_IOCP) +# if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0400) +# if !defined(UNDER_CE) && !defined(ASIO_WINDOWS_APP) +# if !defined(ASIO_DISABLE_IOCP) +# define ASIO_HAS_IOCP 1 +# endif // !defined(ASIO_DISABLE_IOCP) +# endif // !defined(UNDER_CE) && !defined(ASIO_WINDOWS_APP) +# endif // defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0400) +# endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) +#endif // !defined(ASIO_HAS_IOCP) + +// On POSIX (and POSIX-like) platforms we need to include unistd.h in order to +// get access to the various platform feature macros, e.g. to be able to test +// for threads support. +#if !defined(ASIO_HAS_UNISTD_H) +# if !defined(ASIO_HAS_BOOST_CONFIG) +# if defined(unix) \ + || defined(__unix) \ + || defined(_XOPEN_SOURCE) \ + || defined(_POSIX_SOURCE) \ + || (defined(__MACH__) && defined(__APPLE__)) \ + || defined(__FreeBSD__) \ + || defined(__NetBSD__) \ + || defined(__OpenBSD__) \ + || defined(__linux__) \ + || defined(__HAIKU__) +# define ASIO_HAS_UNISTD_H 1 +# endif +# endif // !defined(ASIO_HAS_BOOST_CONFIG) +#endif // !defined(ASIO_HAS_UNISTD_H) +#if defined(ASIO_HAS_UNISTD_H) +# include +#endif // defined(ASIO_HAS_UNISTD_H) + +// Linux: epoll, eventfd and timerfd. +#if defined(__linux__) +# include +# if !defined(ASIO_HAS_EPOLL) +# if !defined(ASIO_DISABLE_EPOLL) +# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,45) +# define ASIO_HAS_EPOLL 1 +# endif // LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,45) +# endif // !defined(ASIO_DISABLE_EPOLL) +# endif // !defined(ASIO_HAS_EPOLL) +# if !defined(ASIO_HAS_EVENTFD) +# if !defined(ASIO_DISABLE_EVENTFD) +# if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22) +# define ASIO_HAS_EVENTFD 1 +# endif // LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,22) +# endif // !defined(ASIO_DISABLE_EVENTFD) +# endif // !defined(ASIO_HAS_EVENTFD) +# if !defined(ASIO_HAS_TIMERFD) +# if defined(ASIO_HAS_EPOLL) +# if (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8) +# define ASIO_HAS_TIMERFD 1 +# endif // (__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8) +# endif // defined(ASIO_HAS_EPOLL) +# endif // !defined(ASIO_HAS_TIMERFD) +#endif // defined(__linux__) + +// Mac OS X, FreeBSD, NetBSD, OpenBSD: kqueue. +#if (defined(__MACH__) && defined(__APPLE__)) \ + || defined(__FreeBSD__) \ + || defined(__NetBSD__) \ + || defined(__OpenBSD__) +# if !defined(ASIO_HAS_KQUEUE) +# if !defined(ASIO_DISABLE_KQUEUE) +# define ASIO_HAS_KQUEUE 1 +# endif // !defined(ASIO_DISABLE_KQUEUE) +# endif // !defined(ASIO_HAS_KQUEUE) +#endif // (defined(__MACH__) && defined(__APPLE__)) + // || defined(__FreeBSD__) + // || defined(__NetBSD__) + // || defined(__OpenBSD__) + +// Solaris: /dev/poll. +#if defined(__sun) +# if !defined(ASIO_HAS_DEV_POLL) +# if !defined(ASIO_DISABLE_DEV_POLL) +# define ASIO_HAS_DEV_POLL 1 +# endif // !defined(ASIO_DISABLE_DEV_POLL) +# endif // !defined(ASIO_HAS_DEV_POLL) +#endif // defined(__sun) + +// Serial ports. +#if !defined(ASIO_HAS_SERIAL_PORT) +# if defined(ASIO_HAS_IOCP) \ + || !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) +# if !defined(__SYMBIAN32__) +# if !defined(ASIO_DISABLE_SERIAL_PORT) +# define ASIO_HAS_SERIAL_PORT 1 +# endif // !defined(ASIO_DISABLE_SERIAL_PORT) +# endif // !defined(__SYMBIAN32__) +# endif // defined(ASIO_HAS_IOCP) + // || !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) +#endif // !defined(ASIO_HAS_SERIAL_PORT) + +// Windows: stream handles. +#if !defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) +# if !defined(ASIO_DISABLE_WINDOWS_STREAM_HANDLE) +# if defined(ASIO_HAS_IOCP) +# define ASIO_HAS_WINDOWS_STREAM_HANDLE 1 +# endif // defined(ASIO_HAS_IOCP) +# endif // !defined(ASIO_DISABLE_WINDOWS_STREAM_HANDLE) +#endif // !defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + +// Windows: random access handles. +#if !defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) +# if !defined(ASIO_DISABLE_WINDOWS_RANDOM_ACCESS_HANDLE) +# if defined(ASIO_HAS_IOCP) +# define ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE 1 +# endif // defined(ASIO_HAS_IOCP) +# endif // !defined(ASIO_DISABLE_WINDOWS_RANDOM_ACCESS_HANDLE) +#endif // !defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + +// Windows: object handles. +#if !defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) +# if !defined(ASIO_DISABLE_WINDOWS_OBJECT_HANDLE) +# if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if !defined(UNDER_CE) && !defined(ASIO_WINDOWS_APP) +# define ASIO_HAS_WINDOWS_OBJECT_HANDLE 1 +# endif // !defined(UNDER_CE) && !defined(ASIO_WINDOWS_APP) +# endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# endif // !defined(ASIO_DISABLE_WINDOWS_OBJECT_HANDLE) +#endif // !defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + +// Windows: OVERLAPPED wrapper. +#if !defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) +# if !defined(ASIO_DISABLE_WINDOWS_OVERLAPPED_PTR) +# if defined(ASIO_HAS_IOCP) +# define ASIO_HAS_WINDOWS_OVERLAPPED_PTR 1 +# endif // defined(ASIO_HAS_IOCP) +# endif // !defined(ASIO_DISABLE_WINDOWS_OVERLAPPED_PTR) +#endif // !defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) + +// POSIX: stream-oriented file descriptors. +#if !defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) +# if !defined(ASIO_DISABLE_POSIX_STREAM_DESCRIPTOR) +# if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) +# define ASIO_HAS_POSIX_STREAM_DESCRIPTOR 1 +# endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) +# endif // !defined(ASIO_DISABLE_POSIX_STREAM_DESCRIPTOR) +#endif // !defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + +// UNIX domain sockets. +#if !defined(ASIO_HAS_LOCAL_SOCKETS) +# if !defined(ASIO_DISABLE_LOCAL_SOCKETS) +# if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) +# define ASIO_HAS_LOCAL_SOCKETS 1 +# endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) +# endif // !defined(ASIO_DISABLE_LOCAL_SOCKETS) +#endif // !defined(ASIO_HAS_LOCAL_SOCKETS) + +// Can use sigaction() instead of signal(). +#if !defined(ASIO_HAS_SIGACTION) +# if !defined(ASIO_DISABLE_SIGACTION) +# if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) +# define ASIO_HAS_SIGACTION 1 +# endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) +# endif // !defined(ASIO_DISABLE_SIGACTION) +#endif // !defined(ASIO_HAS_SIGACTION) + +// Can use signal(). +#if !defined(ASIO_HAS_SIGNAL) +# if !defined(ASIO_DISABLE_SIGNAL) +# if !defined(UNDER_CE) +# define ASIO_HAS_SIGNAL 1 +# endif // !defined(UNDER_CE) +# endif // !defined(ASIO_DISABLE_SIGNAL) +#endif // !defined(ASIO_HAS_SIGNAL) + +// Can use getaddrinfo() and getnameinfo(). +#if !defined(ASIO_HAS_GETADDRINFO) +# if !defined(ASIO_DISABLE_GETADDRINFO) +# if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if defined(_WIN32_WINNT) && (_WIN32_WINNT >= 0x0501) +# define ASIO_HAS_GETADDRINFO 1 +# elif defined(UNDER_CE) +# define ASIO_HAS_GETADDRINFO 1 +# endif // defined(UNDER_CE) +# elif defined(__MACH__) && defined(__APPLE__) +# if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +# if (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) +# define ASIO_HAS_GETADDRINFO 1 +# endif // (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1050) +# else // defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +# define ASIO_HAS_GETADDRINFO 1 +# endif // defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +# else // defined(__MACH__) && defined(__APPLE__) +# define ASIO_HAS_GETADDRINFO 1 +# endif // defined(__MACH__) && defined(__APPLE__) +# endif // !defined(ASIO_DISABLE_GETADDRINFO) +#endif // !defined(ASIO_HAS_GETADDRINFO) + +// Whether standard iostreams are disabled. +#if !defined(ASIO_NO_IOSTREAM) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_NO_IOSTREAM) +# define ASIO_NO_IOSTREAM 1 +# endif // !defined(BOOST_NO_IOSTREAM) +#endif // !defined(ASIO_NO_IOSTREAM) + +// Whether exception handling is disabled. +#if !defined(ASIO_NO_EXCEPTIONS) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_NO_EXCEPTIONS) +# define ASIO_NO_EXCEPTIONS 1 +# endif // !defined(BOOST_NO_EXCEPTIONS) +#endif // !defined(ASIO_NO_EXCEPTIONS) + +// Whether the typeid operator is supported. +#if !defined(ASIO_NO_TYPEID) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_NO_TYPEID) +# define ASIO_NO_TYPEID 1 +# endif // !defined(BOOST_NO_TYPEID) +#endif // !defined(ASIO_NO_TYPEID) + +// Threads. +#if !defined(ASIO_HAS_THREADS) +# if !defined(ASIO_DISABLE_THREADS) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_HAS_THREADS) +# define ASIO_HAS_THREADS 1 +# elif defined(__GNUC__) && !defined(__MINGW32__) \ + && !defined(linux) && !defined(__linux) && !defined(__linux__) +# define ASIO_HAS_THREADS 1 +# elif defined(_MT) || defined(__MT__) +# define ASIO_HAS_THREADS 1 +# elif defined(_REENTRANT) +# define ASIO_HAS_THREADS 1 +# elif defined(__APPLE__) +# define ASIO_HAS_THREADS 1 +# elif defined(__HAIKU__) +# define ASIO_HAS_THREADS 1 +# elif defined(_POSIX_THREADS) && (_POSIX_THREADS + 0 >= 0) +# define ASIO_HAS_THREADS 1 +# elif defined(_PTHREADS) +# define ASIO_HAS_THREADS 1 +# endif // defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_HAS_THREADS) +# endif // !defined(ASIO_DISABLE_THREADS) +#endif // !defined(ASIO_HAS_THREADS) + +// POSIX threads. +#if !defined(ASIO_HAS_PTHREADS) +# if defined(ASIO_HAS_THREADS) +# if defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_HAS_PTHREADS) +# define ASIO_HAS_PTHREADS 1 +# elif defined(_POSIX_THREADS) && (_POSIX_THREADS + 0 >= 0) +# define ASIO_HAS_PTHREADS 1 +# elif defined(__HAIKU__) +# define ASIO_HAS_PTHREADS 1 +# endif // defined(ASIO_HAS_BOOST_CONFIG) && defined(BOOST_HAS_PTHREADS) +# endif // defined(ASIO_HAS_THREADS) +#endif // !defined(ASIO_HAS_PTHREADS) + +// Helper to prevent macro expansion. +#define ASIO_PREVENT_MACRO_SUBSTITUTION + +// Helper to define in-class constants. +#if !defined(ASIO_STATIC_CONSTANT) +# if !defined(ASIO_DISABLE_BOOST_STATIC_CONSTANT) +# define ASIO_STATIC_CONSTANT(type, assignment) \ + BOOST_STATIC_CONSTANT(type, assignment) +# else // !defined(ASIO_DISABLE_BOOST_STATIC_CONSTANT) +# define ASIO_STATIC_CONSTANT(type, assignment) \ + static const type assignment +# endif // !defined(ASIO_DISABLE_BOOST_STATIC_CONSTANT) +#endif // !defined(ASIO_STATIC_CONSTANT) + +// Boost array library. +#if !defined(ASIO_HAS_BOOST_ARRAY) +# if !defined(ASIO_DISABLE_BOOST_ARRAY) +# define ASIO_HAS_BOOST_ARRAY 1 +# endif // !defined(ASIO_DISABLE_BOOST_ARRAY) +#endif // !defined(ASIO_HAS_BOOST_ARRAY) + +// Boost assert macro. +#if !defined(ASIO_HAS_BOOST_ASSERT) +# if !defined(ASIO_DISABLE_BOOST_ASSERT) +# define ASIO_HAS_BOOST_ASSERT 1 +# endif // !defined(ASIO_DISABLE_BOOST_ASSERT) +#endif // !defined(ASIO_HAS_BOOST_ASSERT) + +// Boost limits header. +#if !defined(ASIO_HAS_BOOST_LIMITS) +# if !defined(ASIO_DISABLE_BOOST_LIMITS) +# define ASIO_HAS_BOOST_LIMITS 1 +# endif // !defined(ASIO_DISABLE_BOOST_LIMITS) +#endif // !defined(ASIO_HAS_BOOST_LIMITS) + +// Boost throw_exception function. +#if !defined(ASIO_HAS_BOOST_THROW_EXCEPTION) +# if !defined(ASIO_DISABLE_BOOST_THROW_EXCEPTION) +# define ASIO_HAS_BOOST_THROW_EXCEPTION 1 +# endif // !defined(ASIO_DISABLE_BOOST_THROW_EXCEPTION) +#endif // !defined(ASIO_HAS_BOOST_THROW_EXCEPTION) + +// Boost regex library. +#if !defined(ASIO_HAS_BOOST_REGEX) +# if !defined(ASIO_DISABLE_BOOST_REGEX) +# define ASIO_HAS_BOOST_REGEX 1 +# endif // !defined(ASIO_DISABLE_BOOST_REGEX) +#endif // !defined(ASIO_HAS_BOOST_REGEX) + +// Boost bind function. +#if !defined(ASIO_HAS_BOOST_BIND) +# if !defined(ASIO_DISABLE_BOOST_BIND) +# define ASIO_HAS_BOOST_BIND 1 +# endif // !defined(ASIO_DISABLE_BOOST_BIND) +#endif // !defined(ASIO_HAS_BOOST_BIND) + +// Boost's BOOST_WORKAROUND macro. +#if !defined(ASIO_HAS_BOOST_WORKAROUND) +# if !defined(ASIO_DISABLE_BOOST_WORKAROUND) +# define ASIO_HAS_BOOST_WORKAROUND 1 +# endif // !defined(ASIO_DISABLE_BOOST_WORKAROUND) +#endif // !defined(ASIO_HAS_BOOST_WORKAROUND) + +// Microsoft Visual C++'s secure C runtime library. +#if !defined(ASIO_HAS_SECURE_RTL) +# if !defined(ASIO_DISABLE_SECURE_RTL) +# if defined(ASIO_MSVC) \ + && (ASIO_MSVC >= 1400) \ + && !defined(UNDER_CE) +# define ASIO_HAS_SECURE_RTL 1 +# endif // defined(ASIO_MSVC) + // && (ASIO_MSVC >= 1400) + // && !defined(UNDER_CE) +# endif // !defined(ASIO_DISABLE_SECURE_RTL) +#endif // !defined(ASIO_HAS_SECURE_RTL) + +// Handler hooking. Disabled for ancient Borland C++ and gcc compilers. +#if !defined(ASIO_HAS_HANDLER_HOOKS) +# if !defined(ASIO_DISABLE_HANDLER_HOOKS) +# if defined(__GNUC__) +# if (__GNUC__ >= 3) +# define ASIO_HAS_HANDLER_HOOKS 1 +# endif // (__GNUC__ >= 3) +# elif !defined(__BORLANDC__) +# define ASIO_HAS_HANDLER_HOOKS 1 +# endif // !defined(__BORLANDC__) +# endif // !defined(ASIO_DISABLE_HANDLER_HOOKS) +#endif // !defined(ASIO_HAS_HANDLER_HOOKS) + +// Support for the __thread keyword extension. +#if !defined(ASIO_DISABLE_THREAD_KEYWORD_EXTENSION) +# if defined(__linux__) +# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# if ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3) +# if !defined(__INTEL_COMPILER) && !defined(__ICL) \ + && !(defined(__clang__) && defined(__ANDROID__)) +# define ASIO_HAS_THREAD_KEYWORD_EXTENSION 1 +# define ASIO_THREAD_KEYWORD __thread +# elif defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1100) +# define ASIO_HAS_THREAD_KEYWORD_EXTENSION 1 +# endif // defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 1100) + // && !(defined(__clang__) && defined(__ANDROID__)) +# endif // ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3) +# endif // defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# endif // defined(__linux__) +# if defined(ASIO_MSVC) && defined(ASIO_WINDOWS_RUNTIME) +# if (_MSC_VER >= 1700) +# define ASIO_HAS_THREAD_KEYWORD_EXTENSION 1 +# define ASIO_THREAD_KEYWORD __declspec(thread) +# endif // (_MSC_VER >= 1700) +# endif // defined(ASIO_MSVC) && defined(ASIO_WINDOWS_RUNTIME) +#endif // !defined(ASIO_DISABLE_THREAD_KEYWORD_EXTENSION) +#if !defined(ASIO_THREAD_KEYWORD) +# define ASIO_THREAD_KEYWORD __thread +#endif // !defined(ASIO_THREAD_KEYWORD) + +// Support for POSIX ssize_t typedef. +#if !defined(ASIO_DISABLE_SSIZE_T) +# if defined(__linux__) \ + || (defined(__MACH__) && defined(__APPLE__)) +# define ASIO_HAS_SSIZE_T 1 +# endif // defined(__linux__) + // || (defined(__MACH__) && defined(__APPLE__)) +#endif // !defined(ASIO_DISABLE_SSIZE_T) + +// Helper macros to manage transition away from error_code return values. +#if defined(ASIO_NO_DEPRECATED) +# define ASIO_SYNC_OP_VOID void +# define ASIO_SYNC_OP_VOID_RETURN(e) return +#else // defined(ASIO_NO_DEPRECATED) +# define ASIO_SYNC_OP_VOID asio::error_code +# define ASIO_SYNC_OP_VOID_RETURN(e) return e +#endif // defined(ASIO_NO_DEPRECATED) + +// Newer gcc, clang need special treatment to suppress unused typedef warnings. +#if defined(__clang__) +# if defined(__apple_build_version__) +# if (__clang_major__ >= 7) +# define ASIO_UNUSED_TYPEDEF __attribute__((__unused__)) +# endif // (__clang_major__ >= 7) +# elif ((__clang_major__ == 3) && (__clang_minor__ >= 6)) \ + || (__clang_major__ > 3) +# define ASIO_UNUSED_TYPEDEF __attribute__((__unused__)) +# endif // ((__clang_major__ == 3) && (__clang_minor__ >= 6)) + // || (__clang_major__ > 3) +#elif defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4) +# define ASIO_UNUSED_TYPEDEF __attribute__((__unused__)) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4) +#endif // defined(__GNUC__) +#if !defined(ASIO_UNUSED_TYPEDEF) +# define ASIO_UNUSED_TYPEDEF +#endif // !defined(ASIO_UNUSED_TYPEDEF) + +// Some versions of gcc generate spurious warnings about unused variables. +#if defined(__GNUC__) +# if (__GNUC__ >= 4) +# define ASIO_UNUSED_VARIABLE __attribute__((__unused__)) +# endif // (__GNUC__ >= 4) +#endif // defined(__GNUC__) +#if !defined(ASIO_UNUSED_VARIABLE) +# define ASIO_UNUSED_VARIABLE +#endif // !defined(ASIO_UNUSED_VARIABLE) + +// Support co_await on compilers known to allow it. +#if !defined(ASIO_HAS_CO_AWAIT) +# if !defined(ASIO_DISABLE_CO_AWAIT) +# if defined(ASIO_MSVC) +# if (_MSC_FULL_VER >= 190023506) +# if defined(_RESUMABLE_FUNCTIONS_SUPPORTED) +# define ASIO_HAS_CO_AWAIT 1 +# endif // defined(_RESUMABLE_FUNCTIONS_SUPPORTED) +# endif // (_MSC_FULL_VER >= 190023506) +# endif // defined(ASIO_MSVC) +# endif // !defined(ASIO_DISABLE_CO_AWAIT) +# if defined(__clang__) +# if (__cplusplus >= 201703) && (__cpp_coroutines >= 201703) +# if __has_include() +# define ASIO_HAS_CO_AWAIT 1 +# endif // __has_include() +# endif // (__cplusplus >= 201703) && (__cpp_coroutines >= 201703) +# endif // defined(__clang__) +#endif // !defined(ASIO_HAS_CO_AWAIT) + +#endif // ASIO_DETAIL_CONFIG_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/consuming_buffers.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/consuming_buffers.hpp new file mode 100644 index 00000000..1f604019 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/consuming_buffers.hpp @@ -0,0 +1,414 @@ +// +// detail/consuming_buffers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CONSUMING_BUFFERS_HPP +#define ASIO_DETAIL_CONSUMING_BUFFERS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/buffer.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/limits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper template to determine the maximum number of prepared buffers. +template +struct prepared_buffers_max +{ + enum { value = buffer_sequence_adapter_base::max_buffers }; +}; + +template +struct prepared_buffers_max > +{ + enum { value = N }; +}; + +#if defined(ASIO_HAS_STD_ARRAY) + +template +struct prepared_buffers_max > +{ + enum { value = N }; +}; + +#endif // defined(ASIO_HAS_STD_ARRAY) + +// A buffer sequence used to represent a subsequence of the buffers. +template +struct prepared_buffers +{ + typedef Buffer value_type; + typedef const Buffer* const_iterator; + + enum { max_buffers = MaxBuffers < 16 ? MaxBuffers : 16 }; + + prepared_buffers() : count(0) {} + const_iterator begin() const { return elems; } + const_iterator end() const { return elems + count; } + + Buffer elems[max_buffers]; + std::size_t count; +}; + +// A proxy for a sub-range in a list of buffers. +template +class consuming_buffers +{ +public: + typedef prepared_buffers::value> + prepared_buffers_type; + + // Construct to represent the entire list of buffers. + explicit consuming_buffers(const Buffers& buffers) + : buffers_(buffers), + total_consumed_(0), + next_elem_(0), + next_elem_offset_(0) + { + using asio::buffer_size; + total_size_ = buffer_size(buffers); + } + + // Determine if we are at the end of the buffers. + bool empty() const + { + return total_consumed_ >= total_size_; + } + + // Get the buffer for a single transfer, with a size. + prepared_buffers_type prepare(std::size_t max_size) + { + prepared_buffers_type result; + + Buffer_Iterator next = asio::buffer_sequence_begin(buffers_); + Buffer_Iterator end = asio::buffer_sequence_end(buffers_); + + std::advance(next, next_elem_); + std::size_t elem_offset = next_elem_offset_; + while (next != end && max_size > 0 && (result.count) < result.max_buffers) + { + Buffer next_buf = Buffer(*next) + elem_offset; + result.elems[result.count] = asio::buffer(next_buf, max_size); + max_size -= result.elems[result.count].size(); + elem_offset = 0; + if (result.elems[result.count].size() > 0) + ++result.count; + ++next; + } + + return result; + } + + // Consume the specified number of bytes from the buffers. + void consume(std::size_t size) + { + total_consumed_ += size; + + Buffer_Iterator next = asio::buffer_sequence_begin(buffers_); + Buffer_Iterator end = asio::buffer_sequence_end(buffers_); + + std::advance(next, next_elem_); + while (next != end && size > 0) + { + Buffer next_buf = Buffer(*next) + next_elem_offset_; + if (size < next_buf.size()) + { + next_elem_offset_ += size; + size = 0; + } + else + { + size -= next_buf.size(); + next_elem_offset_ = 0; + ++next_elem_; + ++next; + } + } + } + + // Get the total number of bytes consumed from the buffers. + std::size_t total_consumed() const + { + return total_consumed_; + } + +private: + Buffers buffers_; + std::size_t total_size_; + std::size_t total_consumed_; + std::size_t next_elem_; + std::size_t next_elem_offset_; +}; + +// Base class of all consuming_buffers specialisations for single buffers. +template +class consuming_single_buffer +{ +public: + // Construct to represent the entire list of buffers. + template + explicit consuming_single_buffer(const Buffer1& buffer) + : buffer_(buffer), + total_consumed_(0) + { + } + + // Determine if we are at the end of the buffers. + bool empty() const + { + return total_consumed_ >= buffer_.size(); + } + + // Get the buffer for a single transfer, with a size. + Buffer prepare(std::size_t max_size) + { + return asio::buffer(buffer_ + total_consumed_, max_size); + } + + // Consume the specified number of bytes from the buffers. + void consume(std::size_t size) + { + total_consumed_ += size; + } + + // Get the total number of bytes consumed from the buffers. + std::size_t total_consumed() const + { + return total_consumed_; + } + +private: + Buffer buffer_; + std::size_t total_consumed_; +}; + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const mutable_buffer& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const mutable_buffer& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const const_buffer& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +#if !defined(ASIO_NO_DEPRECATED) + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const mutable_buffers_1& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const mutable_buffers_1& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +template <> +class consuming_buffers + : public consuming_single_buffer +{ +public: + explicit consuming_buffers(const const_buffers_1& buffer) + : consuming_single_buffer(buffer) + { + } +}; + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +class consuming_buffers, + typename boost::array::const_iterator> +{ +public: + // Construct to represent the entire list of buffers. + explicit consuming_buffers(const boost::array& buffers) + : buffers_(buffers), + total_consumed_(0) + { + } + + // Determine if we are at the end of the buffers. + bool empty() const + { + return total_consumed_ >= + Buffer(buffers_[0]).size() + Buffer(buffers_[1]).size(); + } + + // Get the buffer for a single transfer, with a size. + boost::array prepare(std::size_t max_size) + { + boost::array result = {{ + Buffer(buffers_[0]), Buffer(buffers_[1]) }}; + std::size_t buffer0_size = result[0].size(); + result[0] = asio::buffer(result[0] + total_consumed_, max_size); + result[1] = asio::buffer( + result[1] + (total_consumed_ < buffer0_size + ? 0 : total_consumed_ - buffer0_size), + max_size - result[0].size()); + return result; + } + + // Consume the specified number of bytes from the buffers. + void consume(std::size_t size) + { + total_consumed_ += size; + } + + // Get the total number of bytes consumed from the buffers. + std::size_t total_consumed() const + { + return total_consumed_; + } + +private: + boost::array buffers_; + std::size_t total_consumed_; +}; + +#if defined(ASIO_HAS_STD_ARRAY) + +template +class consuming_buffers, + typename std::array::const_iterator> +{ +public: + // Construct to represent the entire list of buffers. + explicit consuming_buffers(const std::array& buffers) + : buffers_(buffers), + total_consumed_(0) + { + } + + // Determine if we are at the end of the buffers. + bool empty() const + { + return total_consumed_ >= + Buffer(buffers_[0]).size() + Buffer(buffers_[1]).size(); + } + + // Get the buffer for a single transfer, with a size. + std::array prepare(std::size_t max_size) + { + std::array result = {{ + Buffer(buffers_[0]), Buffer(buffers_[1]) }}; + std::size_t buffer0_size = result[0].size(); + result[0] = asio::buffer(result[0] + total_consumed_, max_size); + result[1] = asio::buffer( + result[1] + (total_consumed_ < buffer0_size + ? 0 : total_consumed_ - buffer0_size), + max_size - result[0].size()); + return result; + } + + // Consume the specified number of bytes from the buffers. + void consume(std::size_t size) + { + total_consumed_ += size; + } + + // Get the total number of bytes consumed from the buffers. + std::size_t total_consumed() const + { + return total_consumed_; + } + +private: + std::array buffers_; + std::size_t total_consumed_; +}; + +#endif // defined(ASIO_HAS_STD_ARRAY) + +// Specialisation for null_buffers to ensure that the null_buffers type is +// always passed through to the underlying read or write operation. +template +class consuming_buffers + : public asio::null_buffers +{ +public: + consuming_buffers(const null_buffers&) + { + // No-op. + } + + bool empty() + { + return false; + } + + null_buffers prepare(std::size_t) + { + return null_buffers(); + } + + void consume(std::size_t) + { + // No-op. + } + + std::size_t total_consumed() const + { + return 0; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_CONSUMING_BUFFERS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstddef.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstddef.hpp new file mode 100644 index 00000000..b34dae50 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstddef.hpp @@ -0,0 +1,31 @@ +// +// detail/cstddef.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CSTDDEF_HPP +#define ASIO_DETAIL_CSTDDEF_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +namespace asio { + +#if defined(ASIO_HAS_NULLPTR) +using std::nullptr_t; +#else // defined(ASIO_HAS_NULLPTR) +struct nullptr_t {}; +#endif // defined(ASIO_HAS_NULLPTR) + +} // namespace asio + +#endif // ASIO_DETAIL_CSTDDEF_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstdint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstdint.hpp new file mode 100644 index 00000000..1f6ac447 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/cstdint.hpp @@ -0,0 +1,60 @@ +// +// detail/cstdint.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_CSTDINT_HPP +#define ASIO_DETAIL_CSTDINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CSTDINT) +# include +#else // defined(ASIO_HAS_CSTDINT) +# include +#endif // defined(ASIO_HAS_CSTDINT) + +namespace asio { + +#if defined(ASIO_HAS_CSTDINT) +using std::int16_t; +using std::int_least16_t; +using std::uint16_t; +using std::uint_least16_t; +using std::int32_t; +using std::int_least32_t; +using std::uint32_t; +using std::uint_least32_t; +using std::int64_t; +using std::int_least64_t; +using std::uint64_t; +using std::uint_least64_t; +using std::uintmax_t; +#else // defined(ASIO_HAS_CSTDINT) +using boost::int16_t; +using boost::int_least16_t; +using boost::uint16_t; +using boost::uint_least16_t; +using boost::int32_t; +using boost::int_least32_t; +using boost::uint32_t; +using boost::uint_least32_t; +using boost::int64_t; +using boost::int_least64_t; +using boost::uint64_t; +using boost::uint_least64_t; +using boost::uintmax_t; +#endif // defined(ASIO_HAS_CSTDINT) + +} // namespace asio + +#endif // ASIO_DETAIL_CSTDINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/date_time_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/date_time_fwd.hpp new file mode 100644 index 00000000..3a2af4d8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/date_time_fwd.hpp @@ -0,0 +1,34 @@ +// +// detail/date_time_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DATE_TIME_FWD_HPP +#define ASIO_DETAIL_DATE_TIME_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +namespace boost { +namespace date_time { + +template +class base_time; + +} // namespace date_time +namespace posix_time { + +class ptime; + +} // namespace posix_time +} // namespace boost + +#endif // ASIO_DETAIL_DATE_TIME_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/deadline_timer_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/deadline_timer_service.hpp new file mode 100644 index 00000000..28ee3e49 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/deadline_timer_service.hpp @@ -0,0 +1,280 @@ +// +// detail/deadline_timer_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DEADLINE_TIMER_SERVICE_HPP +#define ASIO_DETAIL_DEADLINE_TIMER_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/timer_queue.hpp" +#include "asio/detail/timer_queue_ptime.hpp" +#include "asio/detail/timer_scheduler.hpp" +#include "asio/detail/wait_handler.hpp" +#include "asio/detail/wait_op.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include +# include +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class deadline_timer_service + : public execution_context_service_base > +{ +public: + // The time type. + typedef typename Time_Traits::time_type time_type; + + // The duration type. + typedef typename Time_Traits::duration_type duration_type; + + // The implementation type of the timer. This type is dependent on the + // underlying implementation of the timer service. + struct implementation_type + : private asio::detail::noncopyable + { + time_type expiry; + bool might_have_pending_waits; + typename timer_queue::per_timer_data timer_data; + }; + + // Constructor. + deadline_timer_service(execution_context& context) + : execution_context_service_base< + deadline_timer_service >(context), + scheduler_(asio::use_service(context)) + { + scheduler_.init_task(); + scheduler_.add_timer_queue(timer_queue_); + } + + // Destructor. + ~deadline_timer_service() + { + scheduler_.remove_timer_queue(timer_queue_); + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + } + + // Construct a new timer implementation. + void construct(implementation_type& impl) + { + impl.expiry = time_type(); + impl.might_have_pending_waits = false; + } + + // Destroy a timer implementation. + void destroy(implementation_type& impl) + { + asio::error_code ec; + cancel(impl, ec); + } + + // Move-construct a new serial port implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + scheduler_.move_timer(timer_queue_, impl.timer_data, other_impl.timer_data); + + impl.expiry = other_impl.expiry; + other_impl.expiry = time_type(); + + impl.might_have_pending_waits = other_impl.might_have_pending_waits; + other_impl.might_have_pending_waits = false; + } + + // Move-assign from another serial port implementation. + void move_assign(implementation_type& impl, + deadline_timer_service& other_service, + implementation_type& other_impl) + { + if (this != &other_service) + if (impl.might_have_pending_waits) + scheduler_.cancel_timer(timer_queue_, impl.timer_data); + + other_service.scheduler_.move_timer(other_service.timer_queue_, + impl.timer_data, other_impl.timer_data); + + impl.expiry = other_impl.expiry; + other_impl.expiry = time_type(); + + impl.might_have_pending_waits = other_impl.might_have_pending_waits; + other_impl.might_have_pending_waits = false; + } + + // Cancel any asynchronous wait operations associated with the timer. + std::size_t cancel(implementation_type& impl, asio::error_code& ec) + { + if (!impl.might_have_pending_waits) + { + ec = asio::error_code(); + return 0; + } + + ASIO_HANDLER_OPERATION((scheduler_.context(), + "deadline_timer", &impl, 0, "cancel")); + + std::size_t count = scheduler_.cancel_timer(timer_queue_, impl.timer_data); + impl.might_have_pending_waits = false; + ec = asio::error_code(); + return count; + } + + // Cancels one asynchronous wait operation associated with the timer. + std::size_t cancel_one(implementation_type& impl, + asio::error_code& ec) + { + if (!impl.might_have_pending_waits) + { + ec = asio::error_code(); + return 0; + } + + ASIO_HANDLER_OPERATION((scheduler_.context(), + "deadline_timer", &impl, 0, "cancel_one")); + + std::size_t count = scheduler_.cancel_timer( + timer_queue_, impl.timer_data, 1); + if (count == 0) + impl.might_have_pending_waits = false; + ec = asio::error_code(); + return count; + } + + // Get the expiry time for the timer as an absolute time. + time_type expiry(const implementation_type& impl) const + { + return impl.expiry; + } + + // Get the expiry time for the timer as an absolute time. + time_type expires_at(const implementation_type& impl) const + { + return impl.expiry; + } + + // Get the expiry time for the timer relative to now. + duration_type expires_from_now(const implementation_type& impl) const + { + return Time_Traits::subtract(this->expiry(impl), Time_Traits::now()); + } + + // Set the expiry time for the timer as an absolute time. + std::size_t expires_at(implementation_type& impl, + const time_type& expiry_time, asio::error_code& ec) + { + std::size_t count = cancel(impl, ec); + impl.expiry = expiry_time; + ec = asio::error_code(); + return count; + } + + // Set the expiry time for the timer relative to now. + std::size_t expires_after(implementation_type& impl, + const duration_type& expiry_time, asio::error_code& ec) + { + return expires_at(impl, + Time_Traits::add(Time_Traits::now(), expiry_time), ec); + } + + // Set the expiry time for the timer relative to now. + std::size_t expires_from_now(implementation_type& impl, + const duration_type& expiry_time, asio::error_code& ec) + { + return expires_at(impl, + Time_Traits::add(Time_Traits::now(), expiry_time), ec); + } + + // Perform a blocking wait on the timer. + void wait(implementation_type& impl, asio::error_code& ec) + { + time_type now = Time_Traits::now(); + ec = asio::error_code(); + while (Time_Traits::less_than(now, impl.expiry) && !ec) + { + this->do_wait(Time_Traits::to_posix_duration( + Time_Traits::subtract(impl.expiry, now)), ec); + now = Time_Traits::now(); + } + } + + // Start an asynchronous wait on the timer. + template + void async_wait(implementation_type& impl, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef wait_handler op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + impl.might_have_pending_waits = true; + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "deadline_timer", &impl, 0, "async_wait")); + + scheduler_.schedule_timer(timer_queue_, impl.expiry, impl.timer_data, p.p); + p.v = p.p = 0; + } + +private: + // Helper function to wait given a duration type. The duration type should + // either be of type boost::posix_time::time_duration, or implement the + // required subset of its interface. + template + void do_wait(const Duration& timeout, asio::error_code& ec) + { +#if defined(ASIO_WINDOWS_RUNTIME) + std::this_thread::sleep_for( + std::chrono::seconds(timeout.total_seconds()) + + std::chrono::microseconds(timeout.total_microseconds())); + ec = asio::error_code(); +#else // defined(ASIO_WINDOWS_RUNTIME) + ::timeval tv; + tv.tv_sec = timeout.total_seconds(); + tv.tv_usec = timeout.total_microseconds() % 1000000; + socket_ops::select(0, 0, 0, 0, &tv, ec); +#endif // defined(ASIO_WINDOWS_RUNTIME) + } + + // The queue of timers. + timer_queue timer_queue_; + + // The object that schedules and executes timers. Usually a reactor. + timer_scheduler& scheduler_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_DEADLINE_TIMER_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dependent_type.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dependent_type.hpp new file mode 100644 index 00000000..c7b4866f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dependent_type.hpp @@ -0,0 +1,36 @@ +// +// detail/dependent_type.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DEPENDENT_TYPE_HPP +#define ASIO_DETAIL_DEPENDENT_TYPE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct dependent_type +{ + typedef T type; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_DEPENDENT_TYPE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_ops.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_ops.hpp new file mode 100644 index 00000000..3a142882 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_ops.hpp @@ -0,0 +1,121 @@ +// +// detail/descriptor_ops.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DESCRIPTOR_OPS_HPP +#define ASIO_DETAIL_DESCRIPTOR_OPS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) + +#include +#include "asio/error.hpp" +#include "asio/error_code.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { +namespace descriptor_ops { + +// Descriptor state bits. +enum +{ + // The user wants a non-blocking descriptor. + user_set_non_blocking = 1, + + // The descriptor has been set non-blocking. + internal_non_blocking = 2, + + // Helper "state" used to determine whether the descriptor is non-blocking. + non_blocking = user_set_non_blocking | internal_non_blocking, + + // The descriptor may have been dup()-ed. + possible_dup = 4 +}; + +typedef unsigned char state_type; + +template +inline ReturnType error_wrapper(ReturnType return_value, + asio::error_code& ec) +{ + ec = asio::error_code(errno, + asio::error::get_system_category()); + return return_value; +} + +ASIO_DECL int open(const char* path, int flags, + asio::error_code& ec); + +ASIO_DECL int close(int d, state_type& state, + asio::error_code& ec); + +ASIO_DECL bool set_user_non_blocking(int d, + state_type& state, bool value, asio::error_code& ec); + +ASIO_DECL bool set_internal_non_blocking(int d, + state_type& state, bool value, asio::error_code& ec); + +typedef iovec buf; + +ASIO_DECL std::size_t sync_read(int d, state_type state, buf* bufs, + std::size_t count, bool all_empty, asio::error_code& ec); + +ASIO_DECL bool non_blocking_read(int d, buf* bufs, std::size_t count, + asio::error_code& ec, std::size_t& bytes_transferred); + +ASIO_DECL std::size_t sync_write(int d, state_type state, + const buf* bufs, std::size_t count, bool all_empty, + asio::error_code& ec); + +ASIO_DECL bool non_blocking_write(int d, + const buf* bufs, std::size_t count, + asio::error_code& ec, std::size_t& bytes_transferred); + +ASIO_DECL int ioctl(int d, state_type& state, long cmd, + ioctl_arg_type* arg, asio::error_code& ec); + +ASIO_DECL int fcntl(int d, int cmd, asio::error_code& ec); + +ASIO_DECL int fcntl(int d, int cmd, + long arg, asio::error_code& ec); + +ASIO_DECL int poll_read(int d, + state_type state, asio::error_code& ec); + +ASIO_DECL int poll_write(int d, + state_type state, asio::error_code& ec); + +ASIO_DECL int poll_error(int d, + state_type state, asio::error_code& ec); + +} // namespace descriptor_ops +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/descriptor_ops.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) + +#endif // ASIO_DETAIL_DESCRIPTOR_OPS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_read_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_read_op.hpp new file mode 100644 index 00000000..c14362e5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_read_op.hpp @@ -0,0 +1,130 @@ +// +// detail/descriptor_read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DESCRIPTOR_READ_OP_HPP +#define ASIO_DETAIL_DESCRIPTOR_READ_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/descriptor_ops.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_work.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class descriptor_read_op_base : public reactor_op +{ +public: + descriptor_read_op_base(int descriptor, + const MutableBufferSequence& buffers, func_type complete_func) + : reactor_op(&descriptor_read_op_base::do_perform, complete_func), + descriptor_(descriptor), + buffers_(buffers) + { + } + + static status do_perform(reactor_op* base) + { + descriptor_read_op_base* o(static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = descriptor_ops::non_blocking_read(o->descriptor_, + bufs.buffers(), bufs.count(), o->ec_, o->bytes_transferred_) + ? done : not_done; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_read", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + int descriptor_; + MutableBufferSequence buffers_; +}; + +template +class descriptor_read_op + : public descriptor_read_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(descriptor_read_op); + + descriptor_read_op(int descriptor, const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : descriptor_read_op_base( + descriptor, buffers, &descriptor_read_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + descriptor_read_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#endif // ASIO_DETAIL_DESCRIPTOR_READ_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_write_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_write_op.hpp new file mode 100644 index 00000000..0ba32822 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/descriptor_write_op.hpp @@ -0,0 +1,130 @@ +// +// detail/descriptor_write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DESCRIPTOR_WRITE_OP_HPP +#define ASIO_DETAIL_DESCRIPTOR_WRITE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/descriptor_ops.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_work.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class descriptor_write_op_base : public reactor_op +{ +public: + descriptor_write_op_base(int descriptor, + const ConstBufferSequence& buffers, func_type complete_func) + : reactor_op(&descriptor_write_op_base::do_perform, complete_func), + descriptor_(descriptor), + buffers_(buffers) + { + } + + static status do_perform(reactor_op* base) + { + descriptor_write_op_base* o(static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = descriptor_ops::non_blocking_write(o->descriptor_, + bufs.buffers(), bufs.count(), o->ec_, o->bytes_transferred_) + ? done : not_done; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_write", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + int descriptor_; + ConstBufferSequence buffers_; +}; + +template +class descriptor_write_op + : public descriptor_write_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(descriptor_write_op); + + descriptor_write_op(int descriptor, const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : descriptor_write_op_base( + descriptor, buffers, &descriptor_write_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + descriptor_write_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#endif // ASIO_DETAIL_DESCRIPTOR_WRITE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dev_poll_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dev_poll_reactor.hpp new file mode 100644 index 00000000..41c2330b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/dev_poll_reactor.hpp @@ -0,0 +1,218 @@ +// +// detail/dev_poll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_DEV_POLL_REACTOR_HPP +#define ASIO_DETAIL_DEV_POLL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_DEV_POLL) + +#include +#include +#include +#include "asio/detail/hash_map.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/reactor_op_queue.hpp" +#include "asio/detail/select_interrupter.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class dev_poll_reactor + : public execution_context_service_base +{ +public: + enum op_types { read_op = 0, write_op = 1, + connect_op = 1, except_op = 2, max_ops = 3 }; + + // Per-descriptor data. + struct per_descriptor_data + { + }; + + // Constructor. + ASIO_DECL dev_poll_reactor(asio::execution_context& ctx); + + // Destructor. + ASIO_DECL ~dev_poll_reactor(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Recreate internal descriptors following a fork. + ASIO_DECL void notify_fork( + asio::execution_context::fork_event fork_ev); + + // Initialise the task. + ASIO_DECL void init_task(); + + // Register a socket with the reactor. Returns 0 on success, system error + // code on failure. + ASIO_DECL int register_descriptor(socket_type, per_descriptor_data&); + + // Register a descriptor with an associated single operation. Returns 0 on + // success, system error code on failure. + ASIO_DECL int register_internal_descriptor( + int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op); + + // Move descriptor registration from one descriptor_data object to another. + ASIO_DECL void move_descriptor(socket_type descriptor, + per_descriptor_data& target_descriptor_data, + per_descriptor_data& source_descriptor_data); + + // Post a reactor operation for immediate completion. + void post_immediate_completion(reactor_op* op, bool is_continuation) + { + scheduler_.post_immediate_completion(op, is_continuation); + } + + // Start a new operation. The reactor operation will be performed when the + // given descriptor is flagged as ready, or an error has occurred. + ASIO_DECL void start_op(int op_type, socket_type descriptor, + per_descriptor_data&, reactor_op* op, + bool is_continuation, bool allow_speculative); + + // Cancel all operations associated with the given descriptor. The + // handlers associated with the descriptor will be invoked with the + // operation_aborted error. + ASIO_DECL void cancel_ops(socket_type descriptor, per_descriptor_data&); + + // Cancel any operations that are running against the descriptor and remove + // its registration from the reactor. The reactor resources associated with + // the descriptor must be released by calling cleanup_descriptor_data. + ASIO_DECL void deregister_descriptor(socket_type descriptor, + per_descriptor_data&, bool closing); + + // Remove the descriptor's registration from the reactor. The reactor + // resources associated with the descriptor must be released by calling + // cleanup_descriptor_data. + ASIO_DECL void deregister_internal_descriptor( + socket_type descriptor, per_descriptor_data&); + + // Perform any post-deregistration cleanup tasks associated with the + // descriptor data. + ASIO_DECL void cleanup_descriptor_data(per_descriptor_data&); + + // Add a new timer queue to the reactor. + template + void add_timer_queue(timer_queue& queue); + + // Remove a timer queue from the reactor. + template + void remove_timer_queue(timer_queue& queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer operations associated with the given token. Returns the + // number of operations that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source); + + // Run /dev/poll once until interrupted or events are ready to be dispatched. + ASIO_DECL void run(long usec, op_queue& ops); + + // Interrupt the select loop. + ASIO_DECL void interrupt(); + +private: + // Create the /dev/poll file descriptor. Throws an exception if the descriptor + // cannot be created. + ASIO_DECL static int do_dev_poll_create(); + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // Get the timeout value for the /dev/poll DP_POLL operation. The timeout + // value is returned as a number of milliseconds. A return value of -1 + // indicates that the poll should block indefinitely. + ASIO_DECL int get_timeout(int msec); + + // Cancel all operations associated with the given descriptor. The do_cancel + // function of the handler objects will be invoked. This function does not + // acquire the dev_poll_reactor's mutex. + ASIO_DECL void cancel_ops_unlocked(socket_type descriptor, + const asio::error_code& ec); + + // Add a pending event entry for the given descriptor. + ASIO_DECL ::pollfd& add_pending_event_change(int descriptor); + + // The scheduler implementation used to post completions. + scheduler& scheduler_; + + // Mutex to protect access to internal data. + asio::detail::mutex mutex_; + + // The /dev/poll file descriptor. + int dev_poll_fd_; + + // Vector of /dev/poll events waiting to be written to the descriptor. + std::vector< ::pollfd> pending_event_changes_; + + // Hash map to associate a descriptor with a pending event change index. + hash_map pending_event_change_index_; + + // The interrupter is used to break a blocking DP_POLL operation. + select_interrupter interrupter_; + + // The queues of read, write and except operations. + reactor_op_queue op_queue_[max_ops]; + + // The timer queues. + timer_queue_set timer_queues_; + + // Whether the service has been shut down. + bool shutdown_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/dev_poll_reactor.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/dev_poll_reactor.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_DEV_POLL) + +#endif // ASIO_DETAIL_DEV_POLL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/epoll_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/epoll_reactor.hpp new file mode 100644 index 00000000..248eb8a3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/epoll_reactor.hpp @@ -0,0 +1,266 @@ +// +// detail/epoll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_EPOLL_REACTOR_HPP +#define ASIO_DETAIL_EPOLL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_EPOLL) + +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/conditionally_enabled_mutex.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/object_pool.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/select_interrupter.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_TIMERFD) +# include +#endif // defined(ASIO_HAS_TIMERFD) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class epoll_reactor + : public execution_context_service_base +{ +private: + // The mutex type used by this reactor. + typedef conditionally_enabled_mutex mutex; + +public: + enum op_types { read_op = 0, write_op = 1, + connect_op = 1, except_op = 2, max_ops = 3 }; + + // Per-descriptor queues. + class descriptor_state : operation + { + friend class epoll_reactor; + friend class object_pool_access; + + descriptor_state* next_; + descriptor_state* prev_; + + mutex mutex_; + epoll_reactor* reactor_; + int descriptor_; + uint32_t registered_events_; + op_queue op_queue_[max_ops]; + bool try_speculative_[max_ops]; + bool shutdown_; + + ASIO_DECL descriptor_state(bool locking); + void set_ready_events(uint32_t events) { task_result_ = events; } + void add_ready_events(uint32_t events) { task_result_ |= events; } + ASIO_DECL operation* perform_io(uint32_t events); + ASIO_DECL static void do_complete( + void* owner, operation* base, + const asio::error_code& ec, std::size_t bytes_transferred); + }; + + // Per-descriptor data. + typedef descriptor_state* per_descriptor_data; + + // Constructor. + ASIO_DECL epoll_reactor(asio::execution_context& ctx); + + // Destructor. + ASIO_DECL ~epoll_reactor(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Recreate internal descriptors following a fork. + ASIO_DECL void notify_fork( + asio::execution_context::fork_event fork_ev); + + // Initialise the task. + ASIO_DECL void init_task(); + + // Register a socket with the reactor. Returns 0 on success, system error + // code on failure. + ASIO_DECL int register_descriptor(socket_type descriptor, + per_descriptor_data& descriptor_data); + + // Register a descriptor with an associated single operation. Returns 0 on + // success, system error code on failure. + ASIO_DECL int register_internal_descriptor( + int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op); + + // Move descriptor registration from one descriptor_data object to another. + ASIO_DECL void move_descriptor(socket_type descriptor, + per_descriptor_data& target_descriptor_data, + per_descriptor_data& source_descriptor_data); + + // Post a reactor operation for immediate completion. + void post_immediate_completion(reactor_op* op, bool is_continuation) + { + scheduler_.post_immediate_completion(op, is_continuation); + } + + // Start a new operation. The reactor operation will be performed when the + // given descriptor is flagged as ready, or an error has occurred. + ASIO_DECL void start_op(int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op, + bool is_continuation, bool allow_speculative); + + // Cancel all operations associated with the given descriptor. The + // handlers associated with the descriptor will be invoked with the + // operation_aborted error. + ASIO_DECL void cancel_ops(socket_type descriptor, + per_descriptor_data& descriptor_data); + + // Cancel any operations that are running against the descriptor and remove + // its registration from the reactor. The reactor resources associated with + // the descriptor must be released by calling cleanup_descriptor_data. + ASIO_DECL void deregister_descriptor(socket_type descriptor, + per_descriptor_data& descriptor_data, bool closing); + + // Remove the descriptor's registration from the reactor. The reactor + // resources associated with the descriptor must be released by calling + // cleanup_descriptor_data. + ASIO_DECL void deregister_internal_descriptor( + socket_type descriptor, per_descriptor_data& descriptor_data); + + // Perform any post-deregistration cleanup tasks associated with the + // descriptor data. + ASIO_DECL void cleanup_descriptor_data( + per_descriptor_data& descriptor_data); + + // Add a new timer queue to the reactor. + template + void add_timer_queue(timer_queue& timer_queue); + + // Remove a timer queue from the reactor. + template + void remove_timer_queue(timer_queue& timer_queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer operations associated with the given token. Returns the + // number of operations that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source); + + // Run epoll once until interrupted or events are ready to be dispatched. + ASIO_DECL void run(long usec, op_queue& ops); + + // Interrupt the select loop. + ASIO_DECL void interrupt(); + +private: + // The hint to pass to epoll_create to size its data structures. + enum { epoll_size = 20000 }; + + // Create the epoll file descriptor. Throws an exception if the descriptor + // cannot be created. + ASIO_DECL static int do_epoll_create(); + + // Create the timerfd file descriptor. Does not throw. + ASIO_DECL static int do_timerfd_create(); + + // Allocate a new descriptor state object. + ASIO_DECL descriptor_state* allocate_descriptor_state(); + + // Free an existing descriptor state object. + ASIO_DECL void free_descriptor_state(descriptor_state* s); + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // Called to recalculate and update the timeout. + ASIO_DECL void update_timeout(); + + // Get the timeout value for the epoll_wait call. The timeout value is + // returned as a number of milliseconds. A return value of -1 indicates + // that epoll_wait should block indefinitely. + ASIO_DECL int get_timeout(int msec); + +#if defined(ASIO_HAS_TIMERFD) + // Get the timeout value for the timer descriptor. The return value is the + // flag argument to be used when calling timerfd_settime. + ASIO_DECL int get_timeout(itimerspec& ts); +#endif // defined(ASIO_HAS_TIMERFD) + + // The scheduler implementation used to post completions. + scheduler& scheduler_; + + // Mutex to protect access to internal data. + mutex mutex_; + + // The interrupter is used to break a blocking epoll_wait call. + select_interrupter interrupter_; + + // The epoll file descriptor. + int epoll_fd_; + + // The timer file descriptor. + int timer_fd_; + + // The timer queues. + timer_queue_set timer_queues_; + + // Whether the service has been shut down. + bool shutdown_; + + // Mutex to protect access to the registered descriptors. + mutex registered_descriptors_mutex_; + + // Keep track of all registered descriptors. + object_pool registered_descriptors_; + + // Helper class to do post-perform_io cleanup. + struct perform_io_cleanup_on_block_exit; + friend struct perform_io_cleanup_on_block_exit; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/epoll_reactor.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/epoll_reactor.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_EPOLL) + +#endif // ASIO_DETAIL_EPOLL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/event.hpp new file mode 100644 index 00000000..d1c7a575 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/event.hpp @@ -0,0 +1,48 @@ +// +// detail/event.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_EVENT_HPP +#define ASIO_DETAIL_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_event.hpp" +#elif defined(ASIO_WINDOWS) +# include "asio/detail/win_event.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_event.hpp" +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +# include "asio/detail/std_event.hpp" +#else +# error Only Windows, POSIX and std::condition_variable are supported! +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) +typedef null_event event; +#elif defined(ASIO_WINDOWS) +typedef win_event event; +#elif defined(ASIO_HAS_PTHREADS) +typedef posix_event event; +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +typedef std_event event; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/eventfd_select_interrupter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/eventfd_select_interrupter.hpp new file mode 100644 index 00000000..4dcf6981 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/eventfd_select_interrupter.hpp @@ -0,0 +1,83 @@ +// +// detail/eventfd_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Roelof Naude (roelof.naude at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_EVENTFD_SELECT_INTERRUPTER_HPP +#define ASIO_DETAIL_EVENTFD_SELECT_INTERRUPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_EVENTFD) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class eventfd_select_interrupter +{ +public: + // Constructor. + ASIO_DECL eventfd_select_interrupter(); + + // Destructor. + ASIO_DECL ~eventfd_select_interrupter(); + + // Recreate the interrupter's descriptors. Used after a fork. + ASIO_DECL void recreate(); + + // Interrupt the select call. + ASIO_DECL void interrupt(); + + // Reset the select interrupt. Returns true if the call was interrupted. + ASIO_DECL bool reset(); + + // Get the read descriptor to be passed to select. + int read_descriptor() const + { + return read_descriptor_; + } + +private: + // Open the descriptors. Throws on error. + ASIO_DECL void open_descriptors(); + + // Close the descriptors. + ASIO_DECL void close_descriptors(); + + // The read end of a connection used to interrupt the select call. This file + // descriptor is passed to select such that when it is time to stop, a single + // 64bit value will be written on the other end of the connection and this + // descriptor will become readable. + int read_descriptor_; + + // The write end of a connection used to interrupt the select call. A single + // 64bit non-zero value may be written to this to wake up the select which is + // waiting for the other end to become readable. This descriptor will only + // differ from the read descriptor when a pipe is used. + int write_descriptor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/eventfd_select_interrupter.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_EVENTFD) + +#endif // ASIO_DETAIL_EVENTFD_SELECT_INTERRUPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_function.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_function.hpp new file mode 100644 index 00000000..9b3f581d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_function.hpp @@ -0,0 +1,104 @@ +// +// detail/executor_function.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_EXECUTOR_FUNCTION_HPP +#define ASIO_DETAIL_EXECUTOR_FUNCTION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class executor_function_base +{ +public: + void complete() + { + func_(this, true); + } + + void destroy() + { + func_(this, false); + } + +protected: + typedef void (*func_type)(executor_function_base*, bool); + + executor_function_base(func_type func) + : func_(func) + { + } + + // Prevents deletion through this type. + ~executor_function_base() + { + } + +private: + func_type func_; +}; + +template +class executor_function : public executor_function_base +{ +public: + ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR( + thread_info_base::executor_function_tag, executor_function); + + template + executor_function(ASIO_MOVE_ARG(F) f, const Alloc& allocator) + : executor_function_base(&executor_function::do_complete), + function_(ASIO_MOVE_CAST(F)(f)), + allocator_(allocator) + { + } + + static void do_complete(executor_function_base* base, bool call) + { + // Take ownership of the function object. + executor_function* o(static_cast(base)); + Alloc allocator(o->allocator_); + ptr p = { detail::addressof(allocator), o, o }; + + // Make a copy of the function so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the function may be the true owner of the memory + // associated with the function. Consequently, a local copy of the function + // is required to ensure that any owning sub-object remains valid until + // after we have deallocated the memory here. + Function function(ASIO_MOVE_CAST(Function)(o->function_)); + p.reset(); + + // Make the upcall if required. + if (call) + { + function(); + } + } + +private: + Function function_; + Alloc allocator_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_EXECUTOR_FUNCTION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_op.hpp new file mode 100644 index 00000000..7c7b253f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/executor_op.hpp @@ -0,0 +1,84 @@ +// +// detail/executor_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_EXECUTOR_OP_HPP +#define ASIO_DETAIL_EXECUTOR_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/scheduler_operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class executor_op : public Operation +{ +public: + ASIO_DEFINE_HANDLER_ALLOCATOR_PTR(executor_op); + + template + executor_op(ASIO_MOVE_ARG(H) h, const Alloc& allocator) + : Operation(&executor_op::do_complete), + handler_(ASIO_MOVE_CAST(H)(h)), + allocator_(allocator) + { + } + + static void do_complete(void* owner, Operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + executor_op* o(static_cast(base)); + Alloc allocator(o->allocator_); + ptr p = { detail::addressof(allocator), o, o }; + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + Handler handler(ASIO_MOVE_CAST(Handler)(o->handler_)); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN(()); + asio_handler_invoke_helpers::invoke(handler, handler); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + Alloc allocator_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_EXECUTOR_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fd_set_adapter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fd_set_adapter.hpp new file mode 100644 index 00000000..a239ec70 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fd_set_adapter.hpp @@ -0,0 +1,39 @@ +// +// detail/fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_FD_SET_ADAPTER_HPP +#define ASIO_DETAIL_FD_SET_ADAPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/posix_fd_set_adapter.hpp" +#include "asio/detail/win_fd_set_adapter.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +typedef win_fd_set_adapter fd_set_adapter; +#else +typedef posix_fd_set_adapter fd_set_adapter; +#endif + +} // namespace detail +} // namespace asio + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_FD_SET_ADAPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fenced_block.hpp new file mode 100644 index 00000000..1404837f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/fenced_block.hpp @@ -0,0 +1,80 @@ +// +// detail/fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_FENCED_BLOCK_HPP +#define ASIO_DETAIL_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) \ + || defined(ASIO_DISABLE_FENCED_BLOCK) +# include "asio/detail/null_fenced_block.hpp" +#elif defined(ASIO_HAS_STD_ATOMIC) +# include "asio/detail/std_fenced_block.hpp" +#elif defined(__MACH__) && defined(__APPLE__) +# include "asio/detail/macos_fenced_block.hpp" +#elif defined(__sun) +# include "asio/detail/solaris_fenced_block.hpp" +#elif defined(__GNUC__) && defined(__arm__) \ + && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) +# include "asio/detail/gcc_arm_fenced_block.hpp" +#elif defined(__GNUC__) && (defined(__hppa) || defined(__hppa__)) +# include "asio/detail/gcc_hppa_fenced_block.hpp" +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +# include "asio/detail/gcc_x86_fenced_block.hpp" +#elif defined(__GNUC__) \ + && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)) \ + && !defined(__INTEL_COMPILER) && !defined(__ICL) \ + && !defined(__ICC) && !defined(__ECC) && !defined(__PATHSCALE__) +# include "asio/detail/gcc_sync_fenced_block.hpp" +#elif defined(ASIO_WINDOWS) && !defined(UNDER_CE) +# include "asio/detail/win_fenced_block.hpp" +#else +# include "asio/detail/null_fenced_block.hpp" +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) \ + || defined(ASIO_DISABLE_FENCED_BLOCK) +typedef null_fenced_block fenced_block; +#elif defined(ASIO_HAS_STD_ATOMIC) +typedef std_fenced_block fenced_block; +#elif defined(__MACH__) && defined(__APPLE__) +typedef macos_fenced_block fenced_block; +#elif defined(__sun) +typedef solaris_fenced_block fenced_block; +#elif defined(__GNUC__) && defined(__arm__) \ + && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) +typedef gcc_arm_fenced_block fenced_block; +#elif defined(__GNUC__) && (defined(__hppa) || defined(__hppa__)) +typedef gcc_hppa_fenced_block fenced_block; +#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +typedef gcc_x86_fenced_block fenced_block; +#elif defined(__GNUC__) \ + && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)) \ + && !defined(__INTEL_COMPILER) && !defined(__ICL) \ + && !defined(__ICC) && !defined(__ECC) && !defined(__PATHSCALE__) +typedef gcc_sync_fenced_block fenced_block; +#elif defined(ASIO_WINDOWS) && !defined(UNDER_CE) +typedef win_fenced_block fenced_block; +#else +typedef null_fenced_block fenced_block; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/functional.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/functional.hpp new file mode 100644 index 00000000..ef2e4e43 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/functional.hpp @@ -0,0 +1,38 @@ +// +// detail/functional.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_FUNCTIONAL_HPP +#define ASIO_DETAIL_FUNCTIONAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include + +#if !defined(ASIO_HAS_STD_FUNCTION) +# include +#endif // !defined(ASIO_HAS_STD_FUNCTION) + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_STD_FUNCTION) +using std::function; +#else // defined(ASIO_HAS_STD_FUNCTION) +using boost::function; +#endif // defined(ASIO_HAS_STD_FUNCTION) + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_FUNCTIONAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/future.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/future.hpp new file mode 100644 index 00000000..00c22d1f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/future.hpp @@ -0,0 +1,33 @@ +// +// detail/future.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_FUTURE_HPP +#define ASIO_DETAIL_FUTURE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#if defined(ASIO_HAS_STD_FUTURE) +# include +// Even though the future header is available, libstdc++ may not implement the +// std::future class itself. However, we need to have already included the +// future header to reliably test for _GLIBCXX_HAS_GTHREADS. +# if defined(__GNUC__) && !defined(ASIO_HAS_CLANG_LIBCXX) +# if defined(_GLIBCXX_HAS_GTHREADS) +# define ASIO_HAS_STD_FUTURE_CLASS 1 +# endif // defined(_GLIBCXX_HAS_GTHREADS) +# else // defined(__GNUC__) && !defined(ASIO_HAS_CLANG_LIBCXX) +# define ASIO_HAS_STD_FUTURE_CLASS 1 +# endif // defined(__GNUC__) && !defined(ASIO_HAS_CLANG_LIBCXX) +#endif // defined(ASIO_HAS_STD_FUTURE) + +#endif // ASIO_DETAIL_FUTURE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_arm_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_arm_fenced_block.hpp new file mode 100644 index 00000000..a8911315 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_arm_fenced_block.hpp @@ -0,0 +1,91 @@ +// +// detail/gcc_arm_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP +#define ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__GNUC__) && defined(__arm__) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class gcc_arm_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit gcc_arm_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit gcc_arm_fenced_block(full_t) + { + barrier(); + } + + // Destructor. + ~gcc_arm_fenced_block() + { + barrier(); + } + +private: + static void barrier() + { +#if defined(__ARM_ARCH_4__) \ + || defined(__ARM_ARCH_4T__) \ + || defined(__ARM_ARCH_5__) \ + || defined(__ARM_ARCH_5E__) \ + || defined(__ARM_ARCH_5T__) \ + || defined(__ARM_ARCH_5TE__) \ + || defined(__ARM_ARCH_5TEJ__) \ + || defined(__ARM_ARCH_6__) \ + || defined(__ARM_ARCH_6J__) \ + || defined(__ARM_ARCH_6K__) \ + || defined(__ARM_ARCH_6Z__) \ + || defined(__ARM_ARCH_6ZK__) \ + || defined(__ARM_ARCH_6T2__) +# if defined(__thumb__) + // This is just a placeholder and almost certainly not sufficient. + __asm__ __volatile__ ("" : : : "memory"); +# else // defined(__thumb__) + int a = 0, b = 0; + __asm__ __volatile__ ("swp %0, %1, [%2]" + : "=&r"(a) : "r"(1), "r"(&b) : "memory", "cc"); +# endif // defined(__thumb__) +#else + // ARMv7 and later. + __asm__ __volatile__ ("dmb" : : : "memory"); +#endif + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__GNUC__) && defined(__arm__) + +#endif // ASIO_DETAIL_GCC_ARM_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_hppa_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_hppa_fenced_block.hpp new file mode 100644 index 00000000..30376712 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_hppa_fenced_block.hpp @@ -0,0 +1,68 @@ +// +// detail/gcc_hppa_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_GCC_HPPA_FENCED_BLOCK_HPP +#define ASIO_DETAIL_GCC_HPPA_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__GNUC__) && (defined(__hppa) || defined(__hppa__)) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class gcc_hppa_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit gcc_hppa_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit gcc_hppa_fenced_block(full_t) + { + barrier(); + } + + // Destructor. + ~gcc_hppa_fenced_block() + { + barrier(); + } + +private: + static void barrier() + { + // This is just a placeholder and almost certainly not sufficient. + __asm__ __volatile__ ("" : : : "memory"); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__GNUC__) && (defined(__hppa) || defined(__hppa__)) + +#endif // ASIO_DETAIL_GCC_HPPA_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_sync_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_sync_fenced_block.hpp new file mode 100644 index 00000000..340db21d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_sync_fenced_block.hpp @@ -0,0 +1,65 @@ +// +// detail/gcc_sync_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_GCC_SYNC_FENCED_BLOCK_HPP +#define ASIO_DETAIL_GCC_SYNC_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__GNUC__) \ + && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)) \ + && !defined(__INTEL_COMPILER) && !defined(__ICL) \ + && !defined(__ICC) && !defined(__ECC) && !defined(__PATHSCALE__) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class gcc_sync_fenced_block + : private noncopyable +{ +public: + enum half_or_full_t { half, full }; + + // Constructor. + explicit gcc_sync_fenced_block(half_or_full_t) + : value_(0) + { + __sync_lock_test_and_set(&value_, 1); + } + + // Destructor. + ~gcc_sync_fenced_block() + { + __sync_lock_release(&value_); + } + +private: + int value_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__GNUC__) + // && ((__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4)) + // && !defined(__INTEL_COMPILER) && !defined(__ICL) + // && !defined(__ICC) && !defined(__ECC) && !defined(__PATHSCALE__) + +#endif // ASIO_DETAIL_GCC_SYNC_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_x86_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_x86_fenced_block.hpp new file mode 100644 index 00000000..1398b2a0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/gcc_x86_fenced_block.hpp @@ -0,0 +1,99 @@ +// +// detail/gcc_x86_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_GCC_X86_FENCED_BLOCK_HPP +#define ASIO_DETAIL_GCC_X86_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class gcc_x86_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit gcc_x86_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit gcc_x86_fenced_block(full_t) + { + lbarrier(); + } + + // Destructor. + ~gcc_x86_fenced_block() + { + sbarrier(); + } + +private: + static int barrier() + { + int r = 0, m = 1; + __asm__ __volatile__ ( + "xchgl %0, %1" : + "=r"(r), "=m"(m) : + "0"(1), "m"(m) : + "memory", "cc"); + return r; + } + + static void lbarrier() + { +#if defined(__SSE2__) +# if (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) + __builtin_ia32_lfence(); +# else // (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) + __asm__ __volatile__ ("lfence" ::: "memory"); +# endif // (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) +#else // defined(__SSE2__) + barrier(); +#endif // defined(__SSE2__) + } + + static void sbarrier() + { +#if defined(__SSE2__) +# if (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) + __builtin_ia32_sfence(); +# else // (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) + __asm__ __volatile__ ("sfence" ::: "memory"); +# endif // (__GNUC__ >= 4) && !defined(__INTEL_COMPILER) && !defined(__ICL) +#else // defined(__SSE2__) + barrier(); +#endif // defined(__SSE2__) + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) + +#endif // ASIO_DETAIL_GCC_X86_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/global.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/global.hpp new file mode 100644 index 00000000..9d1b58db --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/global.hpp @@ -0,0 +1,52 @@ +// +// detail/global.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_GLOBAL_HPP +#define ASIO_DETAIL_GLOBAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_global.hpp" +#elif defined(ASIO_WINDOWS) +# include "asio/detail/win_global.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_global.hpp" +#elif defined(ASIO_HAS_STD_CALL_ONCE) +# include "asio/detail/std_global.hpp" +#else +# error Only Windows, POSIX and std::call_once are supported! +#endif + +namespace asio { +namespace detail { + +template +inline T& global() +{ +#if !defined(ASIO_HAS_THREADS) + return null_global(); +#elif defined(ASIO_WINDOWS) + return win_global(); +#elif defined(ASIO_HAS_PTHREADS) + return posix_global(); +#elif defined(ASIO_HAS_STD_CALL_ONCE) + return std_global(); +#endif +} + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_GLOBAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_alloc_helpers.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_alloc_helpers.hpp new file mode 100644 index 00000000..ef3ff87f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_alloc_helpers.hpp @@ -0,0 +1,242 @@ +// +// detail/handler_alloc_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP +#define ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/handler_alloc_hook.hpp" + +#include "asio/detail/push_options.hpp" + +// Calls to asio_handler_allocate and asio_handler_deallocate must be made from +// a namespace that does not contain any overloads of these functions. The +// asio_handler_alloc_helpers namespace is defined here for that purpose. +namespace asio_handler_alloc_helpers { + +template +inline void* allocate(std::size_t s, Handler& h) +{ +#if !defined(ASIO_HAS_HANDLER_HOOKS) + return ::operator new(s); +#else + using asio::asio_handler_allocate; + return asio_handler_allocate(s, asio::detail::addressof(h)); +#endif +} + +template +inline void deallocate(void* p, std::size_t s, Handler& h) +{ +#if !defined(ASIO_HAS_HANDLER_HOOKS) + ::operator delete(p); +#else + using asio::asio_handler_deallocate; + asio_handler_deallocate(p, s, asio::detail::addressof(h)); +#endif +} + +} // namespace asio_handler_alloc_helpers + +namespace asio { +namespace detail { + +template +class hook_allocator +{ +public: + typedef T value_type; + + template + struct rebind + { + typedef hook_allocator other; + }; + + explicit hook_allocator(Handler& h) + : handler_(h) + { + } + + template + hook_allocator(const hook_allocator& a) + : handler_(a.handler_) + { + } + + T* allocate(std::size_t n) + { + return static_cast( + asio_handler_alloc_helpers::allocate(sizeof(T) * n, handler_)); + } + + void deallocate(T* p, std::size_t n) + { + asio_handler_alloc_helpers::deallocate(p, sizeof(T) * n, handler_); + } + +//private: + Handler& handler_; +}; + +template +class hook_allocator +{ +public: + typedef void value_type; + + template + struct rebind + { + typedef hook_allocator other; + }; + + explicit hook_allocator(Handler& h) + : handler_(h) + { + } + + template + hook_allocator(const hook_allocator& a) + : handler_(a.handler_) + { + } + +//private: + Handler& handler_; +}; + +template +struct get_hook_allocator +{ + typedef Allocator type; + + static type get(Handler&, const Allocator& a) + { + return a; + } +}; + +template +struct get_hook_allocator > +{ + typedef hook_allocator type; + + static type get(Handler& handler, const std::allocator&) + { + return type(handler); + } +}; + +} // namespace detail +} // namespace asio + +#define ASIO_DEFINE_HANDLER_PTR(op) \ + struct ptr \ + { \ + Handler* h; \ + op* v; \ + op* p; \ + ~ptr() \ + { \ + reset(); \ + } \ + static op* allocate(Handler& handler) \ + { \ + typedef typename ::asio::associated_allocator< \ + Handler>::type associated_allocator_type; \ + typedef typename ::asio::detail::get_hook_allocator< \ + Handler, associated_allocator_type>::type hook_allocator_type; \ + ASIO_REBIND_ALLOC(hook_allocator_type, op) a( \ + ::asio::detail::get_hook_allocator< \ + Handler, associated_allocator_type>::get( \ + handler, ::asio::get_associated_allocator(handler))); \ + return a.allocate(1); \ + } \ + void reset() \ + { \ + if (p) \ + { \ + p->~op(); \ + p = 0; \ + } \ + if (v) \ + { \ + typedef typename ::asio::associated_allocator< \ + Handler>::type associated_allocator_type; \ + typedef typename ::asio::detail::get_hook_allocator< \ + Handler, associated_allocator_type>::type hook_allocator_type; \ + ASIO_REBIND_ALLOC(hook_allocator_type, op) a( \ + ::asio::detail::get_hook_allocator< \ + Handler, associated_allocator_type>::get( \ + *h, ::asio::get_associated_allocator(*h))); \ + a.deallocate(static_cast(v), 1); \ + v = 0; \ + } \ + } \ + } \ + /**/ + +#define ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR(purpose, op) \ + struct ptr \ + { \ + const Alloc* a; \ + void* v; \ + op* p; \ + ~ptr() \ + { \ + reset(); \ + } \ + static op* allocate(const Alloc& a) \ + { \ + typedef typename ::asio::detail::get_recycling_allocator< \ + Alloc, purpose>::type recycling_allocator_type; \ + ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ + ::asio::detail::get_recycling_allocator< \ + Alloc, purpose>::get(a)); \ + return a1.allocate(1); \ + } \ + void reset() \ + { \ + if (p) \ + { \ + p->~op(); \ + p = 0; \ + } \ + if (v) \ + { \ + typedef typename ::asio::detail::get_recycling_allocator< \ + Alloc, purpose>::type recycling_allocator_type; \ + ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ + ::asio::detail::get_recycling_allocator< \ + Alloc, purpose>::get(*a)); \ + a1.deallocate(static_cast(v), 1); \ + v = 0; \ + } \ + } \ + } \ + /**/ + +#define ASIO_DEFINE_HANDLER_ALLOCATOR_PTR(op) \ + ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR( \ + ::asio::detail::thread_info_base::default_tag, op ) \ + /**/ + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_cont_helpers.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_cont_helpers.hpp new file mode 100644 index 00000000..0abefbe5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_cont_helpers.hpp @@ -0,0 +1,45 @@ +// +// detail/handler_cont_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_CONT_HELPERS_HPP +#define ASIO_DETAIL_HANDLER_CONT_HELPERS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/memory.hpp" +#include "asio/handler_continuation_hook.hpp" + +#include "asio/detail/push_options.hpp" + +// Calls to asio_handler_is_continuation must be made from a namespace that +// does not contain overloads of this function. This namespace is defined here +// for that purpose. +namespace asio_handler_cont_helpers { + +template +inline bool is_continuation(Context& context) +{ +#if !defined(ASIO_HAS_HANDLER_HOOKS) + return false; +#else + using asio::asio_handler_is_continuation; + return asio_handler_is_continuation( + asio::detail::addressof(context)); +#endif +} + +} // namespace asio_handler_cont_helpers + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HANDLER_CONT_HELPERS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_invoke_helpers.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_invoke_helpers.hpp new file mode 100644 index 00000000..5bab1b08 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_invoke_helpers.hpp @@ -0,0 +1,57 @@ +// +// detail/handler_invoke_helpers.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP +#define ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/memory.hpp" +#include "asio/handler_invoke_hook.hpp" + +#include "asio/detail/push_options.hpp" + +// Calls to asio_handler_invoke must be made from a namespace that does not +// contain overloads of this function. The asio_handler_invoke_helpers +// namespace is defined here for that purpose. +namespace asio_handler_invoke_helpers { + +template +inline void invoke(Function& function, Context& context) +{ +#if !defined(ASIO_HAS_HANDLER_HOOKS) + Function tmp(function); + tmp(); +#else + using asio::asio_handler_invoke; + asio_handler_invoke(function, asio::detail::addressof(context)); +#endif +} + +template +inline void invoke(const Function& function, Context& context) +{ +#if !defined(ASIO_HAS_HANDLER_HOOKS) + Function tmp(function); + tmp(); +#else + using asio::asio_handler_invoke; + asio_handler_invoke(function, asio::detail::addressof(context)); +#endif +} + +} // namespace asio_handler_invoke_helpers + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HANDLER_INVOKE_HELPERS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_tracking.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_tracking.hpp new file mode 100644 index 00000000..d8276de2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_tracking.hpp @@ -0,0 +1,238 @@ +// +// detail/handler_tracking.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_TRACKING_HPP +#define ASIO_DETAIL_HANDLER_TRACKING_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +namespace asio { + +class execution_context; + +} // namespace asio + +#if defined(ASIO_CUSTOM_HANDLER_TRACKING) +# include ASIO_CUSTOM_HANDLER_TRACKING +#elif defined(ASIO_ENABLE_HANDLER_TRACKING) +# include "asio/error_code.hpp" +# include "asio/detail/cstdint.hpp" +# include "asio/detail/static_mutex.hpp" +# include "asio/detail/tss_ptr.hpp" +#endif // defined(ASIO_ENABLE_HANDLER_TRACKING) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_CUSTOM_HANDLER_TRACKING) + +// The user-specified header must define the following macros: +// - ASIO_INHERIT_TRACKED_HANDLER +// - ASIO_ALSO_INHERIT_TRACKED_HANDLER +// - ASIO_HANDLER_TRACKING_INIT +// - ASIO_HANDLER_CREATION(args) +// - ASIO_HANDLER_COMPLETION(args) +// - ASIO_HANDLER_INVOCATION_BEGIN(args) +// - ASIO_HANDLER_INVOCATION_END +// - ASIO_HANDLER_OPERATION(args) +// - ASIO_HANDLER_REACTOR_REGISTRATION(args) +// - ASIO_HANDLER_REACTOR_DEREGISTRATION(args) +// - ASIO_HANDLER_REACTOR_READ_EVENT +// - ASIO_HANDLER_REACTOR_WRITE_EVENT +// - ASIO_HANDLER_REACTOR_ERROR_EVENT +// - ASIO_HANDLER_REACTOR_EVENTS(args) +// - ASIO_HANDLER_REACTOR_OPERATION(args) + +# if !defined(ASIO_ENABLE_HANDLER_TRACKING) +# define ASIO_ENABLE_HANDLER_TRACKING 1 +# endif /// !defined(ASIO_ENABLE_HANDLER_TRACKING) + +#elif defined(ASIO_ENABLE_HANDLER_TRACKING) + +class handler_tracking +{ +public: + class completion; + + // Base class for objects containing tracked handlers. + class tracked_handler + { + private: + // Only the handler_tracking class will have access to the id. + friend class handler_tracking; + friend class completion; + uint64_t id_; + + protected: + // Constructor initialises with no id. + tracked_handler() : id_(0) {} + + // Prevent deletion through this type. + ~tracked_handler() {} + }; + + // Initialise the tracking system. + ASIO_DECL static void init(); + + // Record the creation of a tracked handler. + ASIO_DECL static void creation( + execution_context& context, tracked_handler& h, + const char* object_type, void* object, + uintmax_t native_handle, const char* op_name); + + class completion + { + public: + // Constructor records that handler is to be invoked with no arguments. + ASIO_DECL explicit completion(const tracked_handler& h); + + // Destructor records only when an exception is thrown from the handler, or + // if the memory is being freed without the handler having been invoked. + ASIO_DECL ~completion(); + + // Records that handler is to be invoked with no arguments. + ASIO_DECL void invocation_begin(); + + // Records that handler is to be invoked with one arguments. + ASIO_DECL void invocation_begin(const asio::error_code& ec); + + // Constructor records that handler is to be invoked with two arguments. + ASIO_DECL void invocation_begin( + const asio::error_code& ec, std::size_t bytes_transferred); + + // Constructor records that handler is to be invoked with two arguments. + ASIO_DECL void invocation_begin( + const asio::error_code& ec, int signal_number); + + // Constructor records that handler is to be invoked with two arguments. + ASIO_DECL void invocation_begin( + const asio::error_code& ec, const char* arg); + + // Record that handler invocation has ended. + ASIO_DECL void invocation_end(); + + private: + friend class handler_tracking; + uint64_t id_; + bool invoked_; + completion* next_; + }; + + // Record an operation that is not directly associated with a handler. + ASIO_DECL static void operation(execution_context& context, + const char* object_type, void* object, + uintmax_t native_handle, const char* op_name); + + // Record that a descriptor has been registered with the reactor. + ASIO_DECL static void reactor_registration(execution_context& context, + uintmax_t native_handle, uintmax_t registration); + + // Record that a descriptor has been deregistered from the reactor. + ASIO_DECL static void reactor_deregistration(execution_context& context, + uintmax_t native_handle, uintmax_t registration); + + // Record a reactor-based operation that is associated with a handler. + ASIO_DECL static void reactor_events(execution_context& context, + uintmax_t registration, unsigned events); + + // Record a reactor-based operation that is associated with a handler. + ASIO_DECL static void reactor_operation( + const tracked_handler& h, const char* op_name, + const asio::error_code& ec); + + // Record a reactor-based operation that is associated with a handler. + ASIO_DECL static void reactor_operation( + const tracked_handler& h, const char* op_name, + const asio::error_code& ec, std::size_t bytes_transferred); + + // Write a line of output. + ASIO_DECL static void write_line(const char* format, ...); + +private: + struct tracking_state; + ASIO_DECL static tracking_state* get_state(); +}; + +# define ASIO_INHERIT_TRACKED_HANDLER \ + : public asio::detail::handler_tracking::tracked_handler + +# define ASIO_ALSO_INHERIT_TRACKED_HANDLER \ + , public asio::detail::handler_tracking::tracked_handler + +# define ASIO_HANDLER_TRACKING_INIT \ + asio::detail::handler_tracking::init() + +# define ASIO_HANDLER_CREATION(args) \ + asio::detail::handler_tracking::creation args + +# define ASIO_HANDLER_COMPLETION(args) \ + asio::detail::handler_tracking::completion tracked_completion args + +# define ASIO_HANDLER_INVOCATION_BEGIN(args) \ + tracked_completion.invocation_begin args + +# define ASIO_HANDLER_INVOCATION_END \ + tracked_completion.invocation_end() + +# define ASIO_HANDLER_OPERATION(args) \ + asio::detail::handler_tracking::operation args + +# define ASIO_HANDLER_REACTOR_REGISTRATION(args) \ + asio::detail::handler_tracking::reactor_registration args + +# define ASIO_HANDLER_REACTOR_DEREGISTRATION(args) \ + asio::detail::handler_tracking::reactor_deregistration args + +# define ASIO_HANDLER_REACTOR_READ_EVENT 1 +# define ASIO_HANDLER_REACTOR_WRITE_EVENT 2 +# define ASIO_HANDLER_REACTOR_ERROR_EVENT 4 + +# define ASIO_HANDLER_REACTOR_EVENTS(args) \ + asio::detail::handler_tracking::reactor_events args + +# define ASIO_HANDLER_REACTOR_OPERATION(args) \ + asio::detail::handler_tracking::reactor_operation args + +#else // defined(ASIO_ENABLE_HANDLER_TRACKING) + +# define ASIO_INHERIT_TRACKED_HANDLER +# define ASIO_ALSO_INHERIT_TRACKED_HANDLER +# define ASIO_HANDLER_TRACKING_INIT (void)0 +# define ASIO_HANDLER_CREATION(args) (void)0 +# define ASIO_HANDLER_COMPLETION(args) (void)0 +# define ASIO_HANDLER_INVOCATION_BEGIN(args) (void)0 +# define ASIO_HANDLER_INVOCATION_END (void)0 +# define ASIO_HANDLER_OPERATION(args) (void)0 +# define ASIO_HANDLER_REACTOR_REGISTRATION(args) (void)0 +# define ASIO_HANDLER_REACTOR_DEREGISTRATION(args) (void)0 +# define ASIO_HANDLER_REACTOR_READ_EVENT 0 +# define ASIO_HANDLER_REACTOR_WRITE_EVENT 0 +# define ASIO_HANDLER_REACTOR_ERROR_EVENT 0 +# define ASIO_HANDLER_REACTOR_EVENTS(args) (void)0 +# define ASIO_HANDLER_REACTOR_OPERATION(args) (void)0 + +#endif // defined(ASIO_ENABLE_HANDLER_TRACKING) + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/handler_tracking.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_HANDLER_TRACKING_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_type_requirements.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_type_requirements.hpp new file mode 100644 index 00000000..1b941ff3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_type_requirements.hpp @@ -0,0 +1,556 @@ +// +// detail/handler_type_requirements.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_TYPE_REQUIREMENTS_HPP +#define ASIO_DETAIL_HANDLER_TYPE_REQUIREMENTS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +// Older versions of gcc have difficulty compiling the sizeof expressions where +// we test the handler type requirements. We'll disable checking of handler type +// requirements for those compilers, but otherwise enable it by default. +#if !defined(ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS) +# if !defined(__GNUC__) || (__GNUC__ >= 4) +# define ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS 1 +# endif // !defined(__GNUC__) || (__GNUC__ >= 4) +#endif // !defined(ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS) + +// With C++0x we can use a combination of enhanced SFINAE and static_assert to +// generate better template error messages. As this technique is not yet widely +// portable, we'll only enable it for tested compilers. +#if !defined(ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT) +# if defined(__GNUC__) +# if ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# if defined(__GXX_EXPERIMENTAL_CXX0X__) +# define ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT 1 +# endif // defined(__GXX_EXPERIMENTAL_CXX0X__) +# endif // ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 5)) || (__GNUC__ > 4) +# endif // defined(__GNUC__) +# if defined(ASIO_MSVC) +# if (_MSC_VER >= 1600) +# define ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT 1 +# endif // (_MSC_VER >= 1600) +# endif // defined(ASIO_MSVC) +# if defined(__clang__) +# if __has_feature(__cxx_static_assert__) +# define ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT 1 +# endif // __has_feature(cxx_static_assert) +# endif // defined(__clang__) +#endif // !defined(ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS) + +#if defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS) +# include "asio/async_result.hpp" +#endif // defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS) + +namespace asio { +namespace detail { + +#if defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS) + +# if defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT) + +template +auto zero_arg_copyable_handler_test(Handler h, void*) + -> decltype( + sizeof(Handler(static_cast(h))), + ((h)()), + char(0)); + +template +char (&zero_arg_copyable_handler_test(Handler, ...))[2]; + +template +auto one_arg_handler_test(Handler h, Arg1* a1) + -> decltype( + sizeof(Handler(ASIO_MOVE_CAST(Handler)(h))), + ((h)(*a1)), + char(0)); + +template +char (&one_arg_handler_test(Handler h, ...))[2]; + +template +auto two_arg_handler_test(Handler h, Arg1* a1, Arg2* a2) + -> decltype( + sizeof(Handler(ASIO_MOVE_CAST(Handler)(h))), + ((h)(*a1, *a2)), + char(0)); + +template +char (&two_arg_handler_test(Handler, ...))[2]; + +template +auto two_arg_move_handler_test(Handler h, Arg1* a1, Arg2* a2) + -> decltype( + sizeof(Handler(ASIO_MOVE_CAST(Handler)(h))), + ((h)(*a1, ASIO_MOVE_CAST(Arg2)(*a2))), + char(0)); + +template +char (&two_arg_move_handler_test(Handler, ...))[2]; + +# define ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT(expr, msg) \ + static_assert(expr, msg); + +# else // defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT) + +# define ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT(expr, msg) + +# endif // defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS_ASSERT) + +template T& lvref(); +template T& lvref(T); +template const T& clvref(); +template const T& clvref(T); +#if defined(ASIO_HAS_MOVE) +template T rvref(); +template T rvref(T); +#else // defined(ASIO_HAS_MOVE) +template const T& rvref(); +template const T& rvref(T); +#endif // defined(ASIO_HAS_MOVE) +template char argbyv(T); + +template +struct handler_type_requirements +{ +}; + +#define ASIO_LEGACY_COMPLETION_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void()) asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::zero_arg_copyable_handler_test( \ + asio::detail::clvref< \ + asio_true_handler_type>(), 0)) == 1, \ + "CompletionHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::clvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()(), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_READ_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, std::size_t)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "ReadHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_WRITE_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, std::size_t)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "WriteHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_ACCEPT_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::one_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0))) == 1, \ + "AcceptHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_MOVE_ACCEPT_HANDLER_CHECK( \ + handler_type, handler, socket_type) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, socket_type)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_move_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "MoveAcceptHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::rvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_CONNECT_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::one_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0))) == 1, \ + "ConnectHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_RANGE_CONNECT_HANDLER_CHECK( \ + handler_type, handler, endpoint_type) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, endpoint_type)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "RangeConnectHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_ITERATOR_CONNECT_HANDLER_CHECK( \ + handler_type, handler, iter_type) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, iter_type)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "IteratorConnectHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_RESOLVE_HANDLER_CHECK( \ + handler_type, handler, range_type) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, range_type)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "ResolveHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_WAIT_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::one_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0))) == 1, \ + "WaitHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_SIGNAL_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, int)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "SignalHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_HANDSHAKE_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::one_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0))) == 1, \ + "HandshakeHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_BUFFERED_HANDSHAKE_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code, std::size_t)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::two_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0), \ + static_cast(0))) == 1, \ + "BufferedHandshakeHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref(), \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#define ASIO_SHUTDOWN_HANDLER_CHECK( \ + handler_type, handler) \ + \ + typedef ASIO_HANDLER_TYPE(handler_type, \ + void(asio::error_code)) \ + asio_true_handler_type; \ + \ + ASIO_HANDLER_TYPE_REQUIREMENTS_ASSERT( \ + sizeof(asio::detail::one_arg_handler_test( \ + asio::detail::rvref< \ + asio_true_handler_type>(), \ + static_cast(0))) == 1, \ + "ShutdownHandler type requirements not met") \ + \ + typedef asio::detail::handler_type_requirements< \ + sizeof( \ + asio::detail::argbyv( \ + asio::detail::rvref< \ + asio_true_handler_type>())) + \ + sizeof( \ + asio::detail::lvref< \ + asio_true_handler_type>()( \ + asio::detail::lvref()), \ + char(0))> ASIO_UNUSED_TYPEDEF + +#else // !defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS) + +#define ASIO_LEGACY_COMPLETION_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_READ_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_WRITE_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_ACCEPT_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_MOVE_ACCEPT_HANDLER_CHECK( \ + handler_type, handler, socket_type) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_CONNECT_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_RANGE_CONNECT_HANDLER_CHECK( \ + handler_type, handler, iter_type) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_ITERATOR_CONNECT_HANDLER_CHECK( \ + handler_type, handler, iter_type) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_RESOLVE_HANDLER_CHECK( \ + handler_type, handler, iter_type) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_WAIT_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_SIGNAL_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_HANDSHAKE_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_BUFFERED_HANDSHAKE_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#define ASIO_SHUTDOWN_HANDLER_CHECK( \ + handler_type, handler) \ + typedef int ASIO_UNUSED_TYPEDEF + +#endif // !defined(ASIO_ENABLE_HANDLER_TYPE_REQUIREMENTS) + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_HANDLER_TYPE_REQUIREMENTS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_work.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_work.hpp new file mode 100644 index 00000000..02528a71 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/handler_work.hpp @@ -0,0 +1,113 @@ +// +// detail/handler_work.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HANDLER_WORK_HPP +#define ASIO_DETAIL_HANDLER_WORK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// A helper class template to allow completion handlers to be dispatched +// through either the new executors framework or the old invocaton hook. The +// primary template uses the new executors framework. +template ::type> +class handler_work +{ +public: + explicit handler_work(Handler& handler) ASIO_NOEXCEPT + : io_executor_(), + executor_(asio::get_associated_executor(handler, io_executor_)) + { + } + + handler_work(Handler& handler, const IoExecutor& io_ex) ASIO_NOEXCEPT + : io_executor_(io_ex), + executor_(asio::get_associated_executor(handler, io_executor_)) + { + } + + static void start(Handler& handler) ASIO_NOEXCEPT + { + HandlerExecutor ex(asio::get_associated_executor(handler)); + ex.on_work_started(); + } + + static void start(Handler& handler, + const IoExecutor& io_ex) ASIO_NOEXCEPT + { + HandlerExecutor ex(asio::get_associated_executor(handler, io_ex)); + ex.on_work_started(); + io_ex.on_work_started(); + } + + ~handler_work() + { + io_executor_.on_work_finished(); + executor_.on_work_finished(); + } + + template + void complete(Function& function, Handler& handler) + { + executor_.dispatch(ASIO_MOVE_CAST(Function)(function), + asio::get_associated_allocator(handler)); + } + +private: + // Disallow copying and assignment. + handler_work(const handler_work&); + handler_work& operator=(const handler_work&); + + IoExecutor io_executor_; + HandlerExecutor executor_; +}; + +// This specialisation dispatches a handler through the old invocation hook. +// The specialisation is not strictly required for correctness, as the +// system_executor will dispatch through the hook anyway. However, by doing +// this we avoid an extra copy of the handler. +template +class handler_work +{ +public: + explicit handler_work(Handler&) ASIO_NOEXCEPT {} + static void start(Handler&) ASIO_NOEXCEPT {} + ~handler_work() {} + + template + void complete(Function& function, Handler& handler) + { + asio_handler_invoke_helpers::invoke(function, handler); + } + +private: + // Disallow copying and assignment. + handler_work(const handler_work&); + handler_work& operator=(const handler_work&); +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HANDLER_WORK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/hash_map.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/hash_map.hpp new file mode 100644 index 00000000..b9f9325a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/hash_map.hpp @@ -0,0 +1,331 @@ +// +// detail/hash_map.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_HASH_MAP_HPP +#define ASIO_DETAIL_HASH_MAP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/detail/assert.hpp" +#include "asio/detail/noncopyable.hpp" + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# include "asio/detail/socket_types.hpp" +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +inline std::size_t calculate_hash_value(int i) +{ + return static_cast(i); +} + +inline std::size_t calculate_hash_value(void* p) +{ + return reinterpret_cast(p) + + (reinterpret_cast(p) >> 3); +} + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +inline std::size_t calculate_hash_value(SOCKET s) +{ + return static_cast(s); +} +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +// Note: assumes K and V are POD types. +template +class hash_map + : private noncopyable +{ +public: + // The type of a value in the map. + typedef std::pair value_type; + + // The type of a non-const iterator over the hash map. + typedef typename std::list::iterator iterator; + + // The type of a const iterator over the hash map. + typedef typename std::list::const_iterator const_iterator; + + // Constructor. + hash_map() + : size_(0), + buckets_(0), + num_buckets_(0) + { + } + + // Destructor. + ~hash_map() + { + delete[] buckets_; + } + + // Get an iterator for the beginning of the map. + iterator begin() + { + return values_.begin(); + } + + // Get an iterator for the beginning of the map. + const_iterator begin() const + { + return values_.begin(); + } + + // Get an iterator for the end of the map. + iterator end() + { + return values_.end(); + } + + // Get an iterator for the end of the map. + const_iterator end() const + { + return values_.end(); + } + + // Check whether the map is empty. + bool empty() const + { + return values_.empty(); + } + + // Find an entry in the map. + iterator find(const K& k) + { + if (num_buckets_) + { + size_t bucket = calculate_hash_value(k) % num_buckets_; + iterator it = buckets_[bucket].first; + if (it == values_.end()) + return values_.end(); + iterator end_it = buckets_[bucket].last; + ++end_it; + while (it != end_it) + { + if (it->first == k) + return it; + ++it; + } + } + return values_.end(); + } + + // Find an entry in the map. + const_iterator find(const K& k) const + { + if (num_buckets_) + { + size_t bucket = calculate_hash_value(k) % num_buckets_; + const_iterator it = buckets_[bucket].first; + if (it == values_.end()) + return it; + const_iterator end_it = buckets_[bucket].last; + ++end_it; + while (it != end_it) + { + if (it->first == k) + return it; + ++it; + } + } + return values_.end(); + } + + // Insert a new entry into the map. + std::pair insert(const value_type& v) + { + if (size_ + 1 >= num_buckets_) + rehash(hash_size(size_ + 1)); + size_t bucket = calculate_hash_value(v.first) % num_buckets_; + iterator it = buckets_[bucket].first; + if (it == values_.end()) + { + buckets_[bucket].first = buckets_[bucket].last = + values_insert(values_.end(), v); + ++size_; + return std::pair(buckets_[bucket].last, true); + } + iterator end_it = buckets_[bucket].last; + ++end_it; + while (it != end_it) + { + if (it->first == v.first) + return std::pair(it, false); + ++it; + } + buckets_[bucket].last = values_insert(end_it, v); + ++size_; + return std::pair(buckets_[bucket].last, true); + } + + // Erase an entry from the map. + void erase(iterator it) + { + ASIO_ASSERT(it != values_.end()); + ASIO_ASSERT(num_buckets_ != 0); + + size_t bucket = calculate_hash_value(it->first) % num_buckets_; + bool is_first = (it == buckets_[bucket].first); + bool is_last = (it == buckets_[bucket].last); + if (is_first && is_last) + buckets_[bucket].first = buckets_[bucket].last = values_.end(); + else if (is_first) + ++buckets_[bucket].first; + else if (is_last) + --buckets_[bucket].last; + + values_erase(it); + --size_; + } + + // Erase a key from the map. + void erase(const K& k) + { + iterator it = find(k); + if (it != values_.end()) + erase(it); + } + + // Remove all entries from the map. + void clear() + { + // Clear the values. + values_.clear(); + size_ = 0; + + // Initialise all buckets to empty. + iterator end_it = values_.end(); + for (size_t i = 0; i < num_buckets_; ++i) + buckets_[i].first = buckets_[i].last = end_it; + } + +private: + // Calculate the hash size for the specified number of elements. + static std::size_t hash_size(std::size_t num_elems) + { + static std::size_t sizes[] = + { +#if defined(ASIO_HASH_MAP_BUCKETS) + ASIO_HASH_MAP_BUCKETS +#else // ASIO_HASH_MAP_BUCKETS + 3, 13, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, + 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, + 12582917, 25165843 +#endif // ASIO_HASH_MAP_BUCKETS + }; + const std::size_t nth_size = sizeof(sizes) / sizeof(std::size_t) - 1; + for (std::size_t i = 0; i < nth_size; ++i) + if (num_elems < sizes[i]) + return sizes[i]; + return sizes[nth_size]; + } + + // Re-initialise the hash from the values already contained in the list. + void rehash(std::size_t num_buckets) + { + if (num_buckets == num_buckets_) + return; + ASIO_ASSERT(num_buckets != 0); + + iterator end_iter = values_.end(); + + // Update number of buckets and initialise all buckets to empty. + bucket_type* tmp = new bucket_type[num_buckets]; + delete[] buckets_; + buckets_ = tmp; + num_buckets_ = num_buckets; + for (std::size_t i = 0; i < num_buckets_; ++i) + buckets_[i].first = buckets_[i].last = end_iter; + + // Put all values back into the hash. + iterator iter = values_.begin(); + while (iter != end_iter) + { + std::size_t bucket = calculate_hash_value(iter->first) % num_buckets_; + if (buckets_[bucket].last == end_iter) + { + buckets_[bucket].first = buckets_[bucket].last = iter++; + } + else if (++buckets_[bucket].last == iter) + { + ++iter; + } + else + { + values_.splice(buckets_[bucket].last, values_, iter++); + --buckets_[bucket].last; + } + } + } + + // Insert an element into the values list by splicing from the spares list, + // if a spare is available, and otherwise by inserting a new element. + iterator values_insert(iterator it, const value_type& v) + { + if (spares_.empty()) + { + return values_.insert(it, v); + } + else + { + spares_.front() = v; + values_.splice(it, spares_, spares_.begin()); + return --it; + } + } + + // Erase an element from the values list by splicing it to the spares list. + void values_erase(iterator it) + { + *it = value_type(); + spares_.splice(spares_.begin(), values_, it); + } + + // The number of elements in the hash. + std::size_t size_; + + // The list of all values in the hash map. + std::list values_; + + // The list of spare nodes waiting to be recycled. Assumes that POD types only + // are stored in the hash map. + std::list spares_; + + // The type for a bucket in the hash table. + struct bucket_type + { + iterator first; + iterator last; + }; + + // The buckets in the hash. + bucket_type* buckets_; + + // The number of buckets in the hash. + std::size_t num_buckets_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_HASH_MAP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/dev_poll_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/dev_poll_reactor.hpp new file mode 100644 index 00000000..6cee8e21 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/dev_poll_reactor.hpp @@ -0,0 +1,91 @@ +// +// detail/impl/dev_poll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_DEV_POLL_REACTOR_HPP +#define ASIO_DETAIL_IMPL_DEV_POLL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_DEV_POLL) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void dev_poll_reactor::add_timer_queue(timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +template +void dev_poll_reactor::remove_timer_queue(timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void dev_poll_reactor::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + + if (shutdown_) + { + scheduler_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + scheduler_.work_started(); + if (earliest) + interrupter_.interrupt(); +} + +template +std::size_t dev_poll_reactor::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + lock.unlock(); + scheduler_.post_deferred_completions(ops); + return n; +} + +template +void dev_poll_reactor::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + queue.cancel_timer(target, ops); + queue.move_timer(target, source); + lock.unlock(); + scheduler_.post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_DEV_POLL) + +#endif // ASIO_DETAIL_IMPL_DEV_POLL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/epoll_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/epoll_reactor.hpp new file mode 100644 index 00000000..ddfcb5e2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/epoll_reactor.hpp @@ -0,0 +1,89 @@ +// +// detail/impl/epoll_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_EPOLL_REACTOR_HPP +#define ASIO_DETAIL_IMPL_EPOLL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if defined(ASIO_HAS_EPOLL) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void epoll_reactor::add_timer_queue(timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +template +void epoll_reactor::remove_timer_queue(timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void epoll_reactor::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + mutex::scoped_lock lock(mutex_); + + if (shutdown_) + { + scheduler_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + scheduler_.work_started(); + if (earliest) + update_timeout(); +} + +template +std::size_t epoll_reactor::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + mutex::scoped_lock lock(mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + lock.unlock(); + scheduler_.post_deferred_completions(ops); + return n; +} + +template +void epoll_reactor::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source) +{ + mutex::scoped_lock lock(mutex_); + op_queue ops; + queue.cancel_timer(target, ops); + queue.move_timer(target, source); + lock.unlock(); + scheduler_.post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_EPOLL) + +#endif // ASIO_DETAIL_IMPL_EPOLL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/kqueue_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/kqueue_reactor.hpp new file mode 100644 index 00000000..3028ebb2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/kqueue_reactor.hpp @@ -0,0 +1,93 @@ +// +// detail/impl/kqueue_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2005 Stefan Arentz (stefan at soze dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_KQUEUE_REACTOR_HPP +#define ASIO_DETAIL_IMPL_KQUEUE_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_KQUEUE) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void kqueue_reactor::add_timer_queue(timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +// Remove a timer queue from the reactor. +template +void kqueue_reactor::remove_timer_queue(timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void kqueue_reactor::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + mutex::scoped_lock lock(mutex_); + + if (shutdown_) + { + scheduler_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + scheduler_.work_started(); + if (earliest) + interrupt(); +} + +template +std::size_t kqueue_reactor::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + mutex::scoped_lock lock(mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + lock.unlock(); + scheduler_.post_deferred_completions(ops); + return n; +} + +template +void kqueue_reactor::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source) +{ + mutex::scoped_lock lock(mutex_); + op_queue ops; + queue.cancel_timer(target, ops); + queue.move_timer(target, source); + lock.unlock(); + scheduler_.post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_KQUEUE) + +#endif // ASIO_DETAIL_IMPL_KQUEUE_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/select_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/select_reactor.hpp new file mode 100644 index 00000000..46f9cef5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/select_reactor.hpp @@ -0,0 +1,100 @@ +// +// detail/impl/select_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_SELECT_REACTOR_HPP +#define ASIO_DETAIL_IMPL_SELECT_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) \ + || (!defined(ASIO_HAS_DEV_POLL) \ + && !defined(ASIO_HAS_EPOLL) \ + && !defined(ASIO_HAS_KQUEUE) \ + && !defined(ASIO_WINDOWS_RUNTIME)) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void select_reactor::add_timer_queue(timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +// Remove a timer queue from the reactor. +template +void select_reactor::remove_timer_queue(timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void select_reactor::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + + if (shutdown_) + { + scheduler_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + scheduler_.work_started(); + if (earliest) + interrupter_.interrupt(); +} + +template +std::size_t select_reactor::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + lock.unlock(); + scheduler_.post_deferred_completions(ops); + return n; +} + +template +void select_reactor::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + queue.cancel_timer(target, ops); + queue.move_timer(target, source); + lock.unlock(); + scheduler_.post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + // || (!defined(ASIO_HAS_DEV_POLL) + // && !defined(ASIO_HAS_EPOLL) + // && !defined(ASIO_HAS_KQUEUE) + // && !defined(ASIO_WINDOWS_RUNTIME)) + +#endif // ASIO_DETAIL_IMPL_SELECT_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/service_registry.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/service_registry.hpp new file mode 100644 index 00000000..2fac89dd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/service_registry.hpp @@ -0,0 +1,94 @@ +// +// detail/impl/service_registry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP +#define ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +Service& service_registry::use_service() +{ + execution_context::service::key key; + init_key(key, 0); + factory_type factory = &service_registry::create; + return *static_cast(do_use_service(key, factory, &owner_)); +} + +template +Service& service_registry::use_service(io_context& owner) +{ + execution_context::service::key key; + init_key(key, 0); + factory_type factory = &service_registry::create; + return *static_cast(do_use_service(key, factory, &owner)); +} + +template +void service_registry::add_service(Service* new_service) +{ + execution_context::service::key key; + init_key(key, 0); + return do_add_service(key, new_service); +} + +template +bool service_registry::has_service() const +{ + execution_context::service::key key; + init_key(key, 0); + return do_has_service(key); +} + +template +inline void service_registry::init_key( + execution_context::service::key& key, ...) +{ + init_key_from_id(key, Service::id); +} + +#if !defined(ASIO_NO_TYPEID) +template +void service_registry::init_key(execution_context::service::key& key, + typename enable_if< + is_base_of::value>::type*) +{ + key.type_info_ = &typeid(typeid_wrapper); + key.id_ = 0; +} + +template +void service_registry::init_key_from_id(execution_context::service::key& key, + const service_id& /*id*/) +{ + key.type_info_ = &typeid(typeid_wrapper); + key.id_ = 0; +} +#endif // !defined(ASIO_NO_TYPEID) + +template +execution_context::service* service_registry::create(void* owner) +{ + return new Service(*static_cast(owner)); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IMPL_SERVICE_REGISTRY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_executor_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_executor_service.hpp new file mode 100644 index 00000000..3282f201 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_executor_service.hpp @@ -0,0 +1,179 @@ +// +// detail/impl/strand_executor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_STRAND_EXECUTOR_SERVICE_HPP +#define ASIO_DETAIL_IMPL_STRAND_EXECUTOR_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/call_stack.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/executor_work_guard.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class strand_executor_service::invoker +{ +public: + invoker(const implementation_type& impl, Executor& ex) + : impl_(impl), + work_(ex) + { + } + + invoker(const invoker& other) + : impl_(other.impl_), + work_(other.work_) + { + } + +#if defined(ASIO_HAS_MOVE) + invoker(invoker&& other) + : impl_(ASIO_MOVE_CAST(implementation_type)(other.impl_)), + work_(ASIO_MOVE_CAST(executor_work_guard)(other.work_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + struct on_invoker_exit + { + invoker* this_; + + ~on_invoker_exit() + { + this_->impl_->mutex_->lock(); + this_->impl_->ready_queue_.push(this_->impl_->waiting_queue_); + bool more_handlers = this_->impl_->locked_ = + !this_->impl_->ready_queue_.empty(); + this_->impl_->mutex_->unlock(); + + if (more_handlers) + { + Executor ex(this_->work_.get_executor()); + recycling_allocator allocator; + ex.post(ASIO_MOVE_CAST(invoker)(*this_), allocator); + } + } + }; + + void operator()() + { + // Indicate that this strand is executing on the current thread. + call_stack::context ctx(impl_.get()); + + // Ensure the next handler, if any, is scheduled on block exit. + on_invoker_exit on_exit = { this }; + (void)on_exit; + + // Run all ready handlers. No lock is required since the ready queue is + // accessed only within the strand. + asio::error_code ec; + while (scheduler_operation* o = impl_->ready_queue_.front()) + { + impl_->ready_queue_.pop(); + o->complete(impl_.get(), ec, 0); + } + } + +private: + implementation_type impl_; + executor_work_guard work_; +}; + +template +void strand_executor_service::dispatch(const implementation_type& impl, + Executor& ex, ASIO_MOVE_ARG(Function) function, const Allocator& a) +{ + typedef typename decay::type function_type; + + // If we are already in the strand then the function can run immediately. + if (call_stack::contains(impl.get())) + { + // Make a local, non-const copy of the function. + function_type tmp(ASIO_MOVE_CAST(Function)(function)); + + fenced_block b(fenced_block::full); + asio_handler_invoke_helpers::invoke(tmp, tmp); + return; + } + + // Allocate and construct an operation to wrap the function. + typedef executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(function), a); + + ASIO_HANDLER_CREATION((impl->service_->context(), *p.p, + "strand_executor", impl.get(), 0, "dispatch")); + + // Add the function to the strand and schedule the strand if required. + bool first = enqueue(impl, p.p); + p.v = p.p = 0; + if (first) + ex.dispatch(invoker(impl, ex), a); +} + +// Request invocation of the given function and return immediately. +template +void strand_executor_service::post(const implementation_type& impl, + Executor& ex, ASIO_MOVE_ARG(Function) function, const Allocator& a) +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(function), a); + + ASIO_HANDLER_CREATION((impl->service_->context(), *p.p, + "strand_executor", impl.get(), 0, "post")); + + // Add the function to the strand and schedule the strand if required. + bool first = enqueue(impl, p.p); + p.v = p.p = 0; + if (first) + ex.post(invoker(impl, ex), a); +} + +// Request invocation of the given function and return immediately. +template +void strand_executor_service::defer(const implementation_type& impl, + Executor& ex, ASIO_MOVE_ARG(Function) function, const Allocator& a) +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(function), a); + + ASIO_HANDLER_CREATION((impl->service_->context(), *p.p, + "strand_executor", impl.get(), 0, "defer")); + + // Add the function to the strand and schedule the strand if required. + bool first = enqueue(impl, p.p); + p.v = p.p = 0; + if (first) + ex.defer(invoker(impl, ex), a); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IMPL_STRAND_EXECUTOR_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_service.hpp new file mode 100644 index 00000000..e873698b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/strand_service.hpp @@ -0,0 +1,118 @@ +// +// detail/impl/strand_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_STRAND_SERVICE_HPP +#define ASIO_DETAIL_IMPL_STRAND_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/call_stack.hpp" +#include "asio/detail/completion_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +inline strand_service::strand_impl::strand_impl() + : operation(&strand_service::do_complete), + locked_(false) +{ +} + +struct strand_service::on_dispatch_exit +{ + io_context_impl* io_context_; + strand_impl* impl_; + + ~on_dispatch_exit() + { + impl_->mutex_.lock(); + impl_->ready_queue_.push(impl_->waiting_queue_); + bool more_handlers = impl_->locked_ = !impl_->ready_queue_.empty(); + impl_->mutex_.unlock(); + + if (more_handlers) + io_context_->post_immediate_completion(impl_, false); + } +}; + +template +void strand_service::dispatch(strand_service::implementation_type& impl, + Handler& handler) +{ + // If we are already in the strand then the handler can run immediately. + if (call_stack::contains(impl)) + { + fenced_block b(fenced_block::full); + asio_handler_invoke_helpers::invoke(handler, handler); + return; + } + + // Allocate and construct an operation to wrap the handler. + typedef completion_handler op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler); + + ASIO_HANDLER_CREATION((this->context(), + *p.p, "strand", impl, 0, "dispatch")); + + bool dispatch_immediately = do_dispatch(impl, p.p); + operation* o = p.p; + p.v = p.p = 0; + + if (dispatch_immediately) + { + // Indicate that this strand is executing on the current thread. + call_stack::context ctx(impl); + + // Ensure the next handler, if any, is scheduled on block exit. + on_dispatch_exit on_exit = { &io_context_, impl }; + (void)on_exit; + + completion_handler::do_complete( + &io_context_, o, asio::error_code(), 0); + } +} + +// Request the io_context to invoke the given handler and return immediately. +template +void strand_service::post(strand_service::implementation_type& impl, + Handler& handler) +{ + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef completion_handler op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler); + + ASIO_HANDLER_CREATION((this->context(), + *p.p, "strand", impl, 0, "post")); + + do_post(impl, p.p, is_continuation); + p.v = p.p = 0; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IMPL_STRAND_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/win_iocp_io_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/win_iocp_io_context.hpp new file mode 100644 index 00000000..1a60c6c4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/win_iocp_io_context.hpp @@ -0,0 +1,103 @@ +// +// detail/impl/win_iocp_io_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_HPP +#define ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/completion_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void win_iocp_io_context::add_timer_queue( + timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +template +void win_iocp_io_context::remove_timer_queue( + timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void win_iocp_io_context::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + // If the service has been shut down we silently discard the timer. + if (::InterlockedExchangeAdd(&shutdown_, 0) != 0) + { + post_immediate_completion(op, false); + return; + } + + mutex::scoped_lock lock(dispatch_mutex_); + + bool earliest = queue.enqueue_timer(time, timer, op); + work_started(); + if (earliest) + update_timeout(); +} + +template +std::size_t win_iocp_io_context::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + // If the service has been shut down we silently ignore the cancellation. + if (::InterlockedExchangeAdd(&shutdown_, 0) != 0) + return 0; + + mutex::scoped_lock lock(dispatch_mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + post_deferred_completions(ops); + return n; +} + +template +void win_iocp_io_context::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& to, + typename timer_queue::per_timer_data& from) +{ + asio::detail::mutex::scoped_lock lock(dispatch_mutex_); + op_queue ops; + queue.cancel_timer(to, ops); + queue.move_timer(to, from); + lock.unlock(); + post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_IMPL_WIN_IOCP_IO_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/winrt_timer_scheduler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/winrt_timer_scheduler.hpp new file mode 100644 index 00000000..9805e2fd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/impl/winrt_timer_scheduler.hpp @@ -0,0 +1,92 @@ +// +// detail/impl/winrt_timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IMPL_WINRT_TIMER_SCHEDULER_HPP +#define ASIO_DETAIL_IMPL_WINRT_TIMER_SCHEDULER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +void winrt_timer_scheduler::add_timer_queue(timer_queue& queue) +{ + do_add_timer_queue(queue); +} + +// Remove a timer queue from the reactor. +template +void winrt_timer_scheduler::remove_timer_queue(timer_queue& queue) +{ + do_remove_timer_queue(queue); +} + +template +void winrt_timer_scheduler::schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + + if (shutdown_) + { + scheduler_.post_immediate_completion(op, false); + return; + } + + bool earliest = queue.enqueue_timer(time, timer, op); + scheduler_.work_started(); + if (earliest) + event_.signal(lock); +} + +template +std::size_t winrt_timer_scheduler::cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + std::size_t n = queue.cancel_timer(timer, ops, max_cancelled); + lock.unlock(); + scheduler_.post_deferred_completions(ops); + return n; +} + +template +void winrt_timer_scheduler::move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& to, + typename timer_queue::per_timer_data& from) +{ + asio::detail::mutex::scoped_lock lock(mutex_); + op_queue ops; + queue.cancel_timer(to, ops); + queue.move_timer(to, from); + lock.unlock(); + scheduler_.post_deferred_completions(ops); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_IMPL_WINRT_TIMER_SCHEDULER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_control.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_control.hpp new file mode 100644 index 00000000..95b5feda --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_control.hpp @@ -0,0 +1,84 @@ +// +// detail/io_control.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IO_CONTROL_HPP +#define ASIO_DETAIL_IO_CONTROL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { +namespace io_control { + +// I/O control command for getting number of bytes available. +class bytes_readable +{ +public: + // Default constructor. + bytes_readable() + : value_(0) + { + } + + // Construct with a specific command value. + bytes_readable(std::size_t value) + : value_(static_cast(value)) + { + } + + // Get the name of the IO control command. + int name() const + { + return static_cast(ASIO_OS_DEF(FIONREAD)); + } + + // Set the value of the I/O control command. + void set(std::size_t value) + { + value_ = static_cast(value); + } + + // Get the current value of the I/O control command. + std::size_t get() const + { + return static_cast(value_); + } + + // Get the address of the command data. + detail::ioctl_arg_type* data() + { + return &value_; + } + + // Get the address of the command data. + const detail::ioctl_arg_type* data() const + { + return &value_; + } + +private: + detail::ioctl_arg_type value_; +}; + +} // namespace io_control +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IO_CONTROL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_executor.hpp new file mode 100644 index 00000000..6ddadf23 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_executor.hpp @@ -0,0 +1,167 @@ +// +// io_object_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IO_OBJECT_EXECUTOR_HPP +#define ASIO_DETAIL_IO_OBJECT_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Wrap the (potentially polymorphic) executor so that we can bypass it when +// dispatching on a target executor that has a native I/O implementation. +template +class io_object_executor +{ +public: + io_object_executor(const Executor& ex, + bool native_implementation) ASIO_NOEXCEPT + : executor_(ex), + has_native_impl_(native_implementation) + { + } + + io_object_executor(const io_object_executor& other) ASIO_NOEXCEPT + : executor_(other.executor_), + has_native_impl_(other.has_native_impl_) + { + } + + template + io_object_executor( + const io_object_executor& other) ASIO_NOEXCEPT + : executor_(other.inner_executor()), + has_native_impl_(other.has_native_implementation()) + { + } + +#if defined(ASIO_HAS_MOVE) + io_object_executor(io_object_executor&& other) ASIO_NOEXCEPT + : executor_(ASIO_MOVE_CAST(Executor)(other.executor_)), + has_native_impl_(other.has_native_impl_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + const Executor& inner_executor() const ASIO_NOEXCEPT + { + return executor_; + } + + bool has_native_implementation() const ASIO_NOEXCEPT + { + return has_native_impl_; + } + + execution_context& context() const ASIO_NOEXCEPT + { + return executor_.context(); + } + + void on_work_started() const ASIO_NOEXCEPT + { + if (is_same::value + || has_native_impl_) + { + // When using a native implementation, work is already counted by the + // execution context. + } + else + { + executor_.on_work_started(); + } + } + + void on_work_finished() const ASIO_NOEXCEPT + { + if (is_same::value + || has_native_impl_) + { + // When using a native implementation, work is already counted by the + // execution context. + } + else + { + executor_.on_work_finished(); + } + } + + template + void dispatch(ASIO_MOVE_ARG(F) f, const A& a) const + { + if (is_same::value + || has_native_impl_) + { + // When using a native implementation, I/O completion handlers are + // already dispatched according to the execution context's executor's + // rules. We can call the function directly. +#if defined(ASIO_HAS_MOVE) + if (is_same::type>::value) + { + asio_handler_invoke_helpers::invoke(f, f); + return; + } +#endif // defined(ASIO_HAS_MOVE) + typename decay::type function(ASIO_MOVE_CAST(F)(f)); + asio_handler_invoke_helpers::invoke(function, function); + } + else + { + executor_.dispatch(ASIO_MOVE_CAST(F)(f), a); + } + } + + template + void post(ASIO_MOVE_ARG(F) f, const A& a) const + { + executor_.post(ASIO_MOVE_CAST(F)(f), a); + } + + template + void defer(ASIO_MOVE_ARG(F) f, const A& a) const + { + executor_.defer(ASIO_MOVE_CAST(F)(f), a); + } + + friend bool operator==(const io_object_executor& a, + const io_object_executor& b) ASIO_NOEXCEPT + { + return a.executor_ == b.executor_ + && a.has_native_impl_ == b.has_native_impl_; + } + + friend bool operator!=(const io_object_executor& a, + const io_object_executor& b) ASIO_NOEXCEPT + { + return a.executor_ != b.executor_ + || a.has_native_impl_ != b.has_native_impl_; + } + +private: + Executor executor_; + const bool has_native_impl_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IO_OBJECT_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_impl.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_impl.hpp new file mode 100644 index 00000000..6f57b669 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/io_object_impl.hpp @@ -0,0 +1,193 @@ +// +// io_object_impl.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IO_OBJECT_IMPL_HPP +#define ASIO_DETAIL_IO_OBJECT_IMPL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include "asio/detail/config.hpp" +#include "asio/detail/io_object_executor.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class executor; + +namespace detail { + +inline bool is_native_io_executor(const io_context::executor_type&) +{ + return true; +} + +template +inline bool is_native_io_executor(const Executor&, + typename enable_if::value>::type* = 0) +{ + return false; +} + +template +inline bool is_native_io_executor(const Executor& ex, + typename enable_if::value>::type* = 0) +{ +#if !defined (ASIO_NO_TYPEID) + return ex.target_type() == typeid(io_context::executor_type); +#else // !defined (ASIO_NO_TYPEID) + return false; +#endif // !defined (ASIO_NO_TYPEID) +} + +template +class io_object_impl +{ +public: + // The type of the service that will be used to provide I/O operations. + typedef IoObjectService service_type; + + // The underlying implementation type of I/O object. + typedef typename service_type::implementation_type implementation_type; + + // The type of the executor associated with the object. + typedef Executor executor_type; + + // The type of executor to be used when implementing asynchronous operations. + typedef io_object_executor implementation_executor_type; + + // Construct an I/O object using an executor. + explicit io_object_impl(const executor_type& ex) + : service_(&asio::use_service(ex.context())), + implementation_executor_(ex, (is_native_io_executor)(ex)) + { + service_->construct(implementation_); + } + + // Construct an I/O object using an execution context. + template + explicit io_object_impl(ExecutionContext& context, + typename enable_if::value>::type* = 0) + : service_(&asio::use_service(context)), + implementation_executor_(context.get_executor(), + is_same::value) + { + service_->construct(implementation_); + } + +#if defined(ASIO_HAS_MOVE) + // Move-construct an I/O object. + io_object_impl(io_object_impl&& other) + : service_(&other.get_service()), + implementation_executor_(other.get_implementation_executor()) + { + service_->move_construct(implementation_, other.implementation_); + } + + // Perform a converting move-construction of an I/O object. + template + io_object_impl(io_object_impl&& other) + : service_(&asio::use_service( + other.get_implementation_executor().context())), + implementation_executor_(other.get_implementation_executor()) + { + service_->converting_move_construct(implementation_, + other.get_service(), other.get_implementation()); + } +#endif // defined(ASIO_HAS_MOVE) + + // Destructor. + ~io_object_impl() + { + service_->destroy(implementation_); + } + +#if defined(ASIO_HAS_MOVE) + // Move-assign an I/O object. + io_object_impl& operator=(io_object_impl&& other) + { + if (this != &other) + { + service_->move_assign(implementation_, + *other.service_, other.implementation_); + implementation_executor_.~implementation_executor_type(); + new (&implementation_executor_) implementation_executor_type( + std::move(other.implementation_executor_)); + service_ = other.service_; + } + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + // Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return implementation_executor_.inner_executor(); + } + + // Get the executor to be used when implementing asynchronous operations. + const implementation_executor_type& get_implementation_executor() + ASIO_NOEXCEPT + { + return implementation_executor_; + } + + // Get the service associated with the I/O object. + service_type& get_service() + { + return *service_; + } + + // Get the service associated with the I/O object. + const service_type& get_service() const + { + return *service_; + } + + // Get the underlying implementation of the I/O object. + implementation_type& get_implementation() + { + return implementation_; + } + + // Get the underlying implementation of the I/O object. + const implementation_type& get_implementation() const + { + return implementation_; + } + +private: + // Disallow copying and copy assignment. + io_object_impl(const io_object_impl&); + io_object_impl& operator=(const io_object_impl&); + + // The service associated with the I/O object. + service_type* service_; + + // The underlying implementation of the I/O object. + implementation_type implementation_; + + // The associated executor. + implementation_executor_type implementation_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IO_OBJECT_IMPL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_buffer_sequence.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_buffer_sequence.hpp new file mode 100644 index 00000000..33013767 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_buffer_sequence.hpp @@ -0,0 +1,312 @@ +// +// detail/is_buffer_sequence.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IS_BUFFER_SEQUENCE_HPP +#define ASIO_DETAIL_IS_BUFFER_SEQUENCE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class mutable_buffer; +class const_buffer; + +namespace detail { + +struct buffer_sequence_memfns_base +{ + void begin(); + void end(); + void size(); + void max_size(); + void capacity(); + void data(); + void prepare(); + void commit(); + void consume(); + void grow(); + void shrink(); +}; + +template +struct buffer_sequence_memfns_derived + : T, buffer_sequence_memfns_base +{ +}; + +template +struct buffer_sequence_memfns_check +{ +}; + +#if defined(ASIO_HAS_DECLTYPE) + +template +char buffer_sequence_begin_helper(...); + +template +char (&buffer_sequence_begin_helper(T* t, + typename enable_if::value>::type*))[2]; + +#else // defined(ASIO_HAS_DECLTYPE) + +template +char (&buffer_sequence_begin_helper(...))[2]; + +template +char buffer_sequence_begin_helper(T* t, + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::begin>*); + +#endif // defined(ASIO_HAS_DECLTYPE) + +#if defined(ASIO_HAS_DECLTYPE) + +template +char buffer_sequence_end_helper(...); + +template +char (&buffer_sequence_end_helper(T* t, + typename enable_if::value>::type*))[2]; + +#else // defined(ASIO_HAS_DECLTYPE) + +template +char (&buffer_sequence_end_helper(...))[2]; + +template +char buffer_sequence_end_helper(T* t, + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::end>*); + +#endif // defined(ASIO_HAS_DECLTYPE) + +template +char (&size_memfn_helper(...))[2]; + +template +char size_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::size>*); + +template +char (&max_size_memfn_helper(...))[2]; + +template +char max_size_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::max_size>*); + +template +char (&capacity_memfn_helper(...))[2]; + +template +char capacity_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::capacity>*); + +template +char (&data_memfn_helper(...))[2]; + +template +char data_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::data>*); + +template +char (&prepare_memfn_helper(...))[2]; + +template +char prepare_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::prepare>*); + +template +char (&commit_memfn_helper(...))[2]; + +template +char commit_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::commit>*); + +template +char (&consume_memfn_helper(...))[2]; + +template +char consume_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::consume>*); + +template +char (&grow_memfn_helper(...))[2]; + +template +char grow_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::grow>*); + +template +char (&shrink_memfn_helper(...))[2]; + +template +char shrink_memfn_helper( + buffer_sequence_memfns_check< + void (buffer_sequence_memfns_base::*)(), + &buffer_sequence_memfns_derived::shrink>*); + +template +char (&buffer_sequence_element_type_helper(...))[2]; + +#if defined(ASIO_HAS_DECLTYPE) + +template +char buffer_sequence_element_type_helper(T* t, + typename enable_if::value>::type*); + +#else // defined(ASIO_HAS_DECLTYPE) + +template +char buffer_sequence_element_type_helper( + typename T::const_iterator*, + typename enable_if::value>::type*); + +#endif // defined(ASIO_HAS_DECLTYPE) + +template +char (&const_buffers_type_typedef_helper(...))[2]; + +template +char const_buffers_type_typedef_helper( + typename T::const_buffers_type*); + +template +char (&mutable_buffers_type_typedef_helper(...))[2]; + +template +char mutable_buffers_type_typedef_helper( + typename T::mutable_buffers_type*); + +template +struct is_buffer_sequence_class + : integral_constant(0, 0)) != 1 && + sizeof(buffer_sequence_end_helper(0, 0)) != 1 && + sizeof(buffer_sequence_element_type_helper(0, 0)) == 1> +{ +}; + +template +struct is_buffer_sequence + : conditional::value, + is_buffer_sequence_class, + false_type>::type +{ +}; + +template <> +struct is_buffer_sequence + : true_type +{ +}; + +template <> +struct is_buffer_sequence + : true_type +{ +}; + +template <> +struct is_buffer_sequence + : true_type +{ +}; + +template <> +struct is_buffer_sequence + : false_type +{ +}; + +template +struct is_dynamic_buffer_class_v1 + : integral_constant(0)) != 1 && + sizeof(max_size_memfn_helper(0)) != 1 && + sizeof(capacity_memfn_helper(0)) != 1 && + sizeof(data_memfn_helper(0)) != 1 && + sizeof(consume_memfn_helper(0)) != 1 && + sizeof(prepare_memfn_helper(0)) != 1 && + sizeof(commit_memfn_helper(0)) != 1 && + sizeof(const_buffers_type_typedef_helper(0)) == 1 && + sizeof(mutable_buffers_type_typedef_helper(0)) == 1> +{ +}; + +template +struct is_dynamic_buffer_v1 + : conditional::value, + is_dynamic_buffer_class_v1, + false_type>::type +{ +}; + +template +struct is_dynamic_buffer_class_v2 + : integral_constant(0)) != 1 && + sizeof(max_size_memfn_helper(0)) != 1 && + sizeof(capacity_memfn_helper(0)) != 1 && + sizeof(data_memfn_helper(0)) != 1 && + sizeof(consume_memfn_helper(0)) != 1 && + sizeof(grow_memfn_helper(0)) != 1 && + sizeof(shrink_memfn_helper(0)) != 1 && + sizeof(const_buffers_type_typedef_helper(0)) == 1 && + sizeof(mutable_buffers_type_typedef_helper(0)) == 1> +{ +}; + +template +struct is_dynamic_buffer_v2 + : conditional::value, + is_dynamic_buffer_class_v2, + false_type>::type +{ +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IS_BUFFER_SEQUENCE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_executor.hpp new file mode 100644 index 00000000..ee11b37c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/is_executor.hpp @@ -0,0 +1,126 @@ +// +// detail/is_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_IS_EXECUTOR_HPP +#define ASIO_DETAIL_IS_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct executor_memfns_base +{ + void context(); + void on_work_started(); + void on_work_finished(); + void dispatch(); + void post(); + void defer(); +}; + +template +struct executor_memfns_derived + : T, executor_memfns_base +{ +}; + +template +struct executor_memfns_check +{ +}; + +template +char (&context_memfn_helper(...))[2]; + +template +char context_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::context>*); + +template +char (&on_work_started_memfn_helper(...))[2]; + +template +char on_work_started_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::on_work_started>*); + +template +char (&on_work_finished_memfn_helper(...))[2]; + +template +char on_work_finished_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::on_work_finished>*); + +template +char (&dispatch_memfn_helper(...))[2]; + +template +char dispatch_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::dispatch>*); + +template +char (&post_memfn_helper(...))[2]; + +template +char post_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::post>*); + +template +char (&defer_memfn_helper(...))[2]; + +template +char defer_memfn_helper( + executor_memfns_check< + void (executor_memfns_base::*)(), + &executor_memfns_derived::defer>*); + +template +struct is_executor_class + : integral_constant(0)) != 1 && + sizeof(on_work_started_memfn_helper(0)) != 1 && + sizeof(on_work_finished_memfn_helper(0)) != 1 && + sizeof(dispatch_memfn_helper(0)) != 1 && + sizeof(post_memfn_helper(0)) != 1 && + sizeof(defer_memfn_helper(0)) != 1> +{ +}; + +template +struct is_executor + : conditional::value, + is_executor_class, + false_type>::type +{ +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_IS_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/keyword_tss_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/keyword_tss_ptr.hpp new file mode 100644 index 00000000..8812e602 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/keyword_tss_ptr.hpp @@ -0,0 +1,70 @@ +// +// detail/keyword_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_KEYWORD_TSS_PTR_HPP +#define ASIO_DETAIL_KEYWORD_TSS_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class keyword_tss_ptr + : private noncopyable +{ +public: + // Constructor. + keyword_tss_ptr() + { + } + + // Destructor. + ~keyword_tss_ptr() + { + } + + // Get the value. + operator T*() const + { + return value_; + } + + // Set the value. + void operator=(T* value) + { + value_ = value; + } + +private: + static ASIO_THREAD_KEYWORD T* value_; +}; + +template +ASIO_THREAD_KEYWORD T* keyword_tss_ptr::value_; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION) + +#endif // ASIO_DETAIL_KEYWORD_TSS_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/kqueue_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/kqueue_reactor.hpp new file mode 100644 index 00000000..fb381154 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/kqueue_reactor.hpp @@ -0,0 +1,242 @@ +// +// detail/kqueue_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2005 Stefan Arentz (stefan at soze dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_KQUEUE_REACTOR_HPP +#define ASIO_DETAIL_KQUEUE_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_KQUEUE) + +#include +#include +#include +#include +#include "asio/detail/limits.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/object_pool.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/select_interrupter.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" + +// Older versions of Mac OS X may not define EV_OOBAND. +#if !defined(EV_OOBAND) +# define EV_OOBAND EV_FLAG1 +#endif // !defined(EV_OOBAND) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class scheduler; + +class kqueue_reactor + : public execution_context_service_base +{ +private: + // The mutex type used by this reactor. + typedef conditionally_enabled_mutex mutex; + +public: + enum op_types { read_op = 0, write_op = 1, + connect_op = 1, except_op = 2, max_ops = 3 }; + + // Per-descriptor queues. + struct descriptor_state + { + descriptor_state(bool locking) : mutex_(locking) {} + + friend class kqueue_reactor; + friend class object_pool_access; + + descriptor_state* next_; + descriptor_state* prev_; + + mutex mutex_; + int descriptor_; + int num_kevents_; // 1 == read only, 2 == read and write + op_queue op_queue_[max_ops]; + bool shutdown_; + }; + + // Per-descriptor data. + typedef descriptor_state* per_descriptor_data; + + // Constructor. + ASIO_DECL kqueue_reactor(asio::execution_context& ctx); + + // Destructor. + ASIO_DECL ~kqueue_reactor(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Recreate internal descriptors following a fork. + ASIO_DECL void notify_fork( + asio::execution_context::fork_event fork_ev); + + // Initialise the task. + ASIO_DECL void init_task(); + + // Register a socket with the reactor. Returns 0 on success, system error + // code on failure. + ASIO_DECL int register_descriptor(socket_type descriptor, + per_descriptor_data& descriptor_data); + + // Register a descriptor with an associated single operation. Returns 0 on + // success, system error code on failure. + ASIO_DECL int register_internal_descriptor( + int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op); + + // Move descriptor registration from one descriptor_data object to another. + ASIO_DECL void move_descriptor(socket_type descriptor, + per_descriptor_data& target_descriptor_data, + per_descriptor_data& source_descriptor_data); + + // Post a reactor operation for immediate completion. + void post_immediate_completion(reactor_op* op, bool is_continuation) + { + scheduler_.post_immediate_completion(op, is_continuation); + } + + // Start a new operation. The reactor operation will be performed when the + // given descriptor is flagged as ready, or an error has occurred. + ASIO_DECL void start_op(int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op, + bool is_continuation, bool allow_speculative); + + // Cancel all operations associated with the given descriptor. The + // handlers associated with the descriptor will be invoked with the + // operation_aborted error. + ASIO_DECL void cancel_ops(socket_type descriptor, + per_descriptor_data& descriptor_data); + + // Cancel any operations that are running against the descriptor and remove + // its registration from the reactor. The reactor resources associated with + // the descriptor must be released by calling cleanup_descriptor_data. + ASIO_DECL void deregister_descriptor(socket_type descriptor, + per_descriptor_data& descriptor_data, bool closing); + + // Remove the descriptor's registration from the reactor. The reactor + // resources associated with the descriptor must be released by calling + // cleanup_descriptor_data. + ASIO_DECL void deregister_internal_descriptor( + socket_type descriptor, per_descriptor_data& descriptor_data); + + // Perform any post-deregistration cleanup tasks associated with the + // descriptor data. + ASIO_DECL void cleanup_descriptor_data( + per_descriptor_data& descriptor_data); + + // Add a new timer queue to the reactor. + template + void add_timer_queue(timer_queue& queue); + + // Remove a timer queue from the reactor. + template + void remove_timer_queue(timer_queue& queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer operations associated with the given token. Returns the + // number of operations that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source); + + // Run the kqueue loop. + ASIO_DECL void run(long usec, op_queue& ops); + + // Interrupt the kqueue loop. + ASIO_DECL void interrupt(); + +private: + // Create the kqueue file descriptor. Throws an exception if the descriptor + // cannot be created. + ASIO_DECL static int do_kqueue_create(); + + // Allocate a new descriptor state object. + ASIO_DECL descriptor_state* allocate_descriptor_state(); + + // Free an existing descriptor state object. + ASIO_DECL void free_descriptor_state(descriptor_state* s); + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // Get the timeout value for the kevent call. + ASIO_DECL timespec* get_timeout(long usec, timespec& ts); + + // The scheduler used to post completions. + scheduler& scheduler_; + + // Mutex to protect access to internal data. + mutex mutex_; + + // The kqueue file descriptor. + int kqueue_fd_; + + // The interrupter is used to break a blocking kevent call. + select_interrupter interrupter_; + + // The timer queues. + timer_queue_set timer_queues_; + + // Whether the service has been shut down. + bool shutdown_; + + // Mutex to protect access to the registered descriptors. + mutex registered_descriptors_mutex_; + + // Keep track of all registered descriptors. + object_pool registered_descriptors_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/kqueue_reactor.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/kqueue_reactor.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_KQUEUE) + +#endif // ASIO_DETAIL_KQUEUE_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/limits.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/limits.hpp new file mode 100644 index 00000000..d32470d2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/limits.hpp @@ -0,0 +1,26 @@ +// +// detail/limits.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_LIMITS_HPP +#define ASIO_DETAIL_LIMITS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_LIMITS) +# include +#else // defined(ASIO_HAS_BOOST_LIMITS) +# include +#endif // defined(ASIO_HAS_BOOST_LIMITS) + +#endif // ASIO_DETAIL_LIMITS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/local_free_on_block_exit.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/local_free_on_block_exit.hpp new file mode 100644 index 00000000..2b601b96 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/local_free_on_block_exit.hpp @@ -0,0 +1,59 @@ +// +// detail/local_free_on_block_exit.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_LOCAL_FREE_ON_BLOCK_EXIT_HPP +#define ASIO_DETAIL_LOCAL_FREE_ON_BLOCK_EXIT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +#if !defined(ASIO_WINDOWS_APP) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class local_free_on_block_exit + : private noncopyable +{ +public: + // Constructor blocks all signals for the calling thread. + explicit local_free_on_block_exit(void* p) + : p_(p) + { + } + + // Destructor restores the previous signal mask. + ~local_free_on_block_exit() + { + ::LocalFree(p_); + } + +private: + void* p_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS_APP) +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#endif // ASIO_DETAIL_LOCAL_FREE_ON_BLOCK_EXIT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/macos_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/macos_fenced_block.hpp new file mode 100644 index 00000000..f123384b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/macos_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/macos_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_MACOS_FENCED_BLOCK_HPP +#define ASIO_DETAIL_MACOS_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__MACH__) && defined(__APPLE__) + +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class macos_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit macos_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit macos_fenced_block(full_t) + { + OSMemoryBarrier(); + } + + // Destructor. + ~macos_fenced_block() + { + OSMemoryBarrier(); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__MACH__) && defined(__APPLE__) + +#endif // ASIO_DETAIL_MACOS_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/memory.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/memory.hpp new file mode 100644 index 00000000..a11ceb9b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/memory.hpp @@ -0,0 +1,70 @@ +// +// detail/memory.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_MEMORY_HPP +#define ASIO_DETAIL_MEMORY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +#if !defined(ASIO_HAS_STD_SHARED_PTR) +# include +# include +#endif // !defined(ASIO_HAS_STD_SHARED_PTR) + +#if !defined(ASIO_HAS_STD_ADDRESSOF) +# include +#endif // !defined(ASIO_HAS_STD_ADDRESSOF) + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_STD_SHARED_PTR) +using std::shared_ptr; +using std::weak_ptr; +#else // defined(ASIO_HAS_STD_SHARED_PTR) +using boost::shared_ptr; +using boost::weak_ptr; +#endif // defined(ASIO_HAS_STD_SHARED_PTR) + +#if defined(ASIO_HAS_STD_ADDRESSOF) +using std::addressof; +#else // defined(ASIO_HAS_STD_ADDRESSOF) +using boost::addressof; +#endif // defined(ASIO_HAS_STD_ADDRESSOF) + +} // namespace detail + +#if defined(ASIO_HAS_CXX11_ALLOCATORS) +using std::allocator_arg_t; +# define ASIO_USES_ALLOCATOR(t) \ + namespace std { \ + template \ + struct uses_allocator : true_type {}; \ + } \ + /**/ +# define ASIO_REBIND_ALLOC(alloc, t) \ + typename std::allocator_traits::template rebind_alloc + /**/ +#else // defined(ASIO_HAS_CXX11_ALLOCATORS) +struct allocator_arg_t {}; +# define ASIO_USES_ALLOCATOR(t) +# define ASIO_REBIND_ALLOC(alloc, t) \ + typename alloc::template rebind::other + /**/ +#endif // defined(ASIO_HAS_CXX11_ALLOCATORS) + +} // namespace asio + +#endif // ASIO_DETAIL_MEMORY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/mutex.hpp new file mode 100644 index 00000000..4e01cca2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/mutex.hpp @@ -0,0 +1,48 @@ +// +// detail/mutex.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_MUTEX_HPP +#define ASIO_DETAIL_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_mutex.hpp" +#elif defined(ASIO_WINDOWS) +# include "asio/detail/win_mutex.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_mutex.hpp" +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +# include "asio/detail/std_mutex.hpp" +#else +# error Only Windows, POSIX and std::mutex are supported! +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) +typedef null_mutex mutex; +#elif defined(ASIO_WINDOWS) +typedef win_mutex mutex; +#elif defined(ASIO_HAS_PTHREADS) +typedef posix_mutex mutex; +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +typedef std_mutex mutex; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/non_const_lvalue.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/non_const_lvalue.hpp new file mode 100644 index 00000000..6d9afc88 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/non_const_lvalue.hpp @@ -0,0 +1,54 @@ +// +// detail/non_const_lvalue.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NON_CONST_LVALUE_HPP +#define ASIO_DETAIL_NON_CONST_LVALUE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct non_const_lvalue +{ +#if defined(ASIO_HAS_MOVE) + explicit non_const_lvalue(T& t) + : value(static_cast::type>::value, + typename decay::type&, T&&>::type>(t)) + { + } + + typename conditional::type>::value, + typename decay::type&, typename decay::type>::type value; +#else // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + explicit non_const_lvalue(const typename decay::type& t) + : value(t) + { + } + + typename decay::type value; +#endif // defined(ASIO_HAS_MOVE) +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_NON_CONST_LVALUE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/noncopyable.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/noncopyable.hpp new file mode 100644 index 00000000..2266e671 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/noncopyable.hpp @@ -0,0 +1,43 @@ +// +// detail/noncopyable.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NONCOPYABLE_HPP +#define ASIO_DETAIL_NONCOPYABLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class noncopyable +{ +protected: + noncopyable() {} + ~noncopyable() {} +private: + noncopyable(const noncopyable&); + const noncopyable& operator=(const noncopyable&); +}; + +} // namespace detail + +using asio::detail::noncopyable; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_NONCOPYABLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_event.hpp new file mode 100644 index 00000000..507de948 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_event.hpp @@ -0,0 +1,100 @@ +// +// detail/null_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_EVENT_HPP +#define ASIO_DETAIL_NULL_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_event + : private noncopyable +{ +public: + // Constructor. + null_event() + { + } + + // Destructor. + ~null_event() + { + } + + // Signal the event. (Retained for backward compatibility.) + template + void signal(Lock&) + { + } + + // Signal all waiters. + template + void signal_all(Lock&) + { + } + + // Unlock the mutex and signal one waiter. + template + void unlock_and_signal_one(Lock&) + { + } + + // If there's a waiter, unlock the mutex and signal it. + template + bool maybe_unlock_and_signal_one(Lock&) + { + return false; + } + + // Reset the event. + template + void clear(Lock&) + { + } + + // Wait for the event to become signalled. + template + void wait(Lock&) + { + do_wait(); + } + + // Timed wait for the event to become signalled. + template + bool wait_for_usec(Lock&, long usec) + { + do_wait_for_usec(usec); + return true; + } + +private: + ASIO_DECL static void do_wait(); + ASIO_DECL static void do_wait_for_usec(long usec); +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/null_event.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_NULL_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_fenced_block.hpp new file mode 100644 index 00000000..b136ea37 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_fenced_block.hpp @@ -0,0 +1,47 @@ +// +// detail/null_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_FENCED_BLOCK_HPP +#define ASIO_DETAIL_NULL_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_fenced_block + : private noncopyable +{ +public: + enum half_or_full_t { half, full }; + + // Constructor. + explicit null_fenced_block(half_or_full_t) + { + } + + // Destructor. + ~null_fenced_block() + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_NULL_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_global.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_global.hpp new file mode 100644 index 00000000..1d70bea3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_global.hpp @@ -0,0 +1,59 @@ +// +// detail/null_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_GLOBAL_HPP +#define ASIO_DETAIL_NULL_GLOBAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct null_global_impl +{ + null_global_impl() + : ptr_(0) + { + } + + // Destructor automatically cleans up the global. + ~null_global_impl() + { + delete ptr_; + } + + static null_global_impl instance_; + T* ptr_; +}; + +template +null_global_impl null_global_impl::instance_; + +template +T& null_global() +{ + if (null_global_impl::instance_.ptr_ == 0) + null_global_impl::instance_.ptr_ = new T; + return *null_global_impl::instance_.ptr_; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_NULL_GLOBAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_mutex.hpp new file mode 100644 index 00000000..8f9666b6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_mutex.hpp @@ -0,0 +1,64 @@ +// +// detail/null_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_MUTEX_HPP +#define ASIO_DETAIL_NULL_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_mutex + : private noncopyable +{ +public: + typedef asio::detail::scoped_lock scoped_lock; + + // Constructor. + null_mutex() + { + } + + // Destructor. + ~null_mutex() + { + } + + // Lock the mutex. + void lock() + { + } + + // Unlock the mutex. + void unlock() + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_THREADS) + +#endif // ASIO_DETAIL_NULL_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_reactor.hpp new file mode 100644 index 00000000..07b2b96e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_reactor.hpp @@ -0,0 +1,68 @@ +// +// detail/null_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_REACTOR_HPP +#define ASIO_DETAIL_NULL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) || defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/scheduler_operation.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_reactor + : public execution_context_service_base +{ +public: + // Constructor. + null_reactor(asio::execution_context& ctx) + : execution_context_service_base(ctx) + { + } + + // Destructor. + ~null_reactor() + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + } + + // No-op because should never be called. + void run(long /*usec*/, op_queue& /*ops*/) + { + } + + // No-op. + void interrupt() + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) || defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_NULL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_signal_blocker.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_signal_blocker.hpp new file mode 100644 index 00000000..f2f2ff2b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_signal_blocker.hpp @@ -0,0 +1,69 @@ +// +// detail/null_signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_SIGNAL_BLOCKER_HPP +#define ASIO_DETAIL_NULL_SIGNAL_BLOCKER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) \ + || defined(ASIO_WINDOWS) \ + || defined(ASIO_WINDOWS_RUNTIME) \ + || defined(__CYGWIN__) \ + || defined(__SYMBIAN32__) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_signal_blocker + : private noncopyable +{ +public: + // Constructor blocks all signals for the calling thread. + null_signal_blocker() + { + } + + // Destructor restores the previous signal mask. + ~null_signal_blocker() + { + } + + // Block all signals for the calling thread. + void block() + { + } + + // Restore the previous signal mask. + void unblock() + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_THREADS) + // || defined(ASIO_WINDOWS) + // || defined(ASIO_WINDOWS_RUNTIME) + // || defined(__CYGWIN__) + // || defined(__SYMBIAN32__) + +#endif // ASIO_DETAIL_NULL_SIGNAL_BLOCKER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_socket_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_socket_service.hpp new file mode 100644 index 00000000..752819f8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_socket_service.hpp @@ -0,0 +1,519 @@ +// +// detail/null_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_SOCKET_SERVICE_HPP +#define ASIO_DETAIL_NULL_SOCKET_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/buffer.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/post.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/bind_handler.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class null_socket_service : + public execution_context_service_base > +{ +public: + // The protocol type. + typedef Protocol protocol_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The native type of a socket. + typedef int native_handle_type; + + // The implementation type of the socket. + struct implementation_type + { + }; + + // Constructor. + null_socket_service(execution_context& context) + : execution_context_service_base >(context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + } + + // Construct a new socket implementation. + void construct(implementation_type&) + { + } + + // Move-construct a new socket implementation. + void move_construct(implementation_type&, implementation_type&) + { + } + + // Move-assign from another socket implementation. + void move_assign(implementation_type&, + null_socket_service&, implementation_type&) + { + } + + // Move-construct a new socket implementation from another protocol type. + template + void converting_move_construct(implementation_type&, + null_socket_service&, + typename null_socket_service::implementation_type&) + { + } + + // Destroy a socket implementation. + void destroy(implementation_type&) + { + } + + // Open a new socket implementation. + asio::error_code open(implementation_type&, + const protocol_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Assign a native socket to a socket implementation. + asio::error_code assign(implementation_type&, const protocol_type&, + const native_handle_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Determine whether the socket is open. + bool is_open(const implementation_type&) const + { + return false; + } + + // Destroy a socket implementation. + asio::error_code close(implementation_type&, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Release ownership of the socket. + native_handle_type release(implementation_type&, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Get the native socket representation. + native_handle_type native_handle(implementation_type&) + { + return 0; + } + + // Cancel all operations associated with the socket. + asio::error_code cancel(implementation_type&, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Determine whether the socket is at the out-of-band data mark. + bool at_mark(const implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return false; + } + + // Determine the number of bytes available for reading. + std::size_t available(const implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Place the socket into the state where it will listen for new connections. + asio::error_code listen(implementation_type&, + int, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Perform an IO control command on the socket. + template + asio::error_code io_control(implementation_type&, + IO_Control_Command&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Gets the non-blocking mode of the socket. + bool non_blocking(const implementation_type&) const + { + return false; + } + + // Sets the non-blocking mode of the socket. + asio::error_code non_blocking(implementation_type&, + bool, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const implementation_type&) const + { + return false; + } + + // Sets the non-blocking mode of the native socket implementation. + asio::error_code native_non_blocking(implementation_type&, + bool, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Disable sends or receives on the socket. + asio::error_code shutdown(implementation_type&, + socket_base::shutdown_type, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Bind the socket to the specified local endpoint. + asio::error_code bind(implementation_type&, + const endpoint_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Set a socket option. + template + asio::error_code set_option(implementation_type&, + const Option&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Set a socket option. + template + asio::error_code get_option(const implementation_type&, + Option&, asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Get the local endpoint. + endpoint_type local_endpoint(const implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return endpoint_type(); + } + + // Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return endpoint_type(); + } + + // Send the given data to the peer. + template + std::size_t send(implementation_type&, const ConstBufferSequence&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Wait until data can be sent without blocking. + std::size_t send(implementation_type&, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send(implementation_type&, const ConstBufferSequence&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send(implementation_type&, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Receive some data from the peer. Returns the number of bytes received. + template + std::size_t receive(implementation_type&, const MutableBufferSequence&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Wait until data can be received without blocking. + std::size_t receive(implementation_type&, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive(implementation_type&, const MutableBufferSequence&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Wait until data can be received without blocking. + template + void async_receive(implementation_type&, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Receive some data with associated flags. Returns the number of bytes + // received. + template + std::size_t receive_with_flags(implementation_type&, + const MutableBufferSequence&, socket_base::message_flags, + socket_base::message_flags&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Wait until data can be received without blocking. + std::size_t receive_with_flags(implementation_type&, + const null_buffers&, socket_base::message_flags, + socket_base::message_flags&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive_with_flags(implementation_type&, + const MutableBufferSequence&, socket_base::message_flags, + socket_base::message_flags&, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Wait until data can be received without blocking. + template + void async_receive_with_flags(implementation_type&, const null_buffers&, + socket_base::message_flags, socket_base::message_flags&, + Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Send a datagram to the specified endpoint. Returns the number of bytes + // sent. + template + std::size_t send_to(implementation_type&, const ConstBufferSequence&, + const endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Wait until data can be sent without blocking. + std::size_t send_to(implementation_type&, const null_buffers&, + const endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send_to(implementation_type&, const ConstBufferSequence&, + const endpoint_type&, socket_base::message_flags, + Handler& handler) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send_to(implementation_type&, const null_buffers&, + const endpoint_type&, socket_base::message_flags, + Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Receive a datagram with the endpoint of the sender. Returns the number of + // bytes received. + template + std::size_t receive_from(implementation_type&, const MutableBufferSequence&, + endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Wait until data can be received without blocking. + std::size_t receive_from(implementation_type&, const null_buffers&, + endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received and + // the sender_endpoint object must both be valid for the lifetime of the + // asynchronous operation. + template + void async_receive_from(implementation_type&, const MutableBufferSequence&, + endpoint_type&, socket_base::message_flags, Handler& handler, + const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Wait until data can be received without blocking. + template + void async_receive_from(implementation_type&, const null_buffers&, + endpoint_type&, socket_base::message_flags, Handler& handler, + const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, detail::bind_handler( + handler, ec, bytes_transferred)); + } + + // Accept a new connection. + template + asio::error_code accept(implementation_type&, + Socket&, endpoint_type*, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Start an asynchronous accept. The peer and peer_endpoint objects + // must be valid until the accept's handler is invoked. + template + void async_accept(implementation_type&, Socket&, endpoint_type*, + Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + asio::post(io_ex, detail::bind_handler(handler, ec)); + } + + // Connect the socket to the specified endpoint. + asio::error_code connect(implementation_type&, + const endpoint_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Start an asynchronous connect. + template + void async_connect(implementation_type&, const endpoint_type&, + Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + asio::post(io_ex, detail::bind_handler(handler, ec)); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_NULL_SOCKET_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_static_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_static_mutex.hpp new file mode 100644 index 00000000..231cce38 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_static_mutex.hpp @@ -0,0 +1,60 @@ +// +// detail/null_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_STATIC_MUTEX_HPP +#define ASIO_DETAIL_NULL_STATIC_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) + +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct null_static_mutex +{ + typedef asio::detail::scoped_lock scoped_lock; + + // Initialise the mutex. + void init() + { + } + + // Lock the mutex. + void lock() + { + } + + // Unlock the mutex. + void unlock() + { + } + + int unused_; +}; + +#define ASIO_NULL_STATIC_MUTEX_INIT { 0 } + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_THREADS) + +#endif // ASIO_DETAIL_NULL_STATIC_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_thread.hpp new file mode 100644 index 00000000..3a4e2c0f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_thread.hpp @@ -0,0 +1,67 @@ +// +// detail/null_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_THREAD_HPP +#define ASIO_DETAIL_NULL_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class null_thread + : private noncopyable +{ +public: + // Constructor. + template + null_thread(Function, unsigned int = 0) + { + asio::detail::throw_error( + asio::error::operation_not_supported, "thread"); + } + + // Destructor. + ~null_thread() + { + } + + // Wait for the thread to exit. + void join() + { + } + + // Get number of CPUs. + static std::size_t hardware_concurrency() + { + return 1; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_THREADS) + +#endif // ASIO_DETAIL_NULL_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_tss_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_tss_ptr.hpp new file mode 100644 index 00000000..9257c3c9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/null_tss_ptr.hpp @@ -0,0 +1,68 @@ +// +// detail/null_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_NULL_TSS_PTR_HPP +#define ASIO_DETAIL_NULL_TSS_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class null_tss_ptr + : private noncopyable +{ +public: + // Constructor. + null_tss_ptr() + : value_(0) + { + } + + // Destructor. + ~null_tss_ptr() + { + } + + // Get the value. + operator T*() const + { + return value_; + } + + // Set the value. + void operator=(T* value) + { + value_ = value; + } + +private: + T* value_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_THREADS) + +#endif // ASIO_DETAIL_NULL_TSS_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/object_pool.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/object_pool.hpp new file mode 100644 index 00000000..3fc9cafd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/object_pool.hpp @@ -0,0 +1,171 @@ +// +// detail/object_pool.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_OBJECT_POOL_HPP +#define ASIO_DETAIL_OBJECT_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class object_pool; + +class object_pool_access +{ +public: + template + static Object* create() + { + return new Object; + } + + template + static Object* create(Arg arg) + { + return new Object(arg); + } + + template + static void destroy(Object* o) + { + delete o; + } + + template + static Object*& next(Object* o) + { + return o->next_; + } + + template + static Object*& prev(Object* o) + { + return o->prev_; + } +}; + +template +class object_pool + : private noncopyable +{ +public: + // Constructor. + object_pool() + : live_list_(0), + free_list_(0) + { + } + + // Destructor destroys all objects. + ~object_pool() + { + destroy_list(live_list_); + destroy_list(free_list_); + } + + // Get the object at the start of the live list. + Object* first() + { + return live_list_; + } + + // Allocate a new object. + Object* alloc() + { + Object* o = free_list_; + if (o) + free_list_ = object_pool_access::next(free_list_); + else + o = object_pool_access::create(); + + object_pool_access::next(o) = live_list_; + object_pool_access::prev(o) = 0; + if (live_list_) + object_pool_access::prev(live_list_) = o; + live_list_ = o; + + return o; + } + + // Allocate a new object with an argument. + template + Object* alloc(Arg arg) + { + Object* o = free_list_; + if (o) + free_list_ = object_pool_access::next(free_list_); + else + o = object_pool_access::create(arg); + + object_pool_access::next(o) = live_list_; + object_pool_access::prev(o) = 0; + if (live_list_) + object_pool_access::prev(live_list_) = o; + live_list_ = o; + + return o; + } + + // Free an object. Moves it to the free list. No destructors are run. + void free(Object* o) + { + if (live_list_ == o) + live_list_ = object_pool_access::next(o); + + if (object_pool_access::prev(o)) + { + object_pool_access::next(object_pool_access::prev(o)) + = object_pool_access::next(o); + } + + if (object_pool_access::next(o)) + { + object_pool_access::prev(object_pool_access::next(o)) + = object_pool_access::prev(o); + } + + object_pool_access::next(o) = free_list_; + object_pool_access::prev(o) = 0; + free_list_ = o; + } + +private: + // Helper function to destroy all elements in a list. + void destroy_list(Object* list) + { + while (list) + { + Object* o = list; + list = object_pool_access::next(o); + object_pool_access::destroy(o); + } + } + + // The list of live objects. + Object* live_list_; + + // The free list. + Object* free_list_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_OBJECT_POOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/old_win_sdk_compat.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/old_win_sdk_compat.hpp new file mode 100644 index 00000000..b0cd2cb1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/old_win_sdk_compat.hpp @@ -0,0 +1,214 @@ +// +// detail/old_win_sdk_compat.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_OLD_WIN_SDK_COMPAT_HPP +#define ASIO_DETAIL_OLD_WIN_SDK_COMPAT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +// Guess whether we are building against on old Platform SDK. +#if !defined(IN6ADDR_ANY_INIT) +#define ASIO_HAS_OLD_WIN_SDK 1 +#endif // !defined(IN6ADDR_ANY_INIT) + +#if defined(ASIO_HAS_OLD_WIN_SDK) + +// Emulation of types that are missing from old Platform SDKs. +// +// N.B. this emulation is also used if building for a Windows 2000 target with +// a recent (i.e. Vista or later) SDK, as the SDK does not provide IPv6 support +// in that case. + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +enum +{ + sockaddr_storage_maxsize = 128, // Maximum size. + sockaddr_storage_alignsize = (sizeof(__int64)), // Desired alignment. + sockaddr_storage_pad1size = (sockaddr_storage_alignsize - sizeof(short)), + sockaddr_storage_pad2size = (sockaddr_storage_maxsize - + (sizeof(short) + sockaddr_storage_pad1size + sockaddr_storage_alignsize)) +}; + +struct sockaddr_storage_emulation +{ + short ss_family; + char __ss_pad1[sockaddr_storage_pad1size]; + __int64 __ss_align; + char __ss_pad2[sockaddr_storage_pad2size]; +}; + +struct in6_addr_emulation +{ + union + { + u_char Byte[16]; + u_short Word[8]; + } u; +}; + +#if !defined(s6_addr) +# define _S6_un u +# define _S6_u8 Byte +# define s6_addr _S6_un._S6_u8 +#endif // !defined(s6_addr) + +struct sockaddr_in6_emulation +{ + short sin6_family; + u_short sin6_port; + u_long sin6_flowinfo; + in6_addr_emulation sin6_addr; + u_long sin6_scope_id; +}; + +struct ipv6_mreq_emulation +{ + in6_addr_emulation ipv6mr_multiaddr; + unsigned int ipv6mr_interface; +}; + +struct addrinfo_emulation +{ + int ai_flags; + int ai_family; + int ai_socktype; + int ai_protocol; + size_t ai_addrlen; + char* ai_canonname; + sockaddr* ai_addr; + addrinfo_emulation* ai_next; +}; + +#if !defined(AI_PASSIVE) +# define AI_PASSIVE 0x1 +#endif + +#if !defined(AI_CANONNAME) +# define AI_CANONNAME 0x2 +#endif + +#if !defined(AI_NUMERICHOST) +# define AI_NUMERICHOST 0x4 +#endif + +#if !defined(EAI_AGAIN) +# define EAI_AGAIN WSATRY_AGAIN +#endif + +#if !defined(EAI_BADFLAGS) +# define EAI_BADFLAGS WSAEINVAL +#endif + +#if !defined(EAI_FAIL) +# define EAI_FAIL WSANO_RECOVERY +#endif + +#if !defined(EAI_FAMILY) +# define EAI_FAMILY WSAEAFNOSUPPORT +#endif + +#if !defined(EAI_MEMORY) +# define EAI_MEMORY WSA_NOT_ENOUGH_MEMORY +#endif + +#if !defined(EAI_NODATA) +# define EAI_NODATA WSANO_DATA +#endif + +#if !defined(EAI_NONAME) +# define EAI_NONAME WSAHOST_NOT_FOUND +#endif + +#if !defined(EAI_SERVICE) +# define EAI_SERVICE WSATYPE_NOT_FOUND +#endif + +#if !defined(EAI_SOCKTYPE) +# define EAI_SOCKTYPE WSAESOCKTNOSUPPORT +#endif + +#if !defined(NI_NOFQDN) +# define NI_NOFQDN 0x01 +#endif + +#if !defined(NI_NUMERICHOST) +# define NI_NUMERICHOST 0x02 +#endif + +#if !defined(NI_NAMEREQD) +# define NI_NAMEREQD 0x04 +#endif + +#if !defined(NI_NUMERICSERV) +# define NI_NUMERICSERV 0x08 +#endif + +#if !defined(NI_DGRAM) +# define NI_DGRAM 0x10 +#endif + +#if !defined(IPPROTO_IPV6) +# define IPPROTO_IPV6 41 +#endif + +#if !defined(IPV6_UNICAST_HOPS) +# define IPV6_UNICAST_HOPS 4 +#endif + +#if !defined(IPV6_MULTICAST_IF) +# define IPV6_MULTICAST_IF 9 +#endif + +#if !defined(IPV6_MULTICAST_HOPS) +# define IPV6_MULTICAST_HOPS 10 +#endif + +#if !defined(IPV6_MULTICAST_LOOP) +# define IPV6_MULTICAST_LOOP 11 +#endif + +#if !defined(IPV6_JOIN_GROUP) +# define IPV6_JOIN_GROUP 12 +#endif + +#if !defined(IPV6_LEAVE_GROUP) +# define IPV6_LEAVE_GROUP 13 +#endif + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_OLD_WIN_SDK) + +// Even newer Platform SDKs that support IPv6 may not define IPV6_V6ONLY. +#if !defined(IPV6_V6ONLY) +# define IPV6_V6ONLY 27 +#endif + +// Some SDKs (e.g. Windows CE) don't define IPPROTO_ICMPV6. +#if !defined(IPPROTO_ICMPV6) +# define IPPROTO_ICMPV6 58 +#endif + +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#endif // ASIO_DETAIL_OLD_WIN_SDK_COMPAT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/op_queue.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/op_queue.hpp new file mode 100644 index 00000000..de059ebe --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/op_queue.hpp @@ -0,0 +1,162 @@ +// +// detail/op_queue.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_OP_QUEUE_HPP +#define ASIO_DETAIL_OP_QUEUE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class op_queue; + +class op_queue_access +{ +public: + template + static Operation* next(Operation* o) + { + return static_cast(o->next_); + } + + template + static void next(Operation1*& o1, Operation2* o2) + { + o1->next_ = o2; + } + + template + static void destroy(Operation* o) + { + o->destroy(); + } + + template + static Operation*& front(op_queue& q) + { + return q.front_; + } + + template + static Operation*& back(op_queue& q) + { + return q.back_; + } +}; + +template +class op_queue + : private noncopyable +{ +public: + // Constructor. + op_queue() + : front_(0), + back_(0) + { + } + + // Destructor destroys all operations. + ~op_queue() + { + while (Operation* op = front_) + { + pop(); + op_queue_access::destroy(op); + } + } + + // Get the operation at the front of the queue. + Operation* front() + { + return front_; + } + + // Pop an operation from the front of the queue. + void pop() + { + if (front_) + { + Operation* tmp = front_; + front_ = op_queue_access::next(front_); + if (front_ == 0) + back_ = 0; + op_queue_access::next(tmp, static_cast(0)); + } + } + + // Push an operation on to the back of the queue. + void push(Operation* h) + { + op_queue_access::next(h, static_cast(0)); + if (back_) + { + op_queue_access::next(back_, h); + back_ = h; + } + else + { + front_ = back_ = h; + } + } + + // Push all operations from another queue on to the back of the queue. The + // source queue may contain operations of a derived type. + template + void push(op_queue& q) + { + if (Operation* other_front = op_queue_access::front(q)) + { + if (back_) + op_queue_access::next(back_, other_front); + else + front_ = other_front; + back_ = op_queue_access::back(q); + op_queue_access::front(q) = 0; + op_queue_access::back(q) = 0; + } + } + + // Whether the queue is empty. + bool empty() const + { + return front_ == 0; + } + + // Test whether an operation is already enqueued. + bool is_enqueued(Operation* o) const + { + return op_queue_access::next(o) != 0 || back_ == o; + } + +private: + friend class op_queue_access; + + // The front of the queue. + Operation* front_; + + // The back of the queue. + Operation* back_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_OP_QUEUE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/operation.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/operation.hpp new file mode 100644 index 00000000..aa4064b8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/operation.hpp @@ -0,0 +1,38 @@ +// +// detail/operation.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_OPERATION_HPP +#define ASIO_DETAIL_OPERATION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_operation.hpp" +#else +# include "asio/detail/scheduler_operation.hpp" +#endif + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_IOCP) +typedef win_iocp_operation operation; +#else +typedef scheduler_operation operation; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_OPERATION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pipe_select_interrupter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pipe_select_interrupter.hpp new file mode 100644 index 00000000..40173ba1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pipe_select_interrupter.hpp @@ -0,0 +1,89 @@ +// +// detail/pipe_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP +#define ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) +#if !defined(ASIO_WINDOWS_RUNTIME) +#if !defined(__CYGWIN__) +#if !defined(__SYMBIAN32__) +#if !defined(ASIO_HAS_EVENTFD) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class pipe_select_interrupter +{ +public: + // Constructor. + ASIO_DECL pipe_select_interrupter(); + + // Destructor. + ASIO_DECL ~pipe_select_interrupter(); + + // Recreate the interrupter's descriptors. Used after a fork. + ASIO_DECL void recreate(); + + // Interrupt the select call. + ASIO_DECL void interrupt(); + + // Reset the select interrupt. Returns true if the call was interrupted. + ASIO_DECL bool reset(); + + // Get the read descriptor to be passed to select. + int read_descriptor() const + { + return read_descriptor_; + } + +private: + // Open the descriptors. Throws on error. + ASIO_DECL void open_descriptors(); + + // Close the descriptors. + ASIO_DECL void close_descriptors(); + + // The read end of a connection used to interrupt the select call. This file + // descriptor is passed to select such that when it is time to stop, a single + // byte will be written on the other end of the connection and this + // descriptor will become readable. + int read_descriptor_; + + // The write end of a connection used to interrupt the select call. A single + // byte may be written to this to wake up the select which is waiting for the + // other end to become readable. + int write_descriptor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/pipe_select_interrupter.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // !defined(ASIO_HAS_EVENTFD) +#endif // !defined(__SYMBIAN32__) +#endif // !defined(__CYGWIN__) +#endif // !defined(ASIO_WINDOWS_RUNTIME) +#endif // !defined(ASIO_WINDOWS) + +#endif // ASIO_DETAIL_PIPE_SELECT_INTERRUPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pop_options.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pop_options.hpp new file mode 100644 index 00000000..7df258d4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/pop_options.hpp @@ -0,0 +1,141 @@ +// +// detail/pop_options.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +// No header guard + +#if defined(__COMO__) + +// Comeau C++ + +#elif defined(__DMC__) + +// Digital Mars C++ + +#elif defined(__INTEL_COMPILER) || defined(__ICL) \ + || defined(__ICC) || defined(__ECC) + +// Intel C++ + +# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility pop +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) + +#elif defined(__clang__) + +// Clang + +# if defined(__OBJC__) +# if !defined(__APPLE_CC__) || (__APPLE_CC__ <= 1) +# if defined(ASIO_OBJC_WORKAROUND) +# undef Protocol +# undef id +# undef ASIO_OBJC_WORKAROUND +# endif +# endif +# endif + +# if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility pop +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) + +#elif defined(__GNUC__) + +// GNU C++ + +# if defined(__MINGW32__) || defined(__CYGWIN__) +# pragma pack (pop) +# endif + +# if defined(__OBJC__) +# if !defined(__APPLE_CC__) || (__APPLE_CC__ <= 1) +# if defined(ASIO_OBJC_WORKAROUND) +# undef Protocol +# undef id +# undef ASIO_OBJC_WORKAROUND +# endif +# endif +# endif + +# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility pop +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) + +# if (__GNUC__ >= 7) +# pragma GCC diagnostic pop +# endif // (__GNUC__ >= 7) + +#elif defined(__KCC) + +// Kai C++ + +#elif defined(__sgi) + +// SGI MIPSpro C++ + +#elif defined(__DECCXX) + +// Compaq Tru64 Unix cxx + +#elif defined(__ghs) + +// Greenhills C++ + +#elif defined(__BORLANDC__) + +// Borland C++ + +# pragma option pop +# pragma nopushoptwarn +# pragma nopackwarning + +#elif defined(__MWERKS__) + +// Metrowerks CodeWarrior + +#elif defined(__SUNPRO_CC) + +// Sun Workshop Compiler C++ + +#elif defined(__HP_aCC) + +// HP aCC + +#elif defined(__MRC__) || defined(__SC__) + +// MPW MrCpp or SCpp + +#elif defined(__IBMCPP__) + +// IBM Visual Age + +#elif defined(_MSC_VER) + +// Microsoft Visual C++ +// +// Must remain the last #elif since some other vendors (Metrowerks, for example) +// also #define _MSC_VER + +# pragma warning (pop) +# pragma pack (pop) + +# if defined(__cplusplus_cli) || defined(__cplusplus_winrt) +# if defined(ASIO_CLR_WORKAROUND) +# undef generic +# undef ASIO_CLR_WORKAROUND +# endif +# endif + +#endif diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_event.hpp new file mode 100644 index 00000000..ea4132e5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_event.hpp @@ -0,0 +1,162 @@ +// +// detail/posix_event.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_EVENT_HPP +#define ASIO_DETAIL_POSIX_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include "asio/detail/assert.hpp" +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class posix_event + : private noncopyable +{ +public: + // Constructor. + ASIO_DECL posix_event(); + + // Destructor. + ~posix_event() + { + ::pthread_cond_destroy(&cond_); + } + + // Signal the event. (Retained for backward compatibility.) + template + void signal(Lock& lock) + { + this->signal_all(lock); + } + + // Signal all waiters. + template + void signal_all(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + state_ |= 1; + ::pthread_cond_broadcast(&cond_); // Ignore EINVAL. + } + + // Unlock the mutex and signal one waiter. + template + void unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + bool have_waiters = (state_ > 1); + lock.unlock(); + if (have_waiters) + ::pthread_cond_signal(&cond_); // Ignore EINVAL. + } + + // If there's a waiter, unlock the mutex and signal it. + template + bool maybe_unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + if (state_ > 1) + { + lock.unlock(); + ::pthread_cond_signal(&cond_); // Ignore EINVAL. + return true; + } + return false; + } + + // Reset the event. + template + void clear(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + state_ &= ~std::size_t(1); + } + + // Wait for the event to become signalled. + template + void wait(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + while ((state_ & 1) == 0) + { + state_ += 2; + ::pthread_cond_wait(&cond_, &lock.mutex().mutex_); // Ignore EINVAL. + state_ -= 2; + } + } + + // Timed wait for the event to become signalled. + template + bool wait_for_usec(Lock& lock, long usec) + { + ASIO_ASSERT(lock.locked()); + if ((state_ & 1) == 0) + { + state_ += 2; + timespec ts; +#if (defined(__MACH__) && defined(__APPLE__)) \ + || (defined(__ANDROID__) && (__ANDROID_API__ < 21) \ + && defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)) + ts.tv_sec = usec / 1000000; + ts.tv_nsec = (usec % 1000000) * 1000; + ::pthread_cond_timedwait_relative_np( + &cond_, &lock.mutex().mutex_, &ts); // Ignore EINVAL. +#else // (defined(__MACH__) && defined(__APPLE__)) + // || (defined(__ANDROID__) && (__ANDROID_API__ < 21) + // && defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)) + if (::clock_gettime(CLOCK_MONOTONIC, &ts) == 0) + { + ts.tv_sec += usec / 1000000; + ts.tv_nsec += (usec % 1000000) * 1000; + ts.tv_sec += ts.tv_nsec / 1000000000; + ts.tv_nsec = ts.tv_nsec % 1000000000; + ::pthread_cond_timedwait(&cond_, + &lock.mutex().mutex_, &ts); // Ignore EINVAL. + } +#endif // (defined(__MACH__) && defined(__APPLE__)) + // || (defined(__ANDROID__) && (__ANDROID_API__ < 21) + // && defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)) + state_ -= 2; + } + return (state_ & 1) != 0; + } + +private: + ::pthread_cond_t cond_; + std::size_t state_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/posix_event.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_fd_set_adapter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_fd_set_adapter.hpp new file mode 100644 index 00000000..6ce97c0d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_fd_set_adapter.hpp @@ -0,0 +1,118 @@ +// +// detail/posix_fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_FD_SET_ADAPTER_HPP +#define ASIO_DETAIL_POSIX_FD_SET_ADAPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) \ + && !defined(__CYGWIN__) \ + && !defined(ASIO_WINDOWS_RUNTIME) + +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/reactor_op_queue.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Adapts the FD_SET type to meet the Descriptor_Set concept's requirements. +class posix_fd_set_adapter : noncopyable +{ +public: + posix_fd_set_adapter() + : max_descriptor_(invalid_socket) + { + using namespace std; // Needed for memset on Solaris. + FD_ZERO(&fd_set_); + } + + void reset() + { + using namespace std; // Needed for memset on Solaris. + FD_ZERO(&fd_set_); + } + + bool set(socket_type descriptor) + { + if (descriptor < (socket_type)FD_SETSIZE) + { + if (max_descriptor_ == invalid_socket || descriptor > max_descriptor_) + max_descriptor_ = descriptor; + FD_SET(descriptor, &fd_set_); + return true; + } + return false; + } + + void set(reactor_op_queue& operations, op_queue& ops) + { + reactor_op_queue::iterator i = operations.begin(); + while (i != operations.end()) + { + reactor_op_queue::iterator op_iter = i++; + if (!set(op_iter->first)) + { + asio::error_code ec(error::fd_set_failure); + operations.cancel_operations(op_iter, ops, ec); + } + } + } + + bool is_set(socket_type descriptor) const + { + return FD_ISSET(descriptor, &fd_set_) != 0; + } + + operator fd_set*() + { + return &fd_set_; + } + + socket_type max_descriptor() const + { + return max_descriptor_; + } + + void perform(reactor_op_queue& operations, + op_queue& ops) const + { + reactor_op_queue::iterator i = operations.begin(); + while (i != operations.end()) + { + reactor_op_queue::iterator op_iter = i++; + if (is_set(op_iter->first)) + operations.perform_operations(op_iter, ops); + } + } + +private: + mutable fd_set fd_set_; + socket_type max_descriptor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS) + // && !defined(__CYGWIN__) + // && !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_POSIX_FD_SET_ADAPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_global.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_global.hpp new file mode 100644 index 00000000..352eb228 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_global.hpp @@ -0,0 +1,80 @@ +// +// detail/posix_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_GLOBAL_HPP +#define ASIO_DETAIL_POSIX_GLOBAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct posix_global_impl +{ + // Helper function to perform initialisation. + static void do_init() + { + instance_.static_ptr_ = instance_.ptr_ = new T; + } + + // Destructor automatically cleans up the global. + ~posix_global_impl() + { + delete static_ptr_; + } + + static ::pthread_once_t init_once_; + static T* static_ptr_; + static posix_global_impl instance_; + T* ptr_; +}; + +template +::pthread_once_t posix_global_impl::init_once_ = PTHREAD_ONCE_INIT; + +template +T* posix_global_impl::static_ptr_ = 0; + +template +posix_global_impl posix_global_impl::instance_; + +template +T& posix_global() +{ + int result = ::pthread_once( + &posix_global_impl::init_once_, + &posix_global_impl::do_init); + + if (result != 0) + std::terminate(); + + return *posix_global_impl::instance_.ptr_; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_GLOBAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_mutex.hpp new file mode 100644 index 00000000..9849408d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_mutex.hpp @@ -0,0 +1,76 @@ +// +// detail/posix_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_MUTEX_HPP +#define ASIO_DETAIL_POSIX_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class posix_event; + +class posix_mutex + : private noncopyable +{ +public: + typedef asio::detail::scoped_lock scoped_lock; + + // Constructor. + ASIO_DECL posix_mutex(); + + // Destructor. + ~posix_mutex() + { + ::pthread_mutex_destroy(&mutex_); // Ignore EBUSY. + } + + // Lock the mutex. + void lock() + { + (void)::pthread_mutex_lock(&mutex_); // Ignore EINVAL. + } + + // Unlock the mutex. + void unlock() + { + (void)::pthread_mutex_unlock(&mutex_); // Ignore EINVAL. + } + +private: + friend class posix_event; + ::pthread_mutex_t mutex_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/posix_mutex.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_signal_blocker.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_signal_blocker.hpp new file mode 100644 index 00000000..6a947639 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_signal_blocker.hpp @@ -0,0 +1,85 @@ +// +// detail/posix_signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP +#define ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class posix_signal_blocker + : private noncopyable +{ +public: + // Constructor blocks all signals for the calling thread. + posix_signal_blocker() + : blocked_(false) + { + sigset_t new_mask; + sigfillset(&new_mask); + blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0); + } + + // Destructor restores the previous signal mask. + ~posix_signal_blocker() + { + if (blocked_) + pthread_sigmask(SIG_SETMASK, &old_mask_, 0); + } + + // Block all signals for the calling thread. + void block() + { + if (!blocked_) + { + sigset_t new_mask; + sigfillset(&new_mask); + blocked_ = (pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask_) == 0); + } + } + + // Restore the previous signal mask. + void unblock() + { + if (blocked_) + blocked_ = (pthread_sigmask(SIG_SETMASK, &old_mask_, 0) != 0); + } + +private: + // Have signals been blocked. + bool blocked_; + + // The previous signal mask. + sigset_t old_mask_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_SIGNAL_BLOCKER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_static_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_static_mutex.hpp new file mode 100644 index 00000000..7ac67ad9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_static_mutex.hpp @@ -0,0 +1,64 @@ +// +// detail/posix_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP +#define ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct posix_static_mutex +{ + typedef asio::detail::scoped_lock scoped_lock; + + // Initialise the mutex. + void init() + { + // Nothing to do. + } + + // Lock the mutex. + void lock() + { + (void)::pthread_mutex_lock(&mutex_); // Ignore EINVAL. + } + + // Unlock the mutex. + void unlock() + { + (void)::pthread_mutex_unlock(&mutex_); // Ignore EINVAL. + } + + ::pthread_mutex_t mutex_; +}; + +#define ASIO_POSIX_STATIC_MUTEX_INIT { PTHREAD_MUTEX_INITIALIZER } + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_STATIC_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_thread.hpp new file mode 100644 index 00000000..02d01b3a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_thread.hpp @@ -0,0 +1,109 @@ +// +// detail/posix_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_THREAD_HPP +#define ASIO_DETAIL_POSIX_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +extern "C" +{ + ASIO_DECL void* asio_detail_posix_thread_function(void* arg); +} + +class posix_thread + : private noncopyable +{ +public: + // Constructor. + template + posix_thread(Function f, unsigned int = 0) + : joined_(false) + { + start_thread(new func(f)); + } + + // Destructor. + ASIO_DECL ~posix_thread(); + + // Wait for the thread to exit. + ASIO_DECL void join(); + + // Get number of CPUs. + ASIO_DECL static std::size_t hardware_concurrency(); + +private: + friend void* asio_detail_posix_thread_function(void* arg); + + class func_base + { + public: + virtual ~func_base() {} + virtual void run() = 0; + }; + + struct auto_func_base_ptr + { + func_base* ptr; + ~auto_func_base_ptr() { delete ptr; } + }; + + template + class func + : public func_base + { + public: + func(Function f) + : f_(f) + { + } + + virtual void run() + { + f_(); + } + + private: + Function f_; + }; + + ASIO_DECL void start_thread(func_base* arg); + + ::pthread_t thread_; + bool joined_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/posix_thread.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_tss_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_tss_ptr.hpp new file mode 100644 index 00000000..f760c59c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/posix_tss_ptr.hpp @@ -0,0 +1,79 @@ +// +// detail/posix_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_POSIX_TSS_PTR_HPP +#define ASIO_DETAIL_POSIX_TSS_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_PTHREADS) + +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper function to create thread-specific storage. +ASIO_DECL void posix_tss_ptr_create(pthread_key_t& key); + +template +class posix_tss_ptr + : private noncopyable +{ +public: + // Constructor. + posix_tss_ptr() + { + posix_tss_ptr_create(tss_key_); + } + + // Destructor. + ~posix_tss_ptr() + { + ::pthread_key_delete(tss_key_); + } + + // Get the value. + operator T*() const + { + return static_cast(::pthread_getspecific(tss_key_)); + } + + // Set the value. + void operator=(T* value) + { + ::pthread_setspecific(tss_key_, value); + } + +private: + // Thread-specific storage to allow unlocked access to determine whether a + // thread is a member of the pool. + pthread_key_t tss_key_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/posix_tss_ptr.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_PTHREADS) + +#endif // ASIO_DETAIL_POSIX_TSS_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/push_options.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/push_options.hpp new file mode 100644 index 00000000..fa8725d4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/push_options.hpp @@ -0,0 +1,181 @@ +// +// detail/push_options.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +// No header guard + +#if defined(__COMO__) + +// Comeau C++ + +#elif defined(__DMC__) + +// Digital Mars C++ + +#elif defined(__INTEL_COMPILER) || defined(__ICL) \ + || defined(__ICC) || defined(__ECC) + +// Intel C++ + +# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility push (default) +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) + +#elif defined(__clang__) + +// Clang + +# if defined(__OBJC__) +# if !defined(__APPLE_CC__) || (__APPLE_CC__ <= 1) +# if !defined(ASIO_DISABLE_OBJC_WORKAROUND) +# if !defined(Protocol) && !defined(id) +# define Protocol cpp_Protocol +# define id cpp_id +# define ASIO_OBJC_WORKAROUND +# endif +# endif +# endif +# endif + +# if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility push (default) +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) + +#elif defined(__GNUC__) + +// GNU C++ + +# if defined(__MINGW32__) || defined(__CYGWIN__) +# pragma pack (push, 8) +# endif + +# if defined(__OBJC__) +# if !defined(__APPLE_CC__) || (__APPLE_CC__ <= 1) +# if !defined(ASIO_DISABLE_OBJC_WORKAROUND) +# if !defined(Protocol) && !defined(id) +# define Protocol cpp_Protocol +# define id cpp_id +# define ASIO_OBJC_WORKAROUND +# endif +# endif +# endif +# endif + +# if (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) +# if !defined(ASIO_DISABLE_VISIBILITY) +# pragma GCC visibility push (default) +# endif // !defined(ASIO_DISABLE_VISIBILITY) +# endif // (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) || (__GNUC__ > 4) + +# if (__GNUC__ >= 7) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wimplicit-fallthrough" +# endif // (__GNUC__ >= 7) + +#elif defined(__KCC) + +// Kai C++ + +#elif defined(__sgi) + +// SGI MIPSpro C++ + +#elif defined(__DECCXX) + +// Compaq Tru64 Unix cxx + +#elif defined(__ghs) + +// Greenhills C++ + +#elif defined(__BORLANDC__) + +// Borland C++ + +# pragma option push -a8 -b -Ve- -Vx- -w-inl -vi- +# pragma nopushoptwarn +# pragma nopackwarning +# if !defined(__MT__) +# error Multithreaded RTL must be selected. +# endif // !defined(__MT__) + +#elif defined(__MWERKS__) + +// Metrowerks CodeWarrior + +#elif defined(__SUNPRO_CC) + +// Sun Workshop Compiler C++ + +#elif defined(__HP_aCC) + +// HP aCC + +#elif defined(__MRC__) || defined(__SC__) + +// MPW MrCpp or SCpp + +#elif defined(__IBMCPP__) + +// IBM Visual Age + +#elif defined(_MSC_VER) + +// Microsoft Visual C++ +// +// Must remain the last #elif since some other vendors (Metrowerks, for example) +// also #define _MSC_VER + +# pragma warning (disable:4103) +# pragma warning (push) +# pragma warning (disable:4127) +# pragma warning (disable:4180) +# pragma warning (disable:4244) +# pragma warning (disable:4355) +# pragma warning (disable:4510) +# pragma warning (disable:4512) +# pragma warning (disable:4610) +# pragma warning (disable:4675) +# if (_MSC_VER < 1600) +// Visual Studio 2008 generates spurious warnings about unused parameters. +# pragma warning (disable:4100) +# endif // (_MSC_VER < 1600) +# if defined(_M_IX86) && defined(_Wp64) +// The /Wp64 option is broken. If you want to check 64 bit portability, use a +// 64 bit compiler! +# pragma warning (disable:4311) +# pragma warning (disable:4312) +# endif // defined(_M_IX86) && defined(_Wp64) +# pragma pack (push, 8) +// Note that if the /Og optimisation flag is enabled with MSVC6, the compiler +// has a tendency to incorrectly optimise away some calls to member template +// functions, even though those functions contain code that should not be +// optimised away! Therefore we will always disable this optimisation option +// for the MSVC6 compiler. +# if (_MSC_VER < 1300) +# pragma optimize ("g", off) +# endif +# if !defined(_MT) +# error Multithreaded RTL must be selected. +# endif // !defined(_MT) + +# if defined(__cplusplus_cli) || defined(__cplusplus_winrt) +# if !defined(ASIO_DISABLE_CLR_WORKAROUND) +# if !defined(generic) +# define generic cpp_generic +# define ASIO_CLR_WORKAROUND +# endif +# endif +# endif + +#endif diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_descriptor_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_descriptor_service.hpp new file mode 100644 index 00000000..7894dc7a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_descriptor_service.hpp @@ -0,0 +1,391 @@ +// +// detail/reactive_descriptor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP +#define ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) + +#include "asio/buffer.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/descriptor_ops.hpp" +#include "asio/detail/descriptor_read_op.hpp" +#include "asio/detail/descriptor_write_op.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/reactive_null_buffers_op.hpp" +#include "asio/detail/reactive_wait_op.hpp" +#include "asio/detail/reactor.hpp" +#include "asio/posix/descriptor_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class reactive_descriptor_service : + public execution_context_service_base +{ +public: + // The native type of a descriptor. + typedef int native_handle_type; + + // The implementation type of the descriptor. + class implementation_type + : private asio::detail::noncopyable + { + public: + // Default constructor. + implementation_type() + : descriptor_(-1), + state_(0) + { + } + + private: + // Only this service will have access to the internal values. + friend class reactive_descriptor_service; + + // The native descriptor representation. + int descriptor_; + + // The current state of the descriptor. + descriptor_ops::state_type state_; + + // Per-descriptor data used by the reactor. + reactor::per_descriptor_data reactor_data_; + }; + + // Constructor. + ASIO_DECL reactive_descriptor_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new descriptor implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Move-construct a new descriptor implementation. + ASIO_DECL void move_construct(implementation_type& impl, + implementation_type& other_impl); + + // Move-assign from another descriptor implementation. + ASIO_DECL void move_assign(implementation_type& impl, + reactive_descriptor_service& other_service, + implementation_type& other_impl); + + // Destroy a descriptor implementation. + ASIO_DECL void destroy(implementation_type& impl); + + // Assign a native descriptor to a descriptor implementation. + ASIO_DECL asio::error_code assign(implementation_type& impl, + const native_handle_type& native_descriptor, + asio::error_code& ec); + + // Determine whether the descriptor is open. + bool is_open(const implementation_type& impl) const + { + return impl.descriptor_ != -1; + } + + // Destroy a descriptor implementation. + ASIO_DECL asio::error_code close(implementation_type& impl, + asio::error_code& ec); + + // Get the native descriptor representation. + native_handle_type native_handle(const implementation_type& impl) const + { + return impl.descriptor_; + } + + // Release ownership of the native descriptor representation. + ASIO_DECL native_handle_type release(implementation_type& impl); + + // Cancel all operations associated with the descriptor. + ASIO_DECL asio::error_code cancel(implementation_type& impl, + asio::error_code& ec); + + // Perform an IO control command on the descriptor. + template + asio::error_code io_control(implementation_type& impl, + IO_Control_Command& command, asio::error_code& ec) + { + descriptor_ops::ioctl(impl.descriptor_, impl.state_, + command.name(), static_cast(command.data()), ec); + return ec; + } + + // Gets the non-blocking mode of the descriptor. + bool non_blocking(const implementation_type& impl) const + { + return (impl.state_ & descriptor_ops::user_set_non_blocking) != 0; + } + + // Sets the non-blocking mode of the descriptor. + asio::error_code non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + descriptor_ops::set_user_non_blocking( + impl.descriptor_, impl.state_, mode, ec); + return ec; + } + + // Gets the non-blocking mode of the native descriptor implementation. + bool native_non_blocking(const implementation_type& impl) const + { + return (impl.state_ & descriptor_ops::internal_non_blocking) != 0; + } + + // Sets the non-blocking mode of the native descriptor implementation. + asio::error_code native_non_blocking(implementation_type& impl, + bool mode, asio::error_code& ec) + { + descriptor_ops::set_internal_non_blocking( + impl.descriptor_, impl.state_, mode, ec); + return ec; + } + + // Wait for the descriptor to become ready to read, ready to write, or to have + // pending error conditions. + asio::error_code wait(implementation_type& impl, + posix::descriptor_base::wait_type w, asio::error_code& ec) + { + switch (w) + { + case posix::descriptor_base::wait_read: + descriptor_ops::poll_read(impl.descriptor_, impl.state_, ec); + break; + case posix::descriptor_base::wait_write: + descriptor_ops::poll_write(impl.descriptor_, impl.state_, ec); + break; + case posix::descriptor_base::wait_error: + descriptor_ops::poll_error(impl.descriptor_, impl.state_, ec); + break; + default: + ec = asio::error::invalid_argument; + break; + } + + return ec; + } + + // Asynchronously wait for the descriptor to become ready to read, ready to + // write, or to have pending error conditions. + template + void async_wait(implementation_type& impl, + posix::descriptor_base::wait_type w, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_wait_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "descriptor", + &impl, impl.descriptor_, "async_wait")); + + int op_type; + switch (w) + { + case posix::descriptor_base::wait_read: + op_type = reactor::read_op; + break; + case posix::descriptor_base::wait_write: + op_type = reactor::write_op; + break; + case posix::descriptor_base::wait_error: + op_type = reactor::except_op; + break; + default: + p.p->ec_ = asio::error::invalid_argument; + reactor_.post_immediate_completion(p.p, is_continuation); + p.v = p.p = 0; + return; + } + + start_op(impl, op_type, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Write some data to the descriptor. + template + size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return descriptor_ops::sync_write(impl.descriptor_, impl.state_, + bufs.buffers(), bufs.count(), bufs.all_empty(), ec); + } + + // Wait until data can be written without blocking. + size_t write_some(implementation_type& impl, + const null_buffers&, asio::error_code& ec) + { + // Wait for descriptor to become ready. + descriptor_ops::poll_write(impl.descriptor_, impl.state_, ec); + + return 0; + } + + // Start an asynchronous write. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, Handler& handler, + const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef descriptor_write_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.descriptor_, buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "descriptor", + &impl, impl.descriptor_, "async_write_some")); + + start_op(impl, reactor::write_op, p.p, is_continuation, true, + buffer_sequence_adapter::all_empty(buffers)); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be written without blocking. + template + void async_write_some(implementation_type& impl, + const null_buffers&, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "descriptor", + &impl, impl.descriptor_, "async_write_some(null_buffers)")); + + start_op(impl, reactor::write_op, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Read some data from the stream. Returns the number of bytes read. + template + size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return descriptor_ops::sync_read(impl.descriptor_, impl.state_, + bufs.buffers(), bufs.count(), bufs.all_empty(), ec); + } + + // Wait until data can be read without blocking. + size_t read_some(implementation_type& impl, + const null_buffers&, asio::error_code& ec) + { + // Wait for descriptor to become ready. + descriptor_ops::poll_read(impl.descriptor_, impl.state_, ec); + + return 0; + } + + // Start an asynchronous read. The buffer for the data being read must be + // valid for the lifetime of the asynchronous operation. + template + void async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef descriptor_read_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.descriptor_, buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "descriptor", + &impl, impl.descriptor_, "async_read_some")); + + start_op(impl, reactor::read_op, p.p, is_continuation, true, + buffer_sequence_adapter::all_empty(buffers)); + p.v = p.p = 0; + } + + // Wait until data can be read without blocking. + template + void async_read_some(implementation_type& impl, + const null_buffers&, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "descriptor", + &impl, impl.descriptor_, "async_read_some(null_buffers)")); + + start_op(impl, reactor::read_op, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + +private: + // Start the asynchronous operation. + ASIO_DECL void start_op(implementation_type& impl, int op_type, + reactor_op* op, bool is_continuation, bool is_non_blocking, bool noop); + + // The selector that performs event demultiplexing for the service. + reactor& reactor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/reactive_descriptor_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) + +#endif // ASIO_DETAIL_REACTIVE_DESCRIPTOR_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_null_buffers_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_null_buffers_op.hpp new file mode 100644 index 00000000..9013f576 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_null_buffers_op.hpp @@ -0,0 +1,92 @@ +// +// detail/reactive_null_buffers_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP +#define ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_null_buffers_op : public reactor_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_null_buffers_op); + + reactive_null_buffers_op(Handler& handler, const IoExecutor& io_ex) + : reactor_op(&reactive_null_buffers_op::do_perform, + &reactive_null_buffers_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static status do_perform(reactor_op*) + { + return done; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_null_buffers_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_serial_port_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_serial_port_service.hpp new file mode 100644 index 00000000..10d80738 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_serial_port_service.hpp @@ -0,0 +1,238 @@ +// +// detail/reactive_serial_port_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP +#define ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_SERIAL_PORT) +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/serial_port_base.hpp" +#include "asio/detail/descriptor_ops.hpp" +#include "asio/detail/reactive_descriptor_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Extend reactive_descriptor_service to provide serial port support. +class reactive_serial_port_service : + public execution_context_service_base +{ +public: + // The native type of a serial port. + typedef reactive_descriptor_service::native_handle_type native_handle_type; + + // The implementation type of the serial port. + typedef reactive_descriptor_service::implementation_type implementation_type; + + ASIO_DECL reactive_serial_port_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new serial port implementation. + void construct(implementation_type& impl) + { + descriptor_service_.construct(impl); + } + + // Move-construct a new serial port implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + descriptor_service_.move_construct(impl, other_impl); + } + + // Move-assign from another serial port implementation. + void move_assign(implementation_type& impl, + reactive_serial_port_service& other_service, + implementation_type& other_impl) + { + descriptor_service_.move_assign(impl, + other_service.descriptor_service_, other_impl); + } + + // Destroy a serial port implementation. + void destroy(implementation_type& impl) + { + descriptor_service_.destroy(impl); + } + + // Open the serial port using the specified device name. + ASIO_DECL asio::error_code open(implementation_type& impl, + const std::string& device, asio::error_code& ec); + + // Assign a native descriptor to a serial port implementation. + asio::error_code assign(implementation_type& impl, + const native_handle_type& native_descriptor, + asio::error_code& ec) + { + return descriptor_service_.assign(impl, native_descriptor, ec); + } + + // Determine whether the serial port is open. + bool is_open(const implementation_type& impl) const + { + return descriptor_service_.is_open(impl); + } + + // Destroy a serial port implementation. + asio::error_code close(implementation_type& impl, + asio::error_code& ec) + { + return descriptor_service_.close(impl, ec); + } + + // Get the native serial port representation. + native_handle_type native_handle(implementation_type& impl) + { + return descriptor_service_.native_handle(impl); + } + + // Cancel all operations associated with the serial port. + asio::error_code cancel(implementation_type& impl, + asio::error_code& ec) + { + return descriptor_service_.cancel(impl, ec); + } + + // Set an option on the serial port. + template + asio::error_code set_option(implementation_type& impl, + const SettableSerialPortOption& option, asio::error_code& ec) + { + return do_set_option(impl, + &reactive_serial_port_service::store_option, + &option, ec); + } + + // Get an option from the serial port. + template + asio::error_code get_option(const implementation_type& impl, + GettableSerialPortOption& option, asio::error_code& ec) const + { + return do_get_option(impl, + &reactive_serial_port_service::load_option, + &option, ec); + } + + // Send a break sequence to the serial port. + asio::error_code send_break(implementation_type& impl, + asio::error_code& ec) + { + errno = 0; + descriptor_ops::error_wrapper(::tcsendbreak( + descriptor_service_.native_handle(impl), 0), ec); + return ec; + } + + // Write the given data. Returns the number of bytes sent. + template + size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return descriptor_service_.write_some(impl, buffers, ec); + } + + // Start an asynchronous write. The data being written must be valid for the + // lifetime of the asynchronous operation. + template + void async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + descriptor_service_.async_write_some(impl, buffers, handler, io_ex); + } + + // Read some data. Returns the number of bytes received. + template + size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return descriptor_service_.read_some(impl, buffers, ec); + } + + // Start an asynchronous read. The buffer for the data being received must be + // valid for the lifetime of the asynchronous operation. + template + void async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + descriptor_service_.async_read_some(impl, buffers, handler, io_ex); + } + +private: + // Function pointer type for storing a serial port option. + typedef asio::error_code (*store_function_type)( + const void*, termios&, asio::error_code&); + + // Helper function template to store a serial port option. + template + static asio::error_code store_option(const void* option, + termios& storage, asio::error_code& ec) + { + static_cast(option)->store(storage, ec); + return ec; + } + + // Helper function to set a serial port option. + ASIO_DECL asio::error_code do_set_option( + implementation_type& impl, store_function_type store, + const void* option, asio::error_code& ec); + + // Function pointer type for loading a serial port option. + typedef asio::error_code (*load_function_type)( + void*, const termios&, asio::error_code&); + + // Helper function template to load a serial port option. + template + static asio::error_code load_option(void* option, + const termios& storage, asio::error_code& ec) + { + static_cast(option)->load(storage, ec); + return ec; + } + + // Helper function to get a serial port option. + ASIO_DECL asio::error_code do_get_option( + const implementation_type& impl, load_function_type load, + void* option, asio::error_code& ec) const; + + // The implementation used for initiating asynchronous operations. + reactive_descriptor_service descriptor_service_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/reactive_serial_port_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) +#endif // defined(ASIO_HAS_SERIAL_PORT) + +#endif // ASIO_DETAIL_REACTIVE_SERIAL_PORT_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_accept_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_accept_op.hpp new file mode 100644 index 00000000..e4e5fd77 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_accept_op.hpp @@ -0,0 +1,230 @@ +// +// detail/reactive_socket_accept_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_holder.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_accept_op_base : public reactor_op +{ +public: + reactive_socket_accept_op_base(socket_type socket, + socket_ops::state_type state, Socket& peer, const Protocol& protocol, + typename Protocol::endpoint* peer_endpoint, func_type complete_func) + : reactor_op(&reactive_socket_accept_op_base::do_perform, complete_func), + socket_(socket), + state_(state), + peer_(peer), + protocol_(protocol), + peer_endpoint_(peer_endpoint), + addrlen_(peer_endpoint ? peer_endpoint->capacity() : 0) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_accept_op_base* o( + static_cast(base)); + + socket_type new_socket = invalid_socket; + status result = socket_ops::non_blocking_accept(o->socket_, + o->state_, o->peer_endpoint_ ? o->peer_endpoint_->data() : 0, + o->peer_endpoint_ ? &o->addrlen_ : 0, o->ec_, new_socket) + ? done : not_done; + o->new_socket_.reset(new_socket); + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_accept", o->ec_)); + + return result; + } + + void do_assign() + { + if (new_socket_.get() != invalid_socket) + { + if (peer_endpoint_) + peer_endpoint_->resize(addrlen_); + peer_.assign(protocol_, new_socket_.get(), ec_); + if (!ec_) + new_socket_.release(); + } + } + +private: + socket_type socket_; + socket_ops::state_type state_; + socket_holder new_socket_; + Socket& peer_; + Protocol protocol_; + typename Protocol::endpoint* peer_endpoint_; + std::size_t addrlen_; +}; + +template +class reactive_socket_accept_op : + public reactive_socket_accept_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_accept_op); + + reactive_socket_accept_op(socket_type socket, + socket_ops::state_type state, Socket& peer, const Protocol& protocol, + typename Protocol::endpoint* peer_endpoint, Handler& handler, + const IoExecutor& io_ex) + : reactive_socket_accept_op_base(socket, state, peer, + protocol, peer_endpoint, &reactive_socket_accept_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_accept_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + // On success, assign new connection to peer socket object. + if (owner) + o->do_assign(); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, o->ec_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +#if defined(ASIO_HAS_MOVE) + +template +class reactive_socket_move_accept_op : + private Protocol::socket::template rebind_executor::other, + public reactive_socket_accept_op_base< + typename Protocol::socket::template rebind_executor::other, + Protocol> +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_move_accept_op); + + reactive_socket_move_accept_op(const PeerIoExecutor& peer_io_ex, + socket_type socket, socket_ops::state_type state, + const Protocol& protocol, typename Protocol::endpoint* peer_endpoint, + Handler& handler, const IoExecutor& io_ex) + : peer_socket_type(peer_io_ex), + reactive_socket_accept_op_base( + socket, state, *this, protocol, peer_endpoint, + &reactive_socket_move_accept_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_move_accept_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + // On success, assign new connection to peer socket object. + if (owner) + o->do_assign(); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::move_binder2 + handler(0, ASIO_MOVE_CAST(Handler)(o->handler_), o->ec_, + ASIO_MOVE_CAST(peer_socket_type)(*o)); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + typedef typename Protocol::socket::template + rebind_executor::other peer_socket_type; + + Handler handler_; + IoExecutor io_executor_; +}; + +#endif // defined(ASIO_HAS_MOVE) + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_connect_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_connect_op.hpp new file mode 100644 index 00000000..59c0fdc5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_connect_op.hpp @@ -0,0 +1,116 @@ +// +// detail/reactive_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_CONNECT_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_CONNECT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class reactive_socket_connect_op_base : public reactor_op +{ +public: + reactive_socket_connect_op_base(socket_type socket, func_type complete_func) + : reactor_op(&reactive_socket_connect_op_base::do_perform, complete_func), + socket_(socket) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_connect_op_base* o( + static_cast(base)); + + status result = socket_ops::non_blocking_connect( + o->socket_, o->ec_) ? done : not_done; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_connect", o->ec_)); + + return result; + } + +private: + socket_type socket_; +}; + +template +class reactive_socket_connect_op : public reactive_socket_connect_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_connect_op); + + reactive_socket_connect_op(socket_type socket, + Handler& handler, const IoExecutor& io_ex) + : reactive_socket_connect_op_base(socket, + &reactive_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_connect_op* o + (static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, o->ec_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_CONNECT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recv_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recv_op.hpp new file mode 100644 index 00000000..02e566ee --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recv_op.hpp @@ -0,0 +1,137 @@ +// +// detail/reactive_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_RECV_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_RECV_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_recv_op_base : public reactor_op +{ +public: + reactive_socket_recv_op_base(socket_type socket, + socket_ops::state_type state, const MutableBufferSequence& buffers, + socket_base::message_flags flags, func_type complete_func) + : reactor_op(&reactive_socket_recv_op_base::do_perform, complete_func), + socket_(socket), + state_(state), + buffers_(buffers), + flags_(flags) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_recv_op_base* o( + static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = socket_ops::non_blocking_recv(o->socket_, + bufs.buffers(), bufs.count(), o->flags_, + (o->state_ & socket_ops::stream_oriented) != 0, + o->ec_, o->bytes_transferred_) ? done : not_done; + + if (result == done) + if ((o->state_ & socket_ops::stream_oriented) != 0) + if (o->bytes_transferred_ == 0) + result = done_and_exhausted; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_recv", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + socket_type socket_; + socket_ops::state_type state_; + MutableBufferSequence buffers_; + socket_base::message_flags flags_; +}; + +template +class reactive_socket_recv_op : + public reactive_socket_recv_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_recv_op); + + reactive_socket_recv_op(socket_type socket, socket_ops::state_type state, + const MutableBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + : reactive_socket_recv_op_base(socket, state, + buffers, flags, &reactive_socket_recv_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_recv_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECV_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvfrom_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvfrom_op.hpp new file mode 100644 index 00000000..2e584681 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvfrom_op.hpp @@ -0,0 +1,142 @@ +// +// detail/reactive_socket_recvfrom_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_RECVFROM_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_RECVFROM_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_recvfrom_op_base : public reactor_op +{ +public: + reactive_socket_recvfrom_op_base(socket_type socket, int protocol_type, + const MutableBufferSequence& buffers, Endpoint& endpoint, + socket_base::message_flags flags, func_type complete_func) + : reactor_op(&reactive_socket_recvfrom_op_base::do_perform, complete_func), + socket_(socket), + protocol_type_(protocol_type), + buffers_(buffers), + sender_endpoint_(endpoint), + flags_(flags) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_recvfrom_op_base* o( + static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + std::size_t addr_len = o->sender_endpoint_.capacity(); + status result = socket_ops::non_blocking_recvfrom(o->socket_, + bufs.buffers(), bufs.count(), o->flags_, + o->sender_endpoint_.data(), &addr_len, + o->ec_, o->bytes_transferred_) ? done : not_done; + + if (result && !o->ec_) + o->sender_endpoint_.resize(addr_len); + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_recvfrom", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + socket_type socket_; + int protocol_type_; + MutableBufferSequence buffers_; + Endpoint& sender_endpoint_; + socket_base::message_flags flags_; +}; + +template +class reactive_socket_recvfrom_op : + public reactive_socket_recvfrom_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_recvfrom_op); + + reactive_socket_recvfrom_op(socket_type socket, int protocol_type, + const MutableBufferSequence& buffers, Endpoint& endpoint, + socket_base::message_flags flags, Handler& handler, + const IoExecutor& io_ex) + : reactive_socket_recvfrom_op_base( + socket, protocol_type, buffers, endpoint, flags, + &reactive_socket_recvfrom_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_recvfrom_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECVFROM_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvmsg_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvmsg_op.hpp new file mode 100644 index 00000000..0a703b3b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_recvmsg_op.hpp @@ -0,0 +1,135 @@ +// +// detail/reactive_socket_recvmsg_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/socket_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_recvmsg_op_base : public reactor_op +{ +public: + reactive_socket_recvmsg_op_base(socket_type socket, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, func_type complete_func) + : reactor_op(&reactive_socket_recvmsg_op_base::do_perform, complete_func), + socket_(socket), + buffers_(buffers), + in_flags_(in_flags), + out_flags_(out_flags) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_recvmsg_op_base* o( + static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = socket_ops::non_blocking_recvmsg(o->socket_, + bufs.buffers(), bufs.count(), + o->in_flags_, o->out_flags_, + o->ec_, o->bytes_transferred_) ? done : not_done; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_recvmsg", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + socket_type socket_; + MutableBufferSequence buffers_; + socket_base::message_flags in_flags_; + socket_base::message_flags& out_flags_; +}; + +template +class reactive_socket_recvmsg_op : + public reactive_socket_recvmsg_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_recvmsg_op); + + reactive_socket_recvmsg_op(socket_type socket, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, Handler& handler, + const IoExecutor& io_ex) + : reactive_socket_recvmsg_op_base(socket, buffers, + in_flags, out_flags, &reactive_socket_recvmsg_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_recvmsg_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_RECVMSG_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_send_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_send_op.hpp new file mode 100644 index 00000000..4eab8165 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_send_op.hpp @@ -0,0 +1,136 @@ +// +// detail/reactive_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_send_op_base : public reactor_op +{ +public: + reactive_socket_send_op_base(socket_type socket, + socket_ops::state_type state, const ConstBufferSequence& buffers, + socket_base::message_flags flags, func_type complete_func) + : reactor_op(&reactive_socket_send_op_base::do_perform, complete_func), + socket_(socket), + state_(state), + buffers_(buffers), + flags_(flags) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_send_op_base* o( + static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = socket_ops::non_blocking_send(o->socket_, + bufs.buffers(), bufs.count(), o->flags_, + o->ec_, o->bytes_transferred_) ? done : not_done; + + if (result == done) + if ((o->state_ & socket_ops::stream_oriented) != 0) + if (o->bytes_transferred_ < bufs.total_size()) + result = done_and_exhausted; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_send", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + socket_type socket_; + socket_ops::state_type state_; + ConstBufferSequence buffers_; + socket_base::message_flags flags_; +}; + +template +class reactive_socket_send_op : + public reactive_socket_send_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_send_op); + + reactive_socket_send_op(socket_type socket, socket_ops::state_type state, + const ConstBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + : reactive_socket_send_op_base(socket, + state, buffers, flags, &reactive_socket_send_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_send_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SEND_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_sendto_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_sendto_op.hpp new file mode 100644 index 00000000..55fd1c81 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_sendto_op.hpp @@ -0,0 +1,134 @@ +// +// detail/reactive_socket_sendto_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_SENDTO_OP_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_SENDTO_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_sendto_op_base : public reactor_op +{ +public: + reactive_socket_sendto_op_base(socket_type socket, + const ConstBufferSequence& buffers, const Endpoint& endpoint, + socket_base::message_flags flags, func_type complete_func) + : reactor_op(&reactive_socket_sendto_op_base::do_perform, complete_func), + socket_(socket), + buffers_(buffers), + destination_(endpoint), + flags_(flags) + { + } + + static status do_perform(reactor_op* base) + { + reactive_socket_sendto_op_base* o( + static_cast(base)); + + buffer_sequence_adapter bufs(o->buffers_); + + status result = socket_ops::non_blocking_sendto(o->socket_, + bufs.buffers(), bufs.count(), o->flags_, + o->destination_.data(), o->destination_.size(), + o->ec_, o->bytes_transferred_) ? done : not_done; + + ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_sendto", + o->ec_, o->bytes_transferred_)); + + return result; + } + +private: + socket_type socket_; + ConstBufferSequence buffers_; + Endpoint destination_; + socket_base::message_flags flags_; +}; + +template +class reactive_socket_sendto_op : + public reactive_socket_sendto_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_socket_sendto_op); + + reactive_socket_sendto_op(socket_type socket, + const ConstBufferSequence& buffers, const Endpoint& endpoint, + socket_base::message_flags flags, Handler& handler, + const IoExecutor& io_ex) + : reactive_socket_sendto_op_base(socket, + buffers, endpoint, flags, &reactive_socket_sendto_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_socket_sendto_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->bytes_transferred_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SENDTO_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service.hpp new file mode 100644 index 00000000..52029674 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service.hpp @@ -0,0 +1,505 @@ +// +// detail/reactive_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_IOCP) + +#include "asio/buffer.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/reactive_null_buffers_op.hpp" +#include "asio/detail/reactive_socket_accept_op.hpp" +#include "asio/detail/reactive_socket_connect_op.hpp" +#include "asio/detail/reactive_socket_recvfrom_op.hpp" +#include "asio/detail/reactive_socket_sendto_op.hpp" +#include "asio/detail/reactive_socket_service_base.hpp" +#include "asio/detail/reactor.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_holder.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_socket_service : + public execution_context_service_base >, + public reactive_socket_service_base +{ +public: + // The protocol type. + typedef Protocol protocol_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The native type of a socket. + typedef socket_type native_handle_type; + + // The implementation type of the socket. + struct implementation_type : + reactive_socket_service_base::base_implementation_type + { + // Default constructor. + implementation_type() + : protocol_(endpoint_type().protocol()) + { + } + + // The protocol associated with the socket. + protocol_type protocol_; + }; + + // Constructor. + reactive_socket_service(execution_context& context) + : execution_context_service_base< + reactive_socket_service >(context), + reactive_socket_service_base(context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + this->base_shutdown(); + } + + // Move-construct a new socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) ASIO_NOEXCEPT + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + } + + // Move-assign from another socket implementation. + void move_assign(implementation_type& impl, + reactive_socket_service_base& other_service, + implementation_type& other_impl) + { + this->base_move_assign(impl, other_service, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + } + + // Move-construct a new socket implementation from another protocol type. + template + void converting_move_construct(implementation_type& impl, + reactive_socket_service&, + typename reactive_socket_service< + Protocol1>::implementation_type& other_impl) + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = protocol_type(other_impl.protocol_); + other_impl.protocol_ = typename Protocol1::endpoint().protocol(); + } + + // Open a new socket implementation. + asio::error_code open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (!do_open(impl, protocol.family(), + protocol.type(), protocol.protocol(), ec)) + impl.protocol_ = protocol; + return ec; + } + + // Assign a native socket to a socket implementation. + asio::error_code assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + if (!do_assign(impl, protocol.type(), native_socket, ec)) + impl.protocol_ = protocol; + return ec; + } + + // Get the native socket representation. + native_handle_type native_handle(implementation_type& impl) + { + return impl.socket_; + } + + // Bind the socket to the specified local endpoint. + asio::error_code bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec); + return ec; + } + + // Set a socket option. + template + asio::error_code set_option(implementation_type& impl, + const Option& option, asio::error_code& ec) + { + socket_ops::setsockopt(impl.socket_, impl.state_, + option.level(impl.protocol_), option.name(impl.protocol_), + option.data(impl.protocol_), option.size(impl.protocol_), ec); + return ec; + } + + // Set a socket option. + template + asio::error_code get_option(const implementation_type& impl, + Option& option, asio::error_code& ec) const + { + std::size_t size = option.size(impl.protocol_); + socket_ops::getsockopt(impl.socket_, impl.state_, + option.level(impl.protocol_), option.name(impl.protocol_), + option.data(impl.protocol_), &size, ec); + if (!ec) + option.resize(impl.protocol_, size); + return ec; + } + + // Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint; + std::size_t addr_len = endpoint.capacity(); + if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec)) + return endpoint_type(); + endpoint.resize(addr_len); + return endpoint; + } + + // Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint; + std::size_t addr_len = endpoint.capacity(); + if (socket_ops::getpeername(impl.socket_, + endpoint.data(), &addr_len, false, ec)) + return endpoint_type(); + endpoint.resize(addr_len); + return endpoint; + } + + // Disable sends or receives on the socket. + asio::error_code shutdown(base_implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + socket_ops::shutdown(impl.socket_, what, ec); + return ec; + } + + // Send a datagram to the specified endpoint. Returns the number of bytes + // sent. + template + size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_sendto(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, + destination.data(), destination.size(), ec); + } + + // Wait until data can be sent without blocking. + size_t send_to(implementation_type& impl, const null_buffers&, + const endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send_to(implementation_type& impl, + const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_sendto_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, buffers, + destination, flags, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_send_to")); + + start_op(impl, reactor::write_op, p.p, is_continuation, true, false); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send_to(implementation_type& impl, const null_buffers&, + const endpoint_type&, socket_base::message_flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_send_to(null_buffers)")); + + start_op(impl, reactor::write_op, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Receive a datagram with the endpoint of the sender. Returns the number of + // bytes received. + template + size_t receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + std::size_t addr_len = sender_endpoint.capacity(); + std::size_t bytes_recvd = socket_ops::sync_recvfrom( + impl.socket_, impl.state_, bufs.buffers(), bufs.count(), + flags, sender_endpoint.data(), &addr_len, ec); + + if (!ec) + sender_endpoint.resize(addr_len); + + return bytes_recvd; + } + + // Wait until data can be received without blocking. + size_t receive_from(implementation_type& impl, const null_buffers&, + endpoint_type& sender_endpoint, socket_base::message_flags, + asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + // Reset endpoint since it can be given no sensible value at this time. + sender_endpoint = endpoint_type(); + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received and + // the sender_endpoint object must both be valid for the lifetime of the + // asynchronous operation. + template + void async_receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, + socket_base::message_flags flags, Handler& handler, + const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_recvfrom_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + int protocol = impl.protocol_.type(); + p.p = new (p.v) op(impl.socket_, protocol, buffers, + sender_endpoint, flags, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive_from")); + + start_op(impl, + (flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, true, false); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive_from(implementation_type& impl, const null_buffers&, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive_from(null_buffers)")); + + // Reset endpoint since it can be given no sensible value at this time. + sender_endpoint = endpoint_type(); + + start_op(impl, + (flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Accept a new connection. + template + asio::error_code accept(implementation_type& impl, + Socket& peer, endpoint_type* peer_endpoint, asio::error_code& ec) + { + // We cannot accept a socket that is already open. + if (peer.is_open()) + { + ec = asio::error::already_open; + return ec; + } + + std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0; + socket_holder new_socket(socket_ops::sync_accept(impl.socket_, + impl.state_, peer_endpoint ? peer_endpoint->data() : 0, + peer_endpoint ? &addr_len : 0, ec)); + + // On success, assign new connection to peer socket object. + if (new_socket.get() != invalid_socket) + { + if (peer_endpoint) + peer_endpoint->resize(addr_len); + peer.assign(impl.protocol_, new_socket.get(), ec); + if (!ec) + new_socket.release(); + } + + return ec; + } + + // Start an asynchronous accept. The peer and peer_endpoint objects must be + // valid until the accept's handler is invoked. + template + void async_accept(implementation_type& impl, Socket& peer, + endpoint_type* peer_endpoint, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_accept_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, impl.state_, peer, + impl.protocol_, peer_endpoint, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_accept")); + + start_accept_op(impl, p.p, is_continuation, peer.is_open()); + p.v = p.p = 0; + } + +#if defined(ASIO_HAS_MOVE) + // Start an asynchronous accept. The peer_endpoint object must be valid until + // the accept's handler is invoked. + template + void async_move_accept(implementation_type& impl, + const PeerIoExecutor& peer_io_ex, endpoint_type* peer_endpoint, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_move_accept_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(peer_io_ex, impl.socket_, impl.state_, + impl.protocol_, peer_endpoint, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_accept")); + + start_accept_op(impl, p.p, is_continuation, false); + p.v = p.p = 0; + } +#endif // defined(ASIO_HAS_MOVE) + + // Connect the socket to the specified endpoint. + asio::error_code connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + socket_ops::sync_connect(impl.socket_, + peer_endpoint.data(), peer_endpoint.size(), ec); + return ec; + } + + // Start an asynchronous connect. + template + void async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_connect_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_connect")); + + start_connect_op(impl, p.p, is_continuation, + peer_endpoint.data(), peer_endpoint.size()); + p.v = p.p = 0; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service_base.hpp new file mode 100644 index 00000000..f9683283 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_socket_service_base.hpp @@ -0,0 +1,518 @@ +// +// detail/reactive_socket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_BASE_HPP +#define ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_IOCP) \ + && !defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/buffer.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactive_null_buffers_op.hpp" +#include "asio/detail/reactive_socket_recv_op.hpp" +#include "asio/detail/reactive_socket_recvmsg_op.hpp" +#include "asio/detail/reactive_socket_send_op.hpp" +#include "asio/detail/reactive_wait_op.hpp" +#include "asio/detail/reactor.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_holder.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class reactive_socket_service_base +{ +public: + // The native type of a socket. + typedef socket_type native_handle_type; + + // The implementation type of the socket. + struct base_implementation_type + { + // The native socket representation. + socket_type socket_; + + // The current state of the socket. + socket_ops::state_type state_; + + // Per-descriptor data used by the reactor. + reactor::per_descriptor_data reactor_data_; + }; + + // Constructor. + ASIO_DECL reactive_socket_service_base(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void base_shutdown(); + + // Construct a new socket implementation. + ASIO_DECL void construct(base_implementation_type& impl); + + // Move-construct a new socket implementation. + ASIO_DECL void base_move_construct(base_implementation_type& impl, + base_implementation_type& other_impl) ASIO_NOEXCEPT; + + // Move-assign from another socket implementation. + ASIO_DECL void base_move_assign(base_implementation_type& impl, + reactive_socket_service_base& other_service, + base_implementation_type& other_impl); + + // Destroy a socket implementation. + ASIO_DECL void destroy(base_implementation_type& impl); + + // Determine whether the socket is open. + bool is_open(const base_implementation_type& impl) const + { + return impl.socket_ != invalid_socket; + } + + // Destroy a socket implementation. + ASIO_DECL asio::error_code close( + base_implementation_type& impl, asio::error_code& ec); + + // Release ownership of the socket. + ASIO_DECL socket_type release( + base_implementation_type& impl, asio::error_code& ec); + + // Get the native socket representation. + native_handle_type native_handle(base_implementation_type& impl) + { + return impl.socket_; + } + + // Cancel all operations associated with the socket. + ASIO_DECL asio::error_code cancel( + base_implementation_type& impl, asio::error_code& ec); + + // Determine whether the socket is at the out-of-band data mark. + bool at_mark(const base_implementation_type& impl, + asio::error_code& ec) const + { + return socket_ops::sockatmark(impl.socket_, ec); + } + + // Determine the number of bytes available for reading. + std::size_t available(const base_implementation_type& impl, + asio::error_code& ec) const + { + return socket_ops::available(impl.socket_, ec); + } + + // Place the socket into the state where it will listen for new connections. + asio::error_code listen(base_implementation_type& impl, + int backlog, asio::error_code& ec) + { + socket_ops::listen(impl.socket_, backlog, ec); + return ec; + } + + // Perform an IO control command on the socket. + template + asio::error_code io_control(base_implementation_type& impl, + IO_Control_Command& command, asio::error_code& ec) + { + socket_ops::ioctl(impl.socket_, impl.state_, command.name(), + static_cast(command.data()), ec); + return ec; + } + + // Gets the non-blocking mode of the socket. + bool non_blocking(const base_implementation_type& impl) const + { + return (impl.state_ & socket_ops::user_set_non_blocking) != 0; + } + + // Sets the non-blocking mode of the socket. + asio::error_code non_blocking(base_implementation_type& impl, + bool mode, asio::error_code& ec) + { + socket_ops::set_user_non_blocking(impl.socket_, impl.state_, mode, ec); + return ec; + } + + // Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const base_implementation_type& impl) const + { + return (impl.state_ & socket_ops::internal_non_blocking) != 0; + } + + // Sets the non-blocking mode of the native socket implementation. + asio::error_code native_non_blocking(base_implementation_type& impl, + bool mode, asio::error_code& ec) + { + socket_ops::set_internal_non_blocking(impl.socket_, impl.state_, mode, ec); + return ec; + } + + // Wait for the socket to become ready to read, ready to write, or to have + // pending error conditions. + asio::error_code wait(base_implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + switch (w) + { + case socket_base::wait_read: + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + break; + case socket_base::wait_write: + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + break; + case socket_base::wait_error: + socket_ops::poll_error(impl.socket_, impl.state_, -1, ec); + break; + default: + ec = asio::error::invalid_argument; + break; + } + + return ec; + } + + // Asynchronously wait for the socket to become ready to read, ready to + // write, or to have pending error conditions. + template + void async_wait(base_implementation_type& impl, + socket_base::wait_type w, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_wait_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_wait")); + + int op_type; + switch (w) + { + case socket_base::wait_read: + op_type = reactor::read_op; + break; + case socket_base::wait_write: + op_type = reactor::write_op; + break; + case socket_base::wait_error: + op_type = reactor::except_op; + break; + default: + p.p->ec_ = asio::error::invalid_argument; + reactor_.post_immediate_completion(p.p, is_continuation); + p.v = p.p = 0; + return; + } + + start_op(impl, op_type, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Send the given data to the peer. + template + size_t send(base_implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_send(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); + } + + // Wait until data can be sent without blocking. + size_t send(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send(base_implementation_type& impl, + const ConstBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_send_op< + ConstBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, impl.state_, + buffers, flags, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_send")); + + start_op(impl, reactor::write_op, p.p, is_continuation, true, + ((impl.state_ & socket_ops::stream_oriented) + && buffer_sequence_adapter::all_empty(buffers))); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_send(null_buffers)")); + + start_op(impl, reactor::write_op, p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Receive some data from the peer. Returns the number of bytes received. + template + size_t receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_recv(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); + } + + // Wait until data can be received without blocking. + size_t receive(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_recv_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, impl.state_, + buffers, flags, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive")); + + start_op(impl, + (flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, + (flags & socket_base::message_out_of_band) == 0, + ((impl.state_ & socket_ops::stream_oriented) + && buffer_sequence_adapter::all_empty(buffers))); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive(null_buffers)")); + + start_op(impl, + (flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, false, false); + p.v = p.p = 0; + } + + // Receive some data with associated flags. Returns the number of bytes + // received. + template + size_t receive_with_flags(base_implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_recvmsg(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), in_flags, out_flags, ec); + } + + // Wait until data can be received without blocking. + size_t receive_with_flags(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + // Clear out_flags, since we cannot give it any other sensible value when + // performing a null_buffers operation. + out_flags = 0; + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive_with_flags(base_implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, Handler& handler, + const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_socket_recvmsg_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, buffers, + in_flags, out_flags, handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive_with_flags")); + + start_op(impl, + (in_flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, + (in_flags & socket_base::message_out_of_band) == 0, false); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive_with_flags(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, Handler& handler, + const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef reactive_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((reactor_.context(), *p.p, "socket", + &impl, impl.socket_, "async_receive_with_flags(null_buffers)")); + + // Clear out_flags, since we cannot give it any other sensible value when + // performing a null_buffers operation. + out_flags = 0; + + start_op(impl, + (in_flags & socket_base::message_out_of_band) + ? reactor::except_op : reactor::read_op, + p.p, is_continuation, false, false); + p.v = p.p = 0; + } + +protected: + // Open a new socket implementation. + ASIO_DECL asio::error_code do_open( + base_implementation_type& impl, int af, + int type, int protocol, asio::error_code& ec); + + // Assign a native socket to a socket implementation. + ASIO_DECL asio::error_code do_assign( + base_implementation_type& impl, int type, + const native_handle_type& native_socket, asio::error_code& ec); + + // Start the asynchronous read or write operation. + ASIO_DECL void start_op(base_implementation_type& impl, int op_type, + reactor_op* op, bool is_continuation, bool is_non_blocking, bool noop); + + // Start the asynchronous accept operation. + ASIO_DECL void start_accept_op(base_implementation_type& impl, + reactor_op* op, bool is_continuation, bool peer_is_open); + + // Start the asynchronous connect operation. + ASIO_DECL void start_connect_op(base_implementation_type& impl, + reactor_op* op, bool is_continuation, + const socket_addr_type* addr, size_t addrlen); + + // The selector that performs event demultiplexing for the service. + reactor& reactor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/reactive_socket_service_base.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // !defined(ASIO_HAS_IOCP) + // && !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_REACTIVE_SOCKET_SERVICE_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_wait_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_wait_op.hpp new file mode 100644 index 00000000..eebcfd1d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactive_wait_op.hpp @@ -0,0 +1,92 @@ +// +// detail/reactive_wait_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTIVE_WAIT_OP_HPP +#define ASIO_DETAIL_REACTIVE_WAIT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactive_wait_op : public reactor_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(reactive_wait_op); + + reactive_wait_op(Handler& handler, const IoExecutor& io_ex) + : reactor_op(&reactive_wait_op::do_perform, + &reactive_wait_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static status do_perform(reactor_op*) + { + return done; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + reactive_wait_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, o->ec_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTIVE_WAIT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor.hpp new file mode 100644 index 00000000..441fc473 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor.hpp @@ -0,0 +1,32 @@ +// +// detail/reactor.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTOR_HPP +#define ASIO_DETAIL_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/reactor_fwd.hpp" + +#if defined(ASIO_HAS_EPOLL) +# include "asio/detail/epoll_reactor.hpp" +#elif defined(ASIO_HAS_KQUEUE) +# include "asio/detail/kqueue_reactor.hpp" +#elif defined(ASIO_HAS_DEV_POLL) +# include "asio/detail/dev_poll_reactor.hpp" +#elif defined(ASIO_HAS_IOCP) || defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/null_reactor.hpp" +#else +# include "asio/detail/select_reactor.hpp" +#endif + +#endif // ASIO_DETAIL_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_fwd.hpp new file mode 100644 index 00000000..ac678294 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_fwd.hpp @@ -0,0 +1,40 @@ +// +// detail/reactor_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTOR_FWD_HPP +#define ASIO_DETAIL_REACTOR_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_IOCP) || defined(ASIO_WINDOWS_RUNTIME) +typedef class null_reactor reactor; +#elif defined(ASIO_HAS_IOCP) +typedef class select_reactor reactor; +#elif defined(ASIO_HAS_EPOLL) +typedef class epoll_reactor reactor; +#elif defined(ASIO_HAS_KQUEUE) +typedef class kqueue_reactor reactor; +#elif defined(ASIO_HAS_DEV_POLL) +typedef class dev_poll_reactor reactor; +#else +typedef class select_reactor reactor; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_REACTOR_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op.hpp new file mode 100644 index 00000000..d2442481 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op.hpp @@ -0,0 +1,65 @@ +// +// detail/reactor_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTOR_OP_HPP +#define ASIO_DETAIL_REACTOR_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class reactor_op + : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + + // The number of bytes transferred, to be passed to the completion handler. + std::size_t bytes_transferred_; + + // Status returned by perform function. May be used to decide whether it is + // worth performing more operations on the descriptor immediately. + enum status { not_done, done, done_and_exhausted }; + + // Perform the operation. Returns true if it is finished. + status perform() + { + return perform_func_(this); + } + +protected: + typedef status (*perform_func_type)(reactor_op*); + + reactor_op(perform_func_type perform_func, func_type complete_func) + : operation(complete_func), + bytes_transferred_(0), + perform_func_(perform_func) + { + } + +private: + perform_func_type perform_func_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTOR_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op_queue.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op_queue.hpp new file mode 100644 index 00000000..2ecc3809 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/reactor_op_queue.hpp @@ -0,0 +1,168 @@ +// +// detail/reactor_op_queue.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REACTOR_OP_QUEUE_HPP +#define ASIO_DETAIL_REACTOR_OP_QUEUE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/hash_map.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class reactor_op_queue + : private noncopyable +{ +public: + typedef Descriptor key_type; + + struct mapped_type : op_queue + { + mapped_type() {} + mapped_type(const mapped_type&) {} + void operator=(const mapped_type&) {} + }; + + typedef typename hash_map::value_type value_type; + typedef typename hash_map::iterator iterator; + + // Constructor. + reactor_op_queue() + : operations_() + { + } + + // Obtain iterators to all registered descriptors. + iterator begin() { return operations_.begin(); } + iterator end() { return operations_.end(); } + + // Add a new operation to the queue. Returns true if this is the only + // operation for the given descriptor, in which case the reactor's event + // demultiplexing function call may need to be interrupted and restarted. + bool enqueue_operation(Descriptor descriptor, reactor_op* op) + { + std::pair entry = + operations_.insert(value_type(descriptor, mapped_type())); + entry.first->second.push(op); + return entry.second; + } + + // Cancel all operations associated with the descriptor identified by the + // supplied iterator. Any operations pending for the descriptor will be + // cancelled. Returns true if any operations were cancelled, in which case + // the reactor's event demultiplexing function may need to be interrupted and + // restarted. + bool cancel_operations(iterator i, op_queue& ops, + const asio::error_code& ec = + asio::error::operation_aborted) + { + if (i != operations_.end()) + { + while (reactor_op* op = i->second.front()) + { + op->ec_ = ec; + i->second.pop(); + ops.push(op); + } + operations_.erase(i); + return true; + } + + return false; + } + + // Cancel all operations associated with the descriptor. Any operations + // pending for the descriptor will be cancelled. Returns true if any + // operations were cancelled, in which case the reactor's event + // demultiplexing function may need to be interrupted and restarted. + bool cancel_operations(Descriptor descriptor, op_queue& ops, + const asio::error_code& ec = + asio::error::operation_aborted) + { + return this->cancel_operations(operations_.find(descriptor), ops, ec); + } + + // Whether there are no operations in the queue. + bool empty() const + { + return operations_.empty(); + } + + // Determine whether there are any operations associated with the descriptor. + bool has_operation(Descriptor descriptor) const + { + return operations_.find(descriptor) != operations_.end(); + } + + // Perform the operations corresponding to the descriptor identified by the + // supplied iterator. Returns true if there are still unfinished operations + // queued for the descriptor. + bool perform_operations(iterator i, op_queue& ops) + { + if (i != operations_.end()) + { + while (reactor_op* op = i->second.front()) + { + if (op->perform()) + { + i->second.pop(); + ops.push(op); + } + else + { + return true; + } + } + operations_.erase(i); + } + return false; + } + + // Perform the operations corresponding to the descriptor. Returns true if + // there are still unfinished operations queued for the descriptor. + bool perform_operations(Descriptor descriptor, op_queue& ops) + { + return this->perform_operations(operations_.find(descriptor), ops); + } + + // Get all operations owned by the queue. + void get_all_operations(op_queue& ops) + { + iterator i = operations_.begin(); + while (i != operations_.end()) + { + iterator op_iter = i++; + ops.push(op_iter->second); + operations_.erase(op_iter); + } + } + +private: + // The operations that are currently executing asynchronously. + hash_map operations_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_REACTOR_OP_QUEUE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/recycling_allocator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/recycling_allocator.hpp new file mode 100644 index 00000000..243dc9bc --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/recycling_allocator.hpp @@ -0,0 +1,106 @@ +// +// detail/recycling_allocator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RECYCLING_ALLOCATOR_HPP +#define ASIO_DETAIL_RECYCLING_ALLOCATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/thread_context.hpp" +#include "asio/detail/thread_info_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class recycling_allocator +{ +public: + typedef T value_type; + + template + struct rebind + { + typedef recycling_allocator other; + }; + + recycling_allocator() + { + } + + template + recycling_allocator(const recycling_allocator&) + { + } + + T* allocate(std::size_t n) + { + typedef thread_context::thread_call_stack call_stack; + void* p = thread_info_base::allocate(Purpose(), + call_stack::top(), sizeof(T) * n); + return static_cast(p); + } + + void deallocate(T* p, std::size_t n) + { + typedef thread_context::thread_call_stack call_stack; + thread_info_base::deallocate(Purpose(), + call_stack::top(), p, sizeof(T) * n); + } +}; + +template +class recycling_allocator +{ +public: + typedef void value_type; + + template + struct rebind + { + typedef recycling_allocator other; + }; + + recycling_allocator() + { + } + + template + recycling_allocator(const recycling_allocator&) + { + } +}; + +template +struct get_recycling_allocator +{ + typedef Allocator type; + static type get(const Allocator& a) { return a; } +}; + +template +struct get_recycling_allocator, Purpose> +{ + typedef recycling_allocator type; + static type get(const std::allocator&) { return type(); } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_RECYCLING_ALLOCATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/regex_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/regex_fwd.hpp new file mode 100644 index 00000000..e0d0ce59 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/regex_fwd.hpp @@ -0,0 +1,35 @@ +// +// detail/regex_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_REGEX_FWD_HPP +#define ASIO_DETAIL_REGEX_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if defined(ASIO_HAS_BOOST_REGEX) + +#include +#include + +namespace boost { + +template +struct sub_match; + +template +class match_results; + +} // namespace boost + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +#endif // ASIO_DETAIL_REGEX_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_endpoint_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_endpoint_op.hpp new file mode 100644 index 00000000..34cb7f79 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_endpoint_op.hpp @@ -0,0 +1,136 @@ +// +// detail/resolve_endpoint_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RESOLVER_ENDPOINT_OP_HPP +#define ASIO_DETAIL_RESOLVER_ENDPOINT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/resolve_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class resolve_endpoint_op : public resolve_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(resolve_endpoint_op); + + typedef typename Protocol::endpoint endpoint_type; + typedef asio::ip::basic_resolver_results results_type; + +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + + resolve_endpoint_op(socket_ops::weak_cancel_token_type cancel_token, + const endpoint_type& endpoint, scheduler_impl& sched, + Handler& handler, const IoExecutor& io_ex) + : resolve_op(&resolve_endpoint_op::do_complete), + cancel_token_(cancel_token), + endpoint_(endpoint), + scheduler_(sched), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the operation object. + resolve_endpoint_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + if (owner && owner != &o->scheduler_) + { + // The operation is being run on the worker io_context. Time to perform + // the resolver operation. + + // Perform the blocking endpoint resolution operation. + char host_name[NI_MAXHOST]; + char service_name[NI_MAXSERV]; + socket_ops::background_getnameinfo(o->cancel_token_, o->endpoint_.data(), + o->endpoint_.size(), host_name, NI_MAXHOST, service_name, NI_MAXSERV, + o->endpoint_.protocol().type(), o->ec_); + o->results_ = results_type::create(o->endpoint_, host_name, service_name); + + // Pass operation back to main io_context for completion. + o->scheduler_.post_deferred_completion(o); + p.v = p.p = 0; + } + else + { + // The operation has been returned to the main io_context. The completion + // handler is ready to be delivered. + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated + // before the upcall is made. Even if we're not about to make an upcall, + // a sub-object of the handler may be the true owner of the memory + // associated with the handler. Consequently, a local copy of the handler + // is required to ensure that any owning sub-object remains valid until + // after we have deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->results_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + endpoint_type endpoint_; + scheduler_impl& scheduler_; + Handler handler_; + IoExecutor io_executor_; + results_type results_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_RESOLVER_ENDPOINT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_op.hpp new file mode 100644 index 00000000..445cf561 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_op.hpp @@ -0,0 +1,45 @@ +// +// detail/resolve_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RESOLVE_OP_HPP +#define ASIO_DETAIL_RESOLVE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class resolve_op : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + +protected: + resolve_op(func_type complete_func) + : operation(complete_func) + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_RESOLVE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_query_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_query_op.hpp new file mode 100644 index 00000000..e5f768f4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolve_query_op.hpp @@ -0,0 +1,148 @@ +// +// detail/resolve_query_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RESOLVE_QUERY_OP_HPP +#define ASIO_DETAIL_RESOLVE_QUERY_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error.hpp" +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/resolve_op.hpp" +#include "asio/detail/socket_ops.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class resolve_query_op : public resolve_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(resolve_query_op); + + typedef asio::ip::basic_resolver_query query_type; + typedef asio::ip::basic_resolver_results results_type; + +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + + resolve_query_op(socket_ops::weak_cancel_token_type cancel_token, + const query_type& query, scheduler_impl& sched, + Handler& handler, const IoExecutor& io_ex) + : resolve_op(&resolve_query_op::do_complete), + cancel_token_(cancel_token), + query_(query), + scheduler_(sched), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex), + addrinfo_(0) + { + handler_work::start(handler_, io_executor_); + } + + ~resolve_query_op() + { + if (addrinfo_) + socket_ops::freeaddrinfo(addrinfo_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the operation object. + resolve_query_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + + if (owner && owner != &o->scheduler_) + { + // The operation is being run on the worker io_context. Time to perform + // the resolver operation. + + // Perform the blocking host resolution operation. + socket_ops::background_getaddrinfo(o->cancel_token_, + o->query_.host_name().c_str(), o->query_.service_name().c_str(), + o->query_.hints(), &o->addrinfo_, o->ec_); + + // Pass operation back to main io_context for completion. + o->scheduler_.post_deferred_completion(o); + p.v = p.p = 0; + } + else + { + // The operation has been returned to the main io_context. The completion + // handler is ready to be delivered. + + // Take ownership of the operation's outstanding work. + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated + // before the upcall is made. Even if we're not about to make an upcall, + // a sub-object of the handler may be the true owner of the memory + // associated with the handler. Consequently, a local copy of the handler + // is required to ensure that any owning sub-object remains valid until + // after we have deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, results_type()); + p.h = asio::detail::addressof(handler.handler_); + if (o->addrinfo_) + { + handler.arg2_ = results_type::create(o->addrinfo_, + o->query_.host_name(), o->query_.service_name()); + } + p.reset(); + + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + query_type query_; + scheduler_impl& scheduler_; + Handler handler_; + IoExecutor io_executor_; + asio::detail::addrinfo_type* addrinfo_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_RESOLVE_QUERY_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service.hpp new file mode 100644 index 00000000..c856cf89 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service.hpp @@ -0,0 +1,145 @@ +// +// detail/resolver_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RESOLVER_SERVICE_HPP +#define ASIO_DETAIL_RESOLVER_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/detail/concurrency_hint.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/resolve_endpoint_op.hpp" +#include "asio/detail/resolve_query_op.hpp" +#include "asio/detail/resolver_service_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class resolver_service : + public execution_context_service_base >, + public resolver_service_base +{ +public: + // The implementation type of the resolver. A cancellation token is used to + // indicate to the background thread that the operation has been cancelled. + typedef socket_ops::shared_cancel_token_type implementation_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The query type. + typedef asio::ip::basic_resolver_query query_type; + + // The results type. + typedef asio::ip::basic_resolver_results results_type; + + // Constructor. + resolver_service(execution_context& context) + : execution_context_service_base >(context), + resolver_service_base(context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + this->base_shutdown(); + } + + // Perform any fork-related housekeeping. + void notify_fork(execution_context::fork_event fork_ev) + { + this->base_notify_fork(fork_ev); + } + + // Resolve a query to a list of entries. + results_type resolve(implementation_type&, const query_type& query, + asio::error_code& ec) + { + asio::detail::addrinfo_type* address_info = 0; + + socket_ops::getaddrinfo(query.host_name().c_str(), + query.service_name().c_str(), query.hints(), &address_info, ec); + auto_addrinfo auto_address_info(address_info); + + return ec ? results_type() : results_type::create( + address_info, query.host_name(), query.service_name()); + } + + // Asynchronously resolve a query to a list of entries. + template + void async_resolve(implementation_type& impl, const query_type& query, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef resolve_query_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl, query, scheduler_, handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "resolver", &impl, 0, "async_resolve")); + + start_resolve_op(p.p); + p.v = p.p = 0; + } + + // Resolve an endpoint to a list of entries. + results_type resolve(implementation_type&, + const endpoint_type& endpoint, asio::error_code& ec) + { + char host_name[NI_MAXHOST]; + char service_name[NI_MAXSERV]; + socket_ops::sync_getnameinfo(endpoint.data(), endpoint.size(), + host_name, NI_MAXHOST, service_name, NI_MAXSERV, + endpoint.protocol().type(), ec); + + return ec ? results_type() : results_type::create( + endpoint, host_name, service_name); + } + + // Asynchronously resolve an endpoint to a list of entries. + template + void async_resolve(implementation_type& impl, const endpoint_type& endpoint, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef resolve_endpoint_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl, endpoint, scheduler_, handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "resolver", &impl, 0, "async_resolve")); + + start_resolve_op(p.p); + p.v = p.p = 0; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_RESOLVER_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service_base.hpp new file mode 100644 index 00000000..5b1f23c6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/resolver_service_base.hpp @@ -0,0 +1,143 @@ +// +// detail/resolver_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP +#define ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/resolve_op.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/thread.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class resolver_service_base +{ +public: + // The implementation type of the resolver. A cancellation token is used to + // indicate to the background thread that the operation has been cancelled. + typedef socket_ops::shared_cancel_token_type implementation_type; + + // Constructor. + ASIO_DECL resolver_service_base(execution_context& context); + + // Destructor. + ASIO_DECL ~resolver_service_base(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void base_shutdown(); + + // Perform any fork-related housekeeping. + ASIO_DECL void base_notify_fork( + execution_context::fork_event fork_ev); + + // Construct a new resolver implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Destroy a resolver implementation. + ASIO_DECL void destroy(implementation_type&); + + // Move-construct a new resolver implementation. + ASIO_DECL void move_construct(implementation_type& impl, + implementation_type& other_impl); + + // Move-assign from another resolver implementation. + ASIO_DECL void move_assign(implementation_type& impl, + resolver_service_base& other_service, + implementation_type& other_impl); + + // Cancel pending asynchronous operations. + ASIO_DECL void cancel(implementation_type& impl); + +protected: + // Helper function to start an asynchronous resolve operation. + ASIO_DECL void start_resolve_op(resolve_op* op); + +#if !defined(ASIO_WINDOWS_RUNTIME) + // Helper class to perform exception-safe cleanup of addrinfo objects. + class auto_addrinfo + : private asio::detail::noncopyable + { + public: + explicit auto_addrinfo(asio::detail::addrinfo_type* ai) + : ai_(ai) + { + } + + ~auto_addrinfo() + { + if (ai_) + socket_ops::freeaddrinfo(ai_); + } + + operator asio::detail::addrinfo_type*() + { + return ai_; + } + + private: + asio::detail::addrinfo_type* ai_; + }; +#endif // !defined(ASIO_WINDOWS_RUNTIME) + + // Helper class to run the work scheduler in a thread. + class work_scheduler_runner; + + // Start the work scheduler if it's not already running. + ASIO_DECL void start_work_thread(); + + // The scheduler implementation used to post completions. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + +private: + // Mutex to protect access to internal data. + asio::detail::mutex mutex_; + + // Private scheduler used for performing asynchronous host resolution. + asio::detail::scoped_ptr work_scheduler_; + + // Thread used for running the work io_context's run loop. + asio::detail::scoped_ptr work_thread_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/resolver_service_base.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler.hpp new file mode 100644 index 00000000..0d721e80 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler.hpp @@ -0,0 +1,224 @@ +// +// detail/scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SCHEDULER_HPP +#define ASIO_DETAIL_SCHEDULER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/error_code.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/conditionally_enabled_event.hpp" +#include "asio/detail/conditionally_enabled_mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_fwd.hpp" +#include "asio/detail/scheduler_operation.hpp" +#include "asio/detail/thread.hpp" +#include "asio/detail/thread_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct scheduler_thread_info; + +class scheduler + : public execution_context_service_base, + public thread_context +{ +public: + typedef scheduler_operation operation; + + // Constructor. Specifies the number of concurrent threads that are likely to + // run the scheduler. If set to 1 certain optimisation are performed. + ASIO_DECL scheduler(asio::execution_context& ctx, + int concurrency_hint = 0, bool own_thread = true); + + // Destructor. + ASIO_DECL ~scheduler(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Initialise the task, if required. + ASIO_DECL void init_task(); + + // Run the event loop until interrupted or no more work. + ASIO_DECL std::size_t run(asio::error_code& ec); + + // Run until interrupted or one operation is performed. + ASIO_DECL std::size_t run_one(asio::error_code& ec); + + // Run until timeout, interrupted, or one operation is performed. + ASIO_DECL std::size_t wait_one( + long usec, asio::error_code& ec); + + // Poll for operations without blocking. + ASIO_DECL std::size_t poll(asio::error_code& ec); + + // Poll for one operation without blocking. + ASIO_DECL std::size_t poll_one(asio::error_code& ec); + + // Interrupt the event processing loop. + ASIO_DECL void stop(); + + // Determine whether the scheduler is stopped. + ASIO_DECL bool stopped() const; + + // Restart in preparation for a subsequent run invocation. + ASIO_DECL void restart(); + + // Notify that some work has started. + void work_started() + { + ++outstanding_work_; + } + + // Used to compensate for a forthcoming work_finished call. Must be called + // from within a scheduler-owned thread. + ASIO_DECL void compensating_work_started(); + + // Notify that some work has finished. + void work_finished() + { + if (--outstanding_work_ == 0) + stop(); + } + + // Return whether a handler can be dispatched immediately. + bool can_dispatch() + { + return thread_call_stack::contains(this) != 0; + } + + // Request invocation of the given operation and return immediately. Assumes + // that work_started() has not yet been called for the operation. + ASIO_DECL void post_immediate_completion( + operation* op, bool is_continuation); + + // Request invocation of the given operation and return immediately. Assumes + // that work_started() was previously called for the operation. + ASIO_DECL void post_deferred_completion(operation* op); + + // Request invocation of the given operations and return immediately. Assumes + // that work_started() was previously called for each operation. + ASIO_DECL void post_deferred_completions(op_queue& ops); + + // Enqueue the given operation following a failed attempt to dispatch the + // operation for immediate invocation. + ASIO_DECL void do_dispatch(operation* op); + + // Process unfinished operations as part of a shutdownoperation. Assumes that + // work_started() was previously called for the operations. + ASIO_DECL void abandon_operations(op_queue& ops); + + // Get the concurrency hint that was used to initialise the scheduler. + int concurrency_hint() const + { + return concurrency_hint_; + } + +private: + // The mutex type used by this scheduler. + typedef conditionally_enabled_mutex mutex; + + // The event type used by this scheduler. + typedef conditionally_enabled_event event; + + // Structure containing thread-specific data. + typedef scheduler_thread_info thread_info; + + // Run at most one operation. May block. + ASIO_DECL std::size_t do_run_one(mutex::scoped_lock& lock, + thread_info& this_thread, const asio::error_code& ec); + + // Run at most one operation with a timeout. May block. + ASIO_DECL std::size_t do_wait_one(mutex::scoped_lock& lock, + thread_info& this_thread, long usec, const asio::error_code& ec); + + // Poll for at most one operation. + ASIO_DECL std::size_t do_poll_one(mutex::scoped_lock& lock, + thread_info& this_thread, const asio::error_code& ec); + + // Stop the task and all idle threads. + ASIO_DECL void stop_all_threads(mutex::scoped_lock& lock); + + // Wake a single idle thread, or the task, and always unlock the mutex. + ASIO_DECL void wake_one_thread_and_unlock( + mutex::scoped_lock& lock); + + // Helper class to run the scheduler in its own thread. + class thread_function; + friend class thread_function; + + // Helper class to perform task-related operations on block exit. + struct task_cleanup; + friend struct task_cleanup; + + // Helper class to call work-related operations on block exit. + struct work_cleanup; + friend struct work_cleanup; + + // Whether to optimise for single-threaded use cases. + const bool one_thread_; + + // Mutex to protect access to internal data. + mutable mutex mutex_; + + // Event to wake up blocked threads. + event wakeup_event_; + + // The task to be run by this service. + reactor* task_; + + // Operation object to represent the position of the task in the queue. + struct task_operation : operation + { + task_operation() : operation(0) {} + } task_operation_; + + // Whether the task has been interrupted. + bool task_interrupted_; + + // The count of unfinished work. + atomic_count outstanding_work_; + + // The queue of handlers that are ready to be delivered. + op_queue op_queue_; + + // Flag to indicate that the dispatcher has been stopped. + bool stopped_; + + // Flag to indicate that the dispatcher has been shut down. + bool shutdown_; + + // The concurrency hint used to initialise the scheduler. + const int concurrency_hint_; + + // The thread that is running the scheduler. + asio::detail::thread* thread_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/scheduler.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_SCHEDULER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_operation.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_operation.hpp new file mode 100644 index 00000000..6f4c5df6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_operation.hpp @@ -0,0 +1,78 @@ +// +// detail/scheduler_operation.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SCHEDULER_OPERATION_HPP +#define ASIO_DETAIL_SCHEDULER_OPERATION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/error_code.hpp" +#include "asio/detail/handler_tracking.hpp" +#include "asio/detail/op_queue.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class scheduler; + +// Base class for all operations. A function pointer is used instead of virtual +// functions to avoid the associated overhead. +class scheduler_operation ASIO_INHERIT_TRACKED_HANDLER +{ +public: + typedef scheduler_operation operation_type; + + void complete(void* owner, const asio::error_code& ec, + std::size_t bytes_transferred) + { + func_(owner, this, ec, bytes_transferred); + } + + void destroy() + { + func_(0, this, asio::error_code(), 0); + } + +protected: + typedef void (*func_type)(void*, + scheduler_operation*, + const asio::error_code&, std::size_t); + + scheduler_operation(func_type func) + : next_(0), + func_(func), + task_result_(0) + { + } + + // Prevents deletion through this type. + ~scheduler_operation() + { + } + +private: + friend class op_queue_access; + scheduler_operation* next_; + func_type func_; +protected: + friend class scheduler; + unsigned int task_result_; // Passed into bytes transferred. +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SCHEDULER_OPERATION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_thread_info.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_thread_info.hpp new file mode 100644 index 00000000..202ac0a7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scheduler_thread_info.hpp @@ -0,0 +1,40 @@ +// +// detail/scheduler_thread_info.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SCHEDULER_THREAD_INFO_HPP +#define ASIO_DETAIL_SCHEDULER_THREAD_INFO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/op_queue.hpp" +#include "asio/detail/thread_info_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class scheduler; +class scheduler_operation; + +struct scheduler_thread_info : public thread_info_base +{ + op_queue private_op_queue; + long private_outstanding_work; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SCHEDULER_THREAD_INFO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_lock.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_lock.hpp new file mode 100644 index 00000000..94d49666 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_lock.hpp @@ -0,0 +1,101 @@ +// +// detail/scoped_lock.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SCOPED_LOCK_HPP +#define ASIO_DETAIL_SCOPED_LOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper class to lock and unlock a mutex automatically. +template +class scoped_lock + : private noncopyable +{ +public: + // Tag type used to distinguish constructors. + enum adopt_lock_t { adopt_lock }; + + // Constructor adopts a lock that is already held. + scoped_lock(Mutex& m, adopt_lock_t) + : mutex_(m), + locked_(true) + { + } + + // Constructor acquires the lock. + explicit scoped_lock(Mutex& m) + : mutex_(m) + { + mutex_.lock(); + locked_ = true; + } + + // Destructor releases the lock. + ~scoped_lock() + { + if (locked_) + mutex_.unlock(); + } + + // Explicitly acquire the lock. + void lock() + { + if (!locked_) + { + mutex_.lock(); + locked_ = true; + } + } + + // Explicitly release the lock. + void unlock() + { + if (locked_) + { + mutex_.unlock(); + locked_ = false; + } + } + + // Test whether the lock is held. + bool locked() const + { + return locked_; + } + + // Get the underlying mutex. + Mutex& mutex() + { + return mutex_; + } + +private: + // The underlying mutex. + Mutex& mutex_; + + // Whether the mutex is currently locked or unlocked. + bool locked_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SCOPED_LOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_ptr.hpp new file mode 100644 index 00000000..1fff7418 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/scoped_ptr.hpp @@ -0,0 +1,87 @@ +// +// detail/scoped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SCOPED_PTR_HPP +#define ASIO_DETAIL_SCOPED_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class scoped_ptr +{ +public: + // Constructor. + explicit scoped_ptr(T* p = 0) + : p_(p) + { + } + + // Destructor. + ~scoped_ptr() + { + delete p_; + } + + // Access. + T* get() + { + return p_; + } + + // Access. + T* operator->() + { + return p_; + } + + // Dereference. + T& operator*() + { + return *p_; + } + + // Reset pointer. + void reset(T* p = 0) + { + delete p_; + p_ = p; + } + + // Release ownership of the pointer. + T* release() + { + T* tmp = p_; + p_ = 0; + return tmp; + } + +private: + // Disallow copying and assignment. + scoped_ptr(const scoped_ptr&); + scoped_ptr& operator=(const scoped_ptr&); + + T* p_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SCOPED_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_interrupter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_interrupter.hpp new file mode 100644 index 00000000..e77e2972 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_interrupter.hpp @@ -0,0 +1,46 @@ +// +// detail/select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SELECT_INTERRUPTER_HPP +#define ASIO_DETAIL_SELECT_INTERRUPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS_RUNTIME) + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) || defined(__SYMBIAN32__) || defined (ESP_PLATFORM) +# include "asio/detail/socket_select_interrupter.hpp" +#elif defined(ASIO_HAS_EVENTFD) +# include "asio/detail/eventfd_select_interrupter.hpp" +#else +# include "asio/detail/pipe_select_interrupter.hpp" +#endif + +namespace asio { +namespace detail { + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) || defined(__SYMBIAN32__) || defined (ESP_PLATFORM) +typedef socket_select_interrupter select_interrupter; +#elif defined(ASIO_HAS_EVENTFD) +typedef eventfd_select_interrupter select_interrupter; +#else +typedef pipe_select_interrupter select_interrupter; +#endif + +} // namespace detail +} // namespace asio + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_SELECT_INTERRUPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_reactor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_reactor.hpp new file mode 100644 index 00000000..be4d02cb --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/select_reactor.hpp @@ -0,0 +1,238 @@ +// +// detail/select_reactor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SELECT_REACTOR_HPP +#define ASIO_DETAIL_SELECT_REACTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) \ + || (!defined(ASIO_HAS_DEV_POLL) \ + && !defined(ASIO_HAS_EPOLL) \ + && !defined(ASIO_HAS_KQUEUE) \ + && !defined(ASIO_WINDOWS_RUNTIME)) + +#include +#include "asio/detail/fd_set_adapter.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/reactor_op_queue.hpp" +#include "asio/detail/select_interrupter.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/thread.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class select_reactor + : public execution_context_service_base +{ +public: +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) + enum op_types { read_op = 0, write_op = 1, except_op = 2, + max_select_ops = 3, connect_op = 3, max_ops = 4 }; +#else // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + enum op_types { read_op = 0, write_op = 1, except_op = 2, + max_select_ops = 3, connect_op = 1, max_ops = 3 }; +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + + // Per-descriptor data. + struct per_descriptor_data + { + }; + + // Constructor. + ASIO_DECL select_reactor(asio::execution_context& ctx); + + // Destructor. + ASIO_DECL ~select_reactor(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Recreate internal descriptors following a fork. + ASIO_DECL void notify_fork( + asio::execution_context::fork_event fork_ev); + + // Initialise the task, but only if the reactor is not in its own thread. + ASIO_DECL void init_task(); + + // Register a socket with the reactor. Returns 0 on success, system error + // code on failure. + ASIO_DECL int register_descriptor(socket_type, per_descriptor_data&); + + // Register a descriptor with an associated single operation. Returns 0 on + // success, system error code on failure. + ASIO_DECL int register_internal_descriptor( + int op_type, socket_type descriptor, + per_descriptor_data& descriptor_data, reactor_op* op); + + // Post a reactor operation for immediate completion. + void post_immediate_completion(reactor_op* op, bool is_continuation) + { + scheduler_.post_immediate_completion(op, is_continuation); + } + + // Start a new operation. The reactor operation will be performed when the + // given descriptor is flagged as ready, or an error has occurred. + ASIO_DECL void start_op(int op_type, socket_type descriptor, + per_descriptor_data&, reactor_op* op, bool is_continuation, bool); + + // Cancel all operations associated with the given descriptor. The + // handlers associated with the descriptor will be invoked with the + // operation_aborted error. + ASIO_DECL void cancel_ops(socket_type descriptor, per_descriptor_data&); + + // Cancel any operations that are running against the descriptor and remove + // its registration from the reactor. The reactor resources associated with + // the descriptor must be released by calling cleanup_descriptor_data. + ASIO_DECL void deregister_descriptor(socket_type descriptor, + per_descriptor_data&, bool closing); + + // Remove the descriptor's registration from the reactor. The reactor + // resources associated with the descriptor must be released by calling + // cleanup_descriptor_data. + ASIO_DECL void deregister_internal_descriptor( + socket_type descriptor, per_descriptor_data&); + + // Perform any post-deregistration cleanup tasks associated with the + // descriptor data. + ASIO_DECL void cleanup_descriptor_data(per_descriptor_data&); + + // Move descriptor registration from one descriptor_data object to another. + ASIO_DECL void move_descriptor(socket_type descriptor, + per_descriptor_data& target_descriptor_data, + per_descriptor_data& source_descriptor_data); + + // Add a new timer queue to the reactor. + template + void add_timer_queue(timer_queue& queue); + + // Remove a timer queue from the reactor. + template + void remove_timer_queue(timer_queue& queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer operations associated with the given token. Returns the + // number of operations that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& target, + typename timer_queue::per_timer_data& source); + + // Run select once until interrupted or events are ready to be dispatched. + ASIO_DECL void run(long usec, op_queue& ops); + + // Interrupt the select loop. + ASIO_DECL void interrupt(); + +private: +#if defined(ASIO_HAS_IOCP) + // Run the select loop in the thread. + ASIO_DECL void run_thread(); +#endif // defined(ASIO_HAS_IOCP) + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // Get the timeout value for the select call. + ASIO_DECL timeval* get_timeout(long usec, timeval& tv); + + // Cancel all operations associated with the given descriptor. This function + // does not acquire the select_reactor's mutex. + ASIO_DECL void cancel_ops_unlocked(socket_type descriptor, + const asio::error_code& ec); + + // The scheduler implementation used to post completions. +# if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_type; +# else // defined(ASIO_HAS_IOCP) + typedef class scheduler scheduler_type; +# endif // defined(ASIO_HAS_IOCP) + scheduler_type& scheduler_; + + // Mutex to protect access to internal data. + asio::detail::mutex mutex_; + + // The interrupter is used to break a blocking select call. + select_interrupter interrupter_; + + // The queues of read, write and except operations. + reactor_op_queue op_queue_[max_ops]; + + // The file descriptor sets to be passed to the select system call. + fd_set_adapter fd_sets_[max_select_ops]; + + // The timer queues. + timer_queue_set timer_queues_; + +#if defined(ASIO_HAS_IOCP) + // Helper class to run the reactor loop in a thread. + class thread_function; + friend class thread_function; + + // Does the reactor loop thread need to stop. + bool stop_thread_; + + // The thread that is running the reactor loop. + asio::detail::thread* thread_; +#endif // defined(ASIO_HAS_IOCP) + + // Whether the service has been shut down. + bool shutdown_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/select_reactor.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/select_reactor.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_IOCP) + // || (!defined(ASIO_HAS_DEV_POLL) + // && !defined(ASIO_HAS_EPOLL) + // && !defined(ASIO_HAS_KQUEUE) + // && !defined(ASIO_WINDOWS_RUNTIME)) + +#endif // ASIO_DETAIL_SELECT_REACTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/service_registry.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/service_registry.hpp new file mode 100644 index 00000000..edced403 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/service_registry.hpp @@ -0,0 +1,164 @@ +// +// detail/service_registry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SERVICE_REGISTRY_HPP +#define ASIO_DETAIL_SERVICE_REGISTRY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/mutex.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class io_context; + +namespace detail { + +template +class typeid_wrapper {}; + +class service_registry + : private noncopyable +{ +public: + // Constructor. + ASIO_DECL service_registry(execution_context& owner); + + // Destructor. + ASIO_DECL ~service_registry(); + + // Shutdown all services. + ASIO_DECL void shutdown_services(); + + // Destroy all services. + ASIO_DECL void destroy_services(); + + // Notify all services of a fork event. + ASIO_DECL void notify_fork(execution_context::fork_event fork_ev); + + // Get the service object corresponding to the specified service type. Will + // create a new service object automatically if no such object already + // exists. Ownership of the service object is not transferred to the caller. + template + Service& use_service(); + + // Get the service object corresponding to the specified service type. Will + // create a new service object automatically if no such object already + // exists. Ownership of the service object is not transferred to the caller. + // This overload is used for backwards compatibility with services that + // inherit from io_context::service. + template + Service& use_service(io_context& owner); + + // Add a service object. Throws on error, in which case ownership of the + // object is retained by the caller. + template + void add_service(Service* new_service); + + // Check whether a service object of the specified type already exists. + template + bool has_service() const; + +private: + // Initalise a service's key when the key_type typedef is not available. + template + static void init_key(execution_context::service::key& key, ...); + +#if !defined(ASIO_NO_TYPEID) + // Initalise a service's key when the key_type typedef is available. + template + static void init_key(execution_context::service::key& key, + typename enable_if< + is_base_of::value>::type*); +#endif // !defined(ASIO_NO_TYPEID) + + // Initialise a service's key based on its id. + ASIO_DECL static void init_key_from_id( + execution_context::service::key& key, + const execution_context::id& id); + +#if !defined(ASIO_NO_TYPEID) + // Initialise a service's key based on its id. + template + static void init_key_from_id(execution_context::service::key& key, + const service_id& /*id*/); +#endif // !defined(ASIO_NO_TYPEID) + + // Check if a service matches the given id. + ASIO_DECL static bool keys_match( + const execution_context::service::key& key1, + const execution_context::service::key& key2); + + // The type of a factory function used for creating a service instance. + typedef execution_context::service*(*factory_type)(void*); + + // Factory function for creating a service instance. + template + static execution_context::service* create(void* owner); + + // Destroy a service instance. + ASIO_DECL static void destroy(execution_context::service* service); + + // Helper class to manage service pointers. + struct auto_service_ptr; + friend struct auto_service_ptr; + struct auto_service_ptr + { + execution_context::service* ptr_; + ~auto_service_ptr() { destroy(ptr_); } + }; + + // Get the service object corresponding to the specified service key. Will + // create a new service object automatically if no such object already + // exists. Ownership of the service object is not transferred to the caller. + ASIO_DECL execution_context::service* do_use_service( + const execution_context::service::key& key, + factory_type factory, void* owner); + + // Add a service object. Throws on error, in which case ownership of the + // object is retained by the caller. + ASIO_DECL void do_add_service( + const execution_context::service::key& key, + execution_context::service* new_service); + + // Check whether a service object with the specified key already exists. + ASIO_DECL bool do_has_service( + const execution_context::service::key& key) const; + + // Mutex to protect access to internal data. + mutable asio::detail::mutex mutex_; + + // The owner of this service registry and the services it contains. + execution_context& owner_; + + // The first service in the list of contained services. + execution_context::service* first_service_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/service_registry.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/service_registry.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_SERVICE_REGISTRY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_blocker.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_blocker.hpp new file mode 100644 index 00000000..4fdfc6a8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_blocker.hpp @@ -0,0 +1,44 @@ +// +// detail/signal_blocker.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SIGNAL_BLOCKER_HPP +#define ASIO_DETAIL_SIGNAL_BLOCKER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \ + || defined(ASIO_WINDOWS_RUNTIME) \ + || defined(__CYGWIN__) || defined(__SYMBIAN32__) +# include "asio/detail/null_signal_blocker.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_signal_blocker.hpp" +#else +# error Only Windows and POSIX are supported! +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) || defined(ASIO_WINDOWS) \ + || defined(ASIO_WINDOWS_RUNTIME) \ + || defined(__CYGWIN__) || defined(__SYMBIAN32__) +typedef null_signal_blocker signal_blocker; +#elif defined(ASIO_HAS_PTHREADS) +typedef posix_signal_blocker signal_blocker; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_SIGNAL_BLOCKER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_handler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_handler.hpp new file mode 100644 index 00000000..e5176f00 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_handler.hpp @@ -0,0 +1,88 @@ +// +// detail/signal_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SIGNAL_HANDLER_HPP +#define ASIO_DETAIL_SIGNAL_HANDLER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_work.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/signal_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class signal_handler : public signal_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(signal_handler); + + signal_handler(Handler& h, const IoExecutor& io_ex) + : signal_op(&signal_handler::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(h)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + signal_handler* h(static_cast(base)); + ptr p = { asio::detail::addressof(h->handler_), h, h }; + handler_work w(h->handler_, h->io_executor_); + + ASIO_HANDLER_COMPLETION((*h)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(h->handler_, h->ec_, h->signal_number_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SIGNAL_HANDLER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_init.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_init.hpp new file mode 100644 index 00000000..8d99197d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_init.hpp @@ -0,0 +1,47 @@ +// +// detail/signal_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SIGNAL_INIT_HPP +#define ASIO_DETAIL_SIGNAL_INIT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class signal_init +{ +public: + // Constructor. + signal_init() + { + std::signal(Signal, SIG_IGN); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#endif // ASIO_DETAIL_SIGNAL_INIT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_op.hpp new file mode 100644 index 00000000..7ca5cbd5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_op.hpp @@ -0,0 +1,49 @@ +// +// detail/signal_op.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SIGNAL_OP_HPP +#define ASIO_DETAIL_SIGNAL_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class signal_op + : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + + // The signal number to be passed to the completion handler. + int signal_number_; + +protected: + signal_op(func_type func) + : operation(func), + signal_number_(0) + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SIGNAL_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_set_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_set_service.hpp new file mode 100644 index 00000000..d4efe9c5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/signal_set_service.hpp @@ -0,0 +1,229 @@ +// +// detail/signal_set_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SIGNAL_SET_SERVICE_HPP +#define ASIO_DETAIL_SIGNAL_SET_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/signal_handler.hpp" +#include "asio/detail/signal_op.hpp" +#include "asio/detail/socket_types.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) +# include "asio/detail/reactor.hpp" +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +#if defined(NSIG) && (NSIG > 0) +enum { max_signal_number = NSIG }; +#else +enum { max_signal_number = 128 }; +#endif + +extern ASIO_DECL struct signal_state* get_signal_state(); + +extern "C" ASIO_DECL void asio_signal_handler(int signal_number); + +class signal_set_service : + public execution_context_service_base +{ +public: + // Type used for tracking an individual signal registration. + class registration + { + public: + // Default constructor. + registration() + : signal_number_(0), + queue_(0), + undelivered_(0), + next_in_table_(0), + prev_in_table_(0), + next_in_set_(0) + { + } + + private: + // Only this service will have access to the internal values. + friend class signal_set_service; + + // The signal number that is registered. + int signal_number_; + + // The waiting signal handlers. + op_queue* queue_; + + // The number of undelivered signals. + std::size_t undelivered_; + + // Pointers to adjacent registrations in the registrations_ table. + registration* next_in_table_; + registration* prev_in_table_; + + // Link to next registration in the signal set. + registration* next_in_set_; + }; + + // The implementation type of the signal_set. + class implementation_type + { + public: + // Default constructor. + implementation_type() + : signals_(0) + { + } + + private: + // Only this service will have access to the internal values. + friend class signal_set_service; + + // The pending signal handlers. + op_queue queue_; + + // Linked list of registered signals. + registration* signals_; + }; + + // Constructor. + ASIO_DECL signal_set_service(execution_context& context); + + // Destructor. + ASIO_DECL ~signal_set_service(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Perform fork-related housekeeping. + ASIO_DECL void notify_fork( + asio::execution_context::fork_event fork_ev); + + // Construct a new signal_set implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Destroy a signal_set implementation. + ASIO_DECL void destroy(implementation_type& impl); + + // Add a signal to a signal_set. + ASIO_DECL asio::error_code add(implementation_type& impl, + int signal_number, asio::error_code& ec); + + // Remove a signal to a signal_set. + ASIO_DECL asio::error_code remove(implementation_type& impl, + int signal_number, asio::error_code& ec); + + // Remove all signals from a signal_set. + ASIO_DECL asio::error_code clear(implementation_type& impl, + asio::error_code& ec); + + // Cancel all operations associated with the signal set. + ASIO_DECL asio::error_code cancel(implementation_type& impl, + asio::error_code& ec); + + // Start an asynchronous operation to wait for a signal to be delivered. + template + void async_wait(implementation_type& impl, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef signal_handler op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "signal_set", &impl, 0, "async_wait")); + + start_wait_op(impl, p.p); + p.v = p.p = 0; + } + + // Deliver notification that a particular signal occurred. + ASIO_DECL static void deliver_signal(int signal_number); + +private: + // Helper function to add a service to the global signal state. + ASIO_DECL static void add_service(signal_set_service* service); + + // Helper function to remove a service from the global signal state. + ASIO_DECL static void remove_service(signal_set_service* service); + + // Helper function to create the pipe descriptors. + ASIO_DECL static void open_descriptors(); + + // Helper function to close the pipe descriptors. + ASIO_DECL static void close_descriptors(); + + // Helper function to start a wait operation. + ASIO_DECL void start_wait_op(implementation_type& impl, signal_op* op); + + // The scheduler used for dispatching handlers. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + +#if !defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_RUNTIME) \ + && !defined(__CYGWIN__) + // The type used for registering for pipe reactor notifications. + class pipe_read_op; + + // The reactor used for waiting for pipe readiness. + reactor& reactor_; + + // The per-descriptor reactor data used for the pipe. + reactor::per_descriptor_data reactor_data_; +#endif // !defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_RUNTIME) + // && !defined(__CYGWIN__) + + // A mapping from signal number to the registered signal sets. + registration* registrations_[max_signal_number]; + + // Pointers to adjacent services in linked list. + signal_set_service* next_; + signal_set_service* prev_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/signal_set_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_SIGNAL_SET_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_holder.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_holder.hpp new file mode 100644 index 00000000..aaa6e2d6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_holder.hpp @@ -0,0 +1,98 @@ +// +// detail/socket_holder.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOCKET_HOLDER_HPP +#define ASIO_DETAIL_SOCKET_HOLDER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Implement the resource acquisition is initialisation idiom for sockets. +class socket_holder + : private noncopyable +{ +public: + // Construct as an uninitialised socket. + socket_holder() + : socket_(invalid_socket) + { + } + + // Construct to take ownership of the specified socket. + explicit socket_holder(socket_type s) + : socket_(s) + { + } + + // Destructor. + ~socket_holder() + { + if (socket_ != invalid_socket) + { + asio::error_code ec; + socket_ops::state_type state = 0; + socket_ops::close(socket_, state, true, ec); + } + } + + // Get the underlying socket. + socket_type get() const + { + return socket_; + } + + // Reset to an uninitialised socket. + void reset() + { + if (socket_ != invalid_socket) + { + asio::error_code ec; + socket_ops::state_type state = 0; + socket_ops::close(socket_, state, true, ec); + socket_ = invalid_socket; + } + } + + // Reset to take ownership of the specified socket. + void reset(socket_type s) + { + reset(); + socket_ = s; + } + + // Release ownership of the socket. + socket_type release() + { + socket_type tmp = socket_; + socket_ = invalid_socket; + return tmp; + } + +private: + // The underlying socket. + socket_type socket_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SOCKET_HOLDER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_ops.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_ops.hpp new file mode 100644 index 00000000..4b94e1f0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_ops.hpp @@ -0,0 +1,337 @@ +// +// detail/socket_ops.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOCKET_OPS_HPP +#define ASIO_DETAIL_SOCKET_OPS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/error_code.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { +namespace socket_ops { + +// Socket state bits. +enum +{ + // The user wants a non-blocking socket. + user_set_non_blocking = 1, + + // The socket has been set non-blocking. + internal_non_blocking = 2, + + // Helper "state" used to determine whether the socket is non-blocking. + non_blocking = user_set_non_blocking | internal_non_blocking, + + // User wants connection_aborted errors, which are disabled by default. + enable_connection_aborted = 4, + + // The user set the linger option. Needs to be checked when closing. + user_set_linger = 8, + + // The socket is stream-oriented. + stream_oriented = 16, + + // The socket is datagram-oriented. + datagram_oriented = 32, + + // The socket may have been dup()-ed. + possible_dup = 64 +}; + +typedef unsigned char state_type; + +struct noop_deleter { void operator()(void*) {} }; +typedef shared_ptr shared_cancel_token_type; +typedef weak_ptr weak_cancel_token_type; + +#if !defined(ASIO_WINDOWS_RUNTIME) + +ASIO_DECL socket_type accept(socket_type s, socket_addr_type* addr, + std::size_t* addrlen, asio::error_code& ec); + +ASIO_DECL socket_type sync_accept(socket_type s, + state_type state, socket_addr_type* addr, + std::size_t* addrlen, asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_accept(socket_type s, + void* output_buffer, DWORD address_length, + socket_addr_type* addr, std::size_t* addrlen, + socket_type new_socket, asio::error_code& ec); + +#else // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_accept(socket_type s, + state_type state, socket_addr_type* addr, std::size_t* addrlen, + asio::error_code& ec, socket_type& new_socket); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL int bind(socket_type s, const socket_addr_type* addr, + std::size_t addrlen, asio::error_code& ec); + +ASIO_DECL int close(socket_type s, state_type& state, + bool destruction, asio::error_code& ec); + +ASIO_DECL bool set_user_non_blocking(socket_type s, + state_type& state, bool value, asio::error_code& ec); + +ASIO_DECL bool set_internal_non_blocking(socket_type s, + state_type& state, bool value, asio::error_code& ec); + +ASIO_DECL int shutdown(socket_type s, + int what, asio::error_code& ec); + +ASIO_DECL int connect(socket_type s, const socket_addr_type* addr, + std::size_t addrlen, asio::error_code& ec); + +ASIO_DECL void sync_connect(socket_type s, const socket_addr_type* addr, + std::size_t addrlen, asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_connect(socket_type s, + asio::error_code& ec); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_connect(socket_type s, + asio::error_code& ec); + +ASIO_DECL int socketpair(int af, int type, int protocol, + socket_type sv[2], asio::error_code& ec); + +ASIO_DECL bool sockatmark(socket_type s, asio::error_code& ec); + +ASIO_DECL size_t available(socket_type s, asio::error_code& ec); + +ASIO_DECL int listen(socket_type s, + int backlog, asio::error_code& ec); + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +typedef WSABUF buf; +#else // defined(ASIO_WINDOWS) || defined(__CYGWIN__) +typedef iovec buf; +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +ASIO_DECL void init_buf(buf& b, void* data, size_t size); + +ASIO_DECL void init_buf(buf& b, const void* data, size_t size); + +ASIO_DECL signed_size_type recv(socket_type s, buf* bufs, + size_t count, int flags, asio::error_code& ec); + +ASIO_DECL size_t sync_recv(socket_type s, state_type state, buf* bufs, + size_t count, int flags, bool all_empty, asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_recv(state_type state, + const weak_cancel_token_type& cancel_token, bool all_empty, + asio::error_code& ec, size_t bytes_transferred); + +#else // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_recv(socket_type s, + buf* bufs, size_t count, int flags, bool is_stream, + asio::error_code& ec, size_t& bytes_transferred); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL signed_size_type recvfrom(socket_type s, buf* bufs, + size_t count, int flags, socket_addr_type* addr, + std::size_t* addrlen, asio::error_code& ec); + +ASIO_DECL size_t sync_recvfrom(socket_type s, state_type state, + buf* bufs, size_t count, int flags, socket_addr_type* addr, + std::size_t* addrlen, asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_recvfrom( + const weak_cancel_token_type& cancel_token, + asio::error_code& ec); + +#else // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_recvfrom(socket_type s, + buf* bufs, size_t count, int flags, + socket_addr_type* addr, std::size_t* addrlen, + asio::error_code& ec, size_t& bytes_transferred); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL signed_size_type recvmsg(socket_type s, buf* bufs, + size_t count, int in_flags, int& out_flags, + asio::error_code& ec); + +ASIO_DECL size_t sync_recvmsg(socket_type s, state_type state, + buf* bufs, size_t count, int in_flags, int& out_flags, + asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_recvmsg( + const weak_cancel_token_type& cancel_token, + asio::error_code& ec); + +#else // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_recvmsg(socket_type s, + buf* bufs, size_t count, int in_flags, int& out_flags, + asio::error_code& ec, size_t& bytes_transferred); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL signed_size_type send(socket_type s, const buf* bufs, + size_t count, int flags, asio::error_code& ec); + +ASIO_DECL size_t sync_send(socket_type s, state_type state, + const buf* bufs, size_t count, int flags, + bool all_empty, asio::error_code& ec); + +#if defined(ASIO_HAS_IOCP) + +ASIO_DECL void complete_iocp_send( + const weak_cancel_token_type& cancel_token, + asio::error_code& ec); + +#else // defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_send(socket_type s, + const buf* bufs, size_t count, int flags, + asio::error_code& ec, size_t& bytes_transferred); + +#endif // defined(ASIO_HAS_IOCP) + +ASIO_DECL signed_size_type sendto(socket_type s, const buf* bufs, + size_t count, int flags, const socket_addr_type* addr, + std::size_t addrlen, asio::error_code& ec); + +ASIO_DECL size_t sync_sendto(socket_type s, state_type state, + const buf* bufs, size_t count, int flags, const socket_addr_type* addr, + std::size_t addrlen, asio::error_code& ec); + +#if !defined(ASIO_HAS_IOCP) + +ASIO_DECL bool non_blocking_sendto(socket_type s, + const buf* bufs, size_t count, int flags, + const socket_addr_type* addr, std::size_t addrlen, + asio::error_code& ec, size_t& bytes_transferred); + +#endif // !defined(ASIO_HAS_IOCP) + +ASIO_DECL socket_type socket(int af, int type, int protocol, + asio::error_code& ec); + +ASIO_DECL int setsockopt(socket_type s, state_type& state, + int level, int optname, const void* optval, + std::size_t optlen, asio::error_code& ec); + +ASIO_DECL int getsockopt(socket_type s, state_type state, + int level, int optname, void* optval, + size_t* optlen, asio::error_code& ec); + +ASIO_DECL int getpeername(socket_type s, socket_addr_type* addr, + std::size_t* addrlen, bool cached, asio::error_code& ec); + +ASIO_DECL int getsockname(socket_type s, socket_addr_type* addr, + std::size_t* addrlen, asio::error_code& ec); + +ASIO_DECL int ioctl(socket_type s, state_type& state, + int cmd, ioctl_arg_type* arg, asio::error_code& ec); + +ASIO_DECL int select(int nfds, fd_set* readfds, fd_set* writefds, + fd_set* exceptfds, timeval* timeout, asio::error_code& ec); + +ASIO_DECL int poll_read(socket_type s, + state_type state, int msec, asio::error_code& ec); + +ASIO_DECL int poll_write(socket_type s, + state_type state, int msec, asio::error_code& ec); + +ASIO_DECL int poll_error(socket_type s, + state_type state, int msec, asio::error_code& ec); + +ASIO_DECL int poll_connect(socket_type s, + int msec, asio::error_code& ec); + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +ASIO_DECL const char* inet_ntop(int af, const void* src, char* dest, + size_t length, unsigned long scope_id, asio::error_code& ec); + +ASIO_DECL int inet_pton(int af, const char* src, void* dest, + unsigned long* scope_id, asio::error_code& ec); + +ASIO_DECL int gethostname(char* name, + int namelen, asio::error_code& ec); + +#if !defined(ASIO_WINDOWS_RUNTIME) + +ASIO_DECL asio::error_code getaddrinfo(const char* host, + const char* service, const addrinfo_type& hints, + addrinfo_type** result, asio::error_code& ec); + +ASIO_DECL asio::error_code background_getaddrinfo( + const weak_cancel_token_type& cancel_token, const char* host, + const char* service, const addrinfo_type& hints, + addrinfo_type** result, asio::error_code& ec); + +ASIO_DECL void freeaddrinfo(addrinfo_type* ai); + +ASIO_DECL asio::error_code getnameinfo( + const socket_addr_type* addr, std::size_t addrlen, + char* host, std::size_t hostlen, char* serv, + std::size_t servlen, int flags, asio::error_code& ec); + +ASIO_DECL asio::error_code sync_getnameinfo( + const socket_addr_type* addr, std::size_t addrlen, + char* host, std::size_t hostlen, char* serv, + std::size_t servlen, int sock_type, asio::error_code& ec); + +ASIO_DECL asio::error_code background_getnameinfo( + const weak_cancel_token_type& cancel_token, + const socket_addr_type* addr, std::size_t addrlen, + char* host, std::size_t hostlen, char* serv, + std::size_t servlen, int sock_type, asio::error_code& ec); + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +ASIO_DECL u_long_type network_to_host_long(u_long_type value); + +ASIO_DECL u_long_type host_to_network_long(u_long_type value); + +ASIO_DECL u_short_type network_to_host_short(u_short_type value); + +ASIO_DECL u_short_type host_to_network_short(u_short_type value); + +} // namespace socket_ops +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/socket_ops.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_SOCKET_OPS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_option.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_option.hpp new file mode 100644 index 00000000..682c9aad --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_option.hpp @@ -0,0 +1,316 @@ +// +// detail/socket_option.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOCKET_OPTION_HPP +#define ASIO_DETAIL_SOCKET_OPTION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { +namespace socket_option { + +// Helper template for implementing boolean-based options. +template +class boolean +{ +public: + // Default constructor. + boolean() + : value_(0) + { + } + + // Construct with a specific option value. + explicit boolean(bool v) + : value_(v ? 1 : 0) + { + } + + // Set the current value of the boolean. + boolean& operator=(bool v) + { + value_ = v ? 1 : 0; + return *this; + } + + // Get the current value of the boolean. + bool value() const + { + return !!value_; + } + + // Convert to bool. + operator bool() const + { + return !!value_; + } + + // Test for false. + bool operator!() const + { + return !value_; + } + + // Get the level of the socket option. + template + int level(const Protocol&) const + { + return Level; + } + + // Get the name of the socket option. + template + int name(const Protocol&) const + { + return Name; + } + + // Get the address of the boolean data. + template + int* data(const Protocol&) + { + return &value_; + } + + // Get the address of the boolean data. + template + const int* data(const Protocol&) const + { + return &value_; + } + + // Get the size of the boolean data. + template + std::size_t size(const Protocol&) const + { + return sizeof(value_); + } + + // Set the size of the boolean data. + template + void resize(const Protocol&, std::size_t s) + { + // On some platforms (e.g. Windows Vista), the getsockopt function will + // return the size of a boolean socket option as one byte, even though a + // four byte integer was passed in. + switch (s) + { + case sizeof(char): + value_ = *reinterpret_cast(&value_) ? 1 : 0; + break; + case sizeof(value_): + break; + default: + { + std::length_error ex("boolean socket option resize"); + asio::detail::throw_exception(ex); + } + } + } + +private: + int value_; +}; + +// Helper template for implementing integer options. +template +class integer +{ +public: + // Default constructor. + integer() + : value_(0) + { + } + + // Construct with a specific option value. + explicit integer(int v) + : value_(v) + { + } + + // Set the value of the int option. + integer& operator=(int v) + { + value_ = v; + return *this; + } + + // Get the current value of the int option. + int value() const + { + return value_; + } + + // Get the level of the socket option. + template + int level(const Protocol&) const + { + return Level; + } + + // Get the name of the socket option. + template + int name(const Protocol&) const + { + return Name; + } + + // Get the address of the int data. + template + int* data(const Protocol&) + { + return &value_; + } + + // Get the address of the int data. + template + const int* data(const Protocol&) const + { + return &value_; + } + + // Get the size of the int data. + template + std::size_t size(const Protocol&) const + { + return sizeof(value_); + } + + // Set the size of the int data. + template + void resize(const Protocol&, std::size_t s) + { + if (s != sizeof(value_)) + { + std::length_error ex("integer socket option resize"); + asio::detail::throw_exception(ex); + } + } + +private: + int value_; +}; + +// Helper template for implementing linger options. +template +class linger +{ +public: + // Default constructor. + linger() + { + value_.l_onoff = 0; + value_.l_linger = 0; + } + + // Construct with specific option values. + linger(bool e, int t) + { + enabled(e); + timeout ASIO_PREVENT_MACRO_SUBSTITUTION(t); + } + + // Set the value for whether linger is enabled. + void enabled(bool value) + { + value_.l_onoff = value ? 1 : 0; + } + + // Get the value for whether linger is enabled. + bool enabled() const + { + return value_.l_onoff != 0; + } + + // Set the value for the linger timeout. + void timeout ASIO_PREVENT_MACRO_SUBSTITUTION(int value) + { +#if defined(WIN32) + value_.l_linger = static_cast(value); +#else + value_.l_linger = value; +#endif + } + + // Get the value for the linger timeout. + int timeout ASIO_PREVENT_MACRO_SUBSTITUTION() const + { + return static_cast(value_.l_linger); + } + + // Get the level of the socket option. + template + int level(const Protocol&) const + { + return Level; + } + + // Get the name of the socket option. + template + int name(const Protocol&) const + { + return Name; + } + + // Get the address of the linger data. + template + detail::linger_type* data(const Protocol&) + { + return &value_; + } + + // Get the address of the linger data. + template + const detail::linger_type* data(const Protocol&) const + { + return &value_; + } + + // Get the size of the linger data. + template + std::size_t size(const Protocol&) const + { + return sizeof(value_); + } + + // Set the size of the int data. + template + void resize(const Protocol&, std::size_t s) + { + if (s != sizeof(value_)) + { + std::length_error ex("linger socket option resize"); + asio::detail::throw_exception(ex); + } + } + +private: + detail::linger_type value_; +}; + +} // namespace socket_option +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SOCKET_OPTION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_select_interrupter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_select_interrupter.hpp new file mode 100644 index 00000000..92ad167d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_select_interrupter.hpp @@ -0,0 +1,93 @@ +// +// detail/socket_select_interrupter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOCKET_SELECT_INTERRUPTER_HPP +#define ASIO_DETAIL_SOCKET_SELECT_INTERRUPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_WINDOWS_RUNTIME) + +#if defined(ASIO_WINDOWS) \ + || defined(__CYGWIN__) \ + || defined(__SYMBIAN32__) \ + || defined(ESP_PLATFORM) + +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class socket_select_interrupter +{ +public: + // Constructor. + ASIO_DECL socket_select_interrupter(); + + // Destructor. + ASIO_DECL ~socket_select_interrupter(); + + // Recreate the interrupter's descriptors. Used after a fork. + ASIO_DECL void recreate(); + + // Interrupt the select call. + ASIO_DECL void interrupt(); + + // Reset the select interrupt. Returns true if the call was interrupted. + ASIO_DECL bool reset(); + + // Get the read descriptor to be passed to select. + socket_type read_descriptor() const + { + return read_descriptor_; + } + +private: + // Open the descriptors. Throws on error. + ASIO_DECL void open_descriptors(); + + // Close the descriptors. + ASIO_DECL void close_descriptors(); + + // The read end of a connection used to interrupt the select call. This file + // descriptor is passed to select such that when it is time to stop, a single + // byte will be written on the other end of the connection and this + // descriptor will become readable. + socket_type read_descriptor_; + + // The write end of a connection used to interrupt the select call. A single + // byte may be written to this to wake up the select which is waiting for the + // other end to become readable. + socket_type write_descriptor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/socket_select_interrupter.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + // || defined(__CYGWIN__) + // || defined(__SYMBIAN32__) + // || defined(ESP_PLATFORM) + +#endif // !defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_SOCKET_SELECT_INTERRUPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_types.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_types.hpp new file mode 100644 index 00000000..1e387070 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/socket_types.hpp @@ -0,0 +1,419 @@ +// +// detail/socket_types.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOCKET_TYPES_HPP +#define ASIO_DETAIL_SOCKET_TYPES_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +// Empty. +#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# if defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) +# error WinSock.h has already been included +# endif // defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_) +# if defined(__BORLANDC__) +# include // Needed for __errno +# if !defined(_WSPIAPI_H_) +# define _WSPIAPI_H_ +# define ASIO_WSPIAPI_H_DEFINED +# endif // !defined(_WSPIAPI_H_) +# endif // defined(__BORLANDC__) +# include +# include +# if defined(WINAPI_FAMILY) +# if ((WINAPI_FAMILY & WINAPI_PARTITION_DESKTOP) != 0) +# include +# endif // ((WINAPI_FAMILY & WINAPI_PARTITION_DESKTOP) != 0) +# endif // defined(WINAPI_FAMILY) +# if !defined(ASIO_WINDOWS_APP) +# include +# endif // !defined(ASIO_WINDOWS_APP) +# if defined(ASIO_WSPIAPI_H_DEFINED) +# undef _WSPIAPI_H_ +# undef ASIO_WSPIAPI_H_DEFINED +# endif // defined(ASIO_WSPIAPI_H_DEFINED) +# if !defined(ASIO_NO_DEFAULT_LINKED_LIBS) +# if defined(UNDER_CE) +# pragma comment(lib, "ws2.lib") +# elif defined(_MSC_VER) || defined(__BORLANDC__) +# pragma comment(lib, "ws2_32.lib") +# if !defined(ASIO_WINDOWS_APP) +# pragma comment(lib, "mswsock.lib") +# endif // !defined(ASIO_WINDOWS_APP) +# endif // defined(_MSC_VER) || defined(__BORLANDC__) +# endif // !defined(ASIO_NO_DEFAULT_LINKED_LIBS) +# include "asio/detail/old_win_sdk_compat.hpp" +#else +# include +# if (defined(__MACH__) && defined(__APPLE__)) \ + || defined(__FreeBSD__) || defined(__NetBSD__) \ + || defined(__OpenBSD__) || defined(__linux__) \ + || defined(__EMSCRIPTEN__) +# include +# elif !defined(__SYMBIAN32__) +# include +# endif +# include +# include +# include +# if defined(__hpux) +# include +# endif +# if !defined(__hpux) || defined(__SELECT) +# include +# endif +# include +# include +# include +# include +# if !defined(__SYMBIAN32__) && !defined(ESP_PLATFORM) +# include +# endif +# include +# include +# include +# if defined(ESP_PLATFORM) +# include "esp_exception.h" +# endif +# include +# if defined(__sun) +# include +# include +# endif +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_WINDOWS_RUNTIME) +const int max_addr_v4_str_len = 256; +const int max_addr_v6_str_len = 256; +typedef unsigned __int32 u_long_type; +typedef unsigned __int16 u_short_type; +struct in4_addr_type { u_long_type s_addr; }; +struct in4_mreq_type { in4_addr_type imr_multiaddr, imr_interface; }; +struct in6_addr_type { unsigned char s6_addr[16]; }; +struct in6_mreq_type { in6_addr_type ipv6mr_multiaddr; + unsigned long ipv6mr_interface; }; +struct socket_addr_type { int sa_family; }; +struct sockaddr_in4_type { int sin_family; + in4_addr_type sin_addr; u_short_type sin_port; }; +struct sockaddr_in6_type { int sin6_family; + in6_addr_type sin6_addr; u_short_type sin6_port; + u_long_type sin6_flowinfo; u_long_type sin6_scope_id; }; +struct sockaddr_storage_type { int ss_family; + unsigned char ss_bytes[128 - sizeof(int)]; }; +struct addrinfo_type { int ai_flags; + int ai_family, ai_socktype, ai_protocol; + int ai_addrlen; const void* ai_addr; + const char* ai_canonname; addrinfo_type* ai_next; }; +struct linger_type { u_short_type l_onoff, l_linger; }; +typedef u_long_type ioctl_arg_type; +typedef int signed_size_type; +# define ASIO_OS_DEF(c) ASIO_OS_DEF_##c +# define ASIO_OS_DEF_AF_UNSPEC 0 +# define ASIO_OS_DEF_AF_INET 2 +# define ASIO_OS_DEF_AF_INET6 23 +# define ASIO_OS_DEF_SOCK_STREAM 1 +# define ASIO_OS_DEF_SOCK_DGRAM 2 +# define ASIO_OS_DEF_SOCK_RAW 3 +# define ASIO_OS_DEF_SOCK_SEQPACKET 5 +# define ASIO_OS_DEF_IPPROTO_IP 0 +# define ASIO_OS_DEF_IPPROTO_IPV6 41 +# define ASIO_OS_DEF_IPPROTO_TCP 6 +# define ASIO_OS_DEF_IPPROTO_UDP 17 +# define ASIO_OS_DEF_IPPROTO_ICMP 1 +# define ASIO_OS_DEF_IPPROTO_ICMPV6 58 +# define ASIO_OS_DEF_FIONBIO 1 +# define ASIO_OS_DEF_FIONREAD 2 +# define ASIO_OS_DEF_INADDR_ANY 0 +# define ASIO_OS_DEF_MSG_OOB 0x1 +# define ASIO_OS_DEF_MSG_PEEK 0x2 +# define ASIO_OS_DEF_MSG_DONTROUTE 0x4 +# define ASIO_OS_DEF_MSG_EOR 0 // Not supported. +# define ASIO_OS_DEF_SHUT_RD 0x0 +# define ASIO_OS_DEF_SHUT_WR 0x1 +# define ASIO_OS_DEF_SHUT_RDWR 0x2 +# define ASIO_OS_DEF_SOMAXCONN 0x7fffffff +# define ASIO_OS_DEF_SOL_SOCKET 0xffff +# define ASIO_OS_DEF_SO_BROADCAST 0x20 +# define ASIO_OS_DEF_SO_DEBUG 0x1 +# define ASIO_OS_DEF_SO_DONTROUTE 0x10 +# define ASIO_OS_DEF_SO_KEEPALIVE 0x8 +# define ASIO_OS_DEF_SO_LINGER 0x80 +# define ASIO_OS_DEF_SO_OOBINLINE 0x100 +# define ASIO_OS_DEF_SO_SNDBUF 0x1001 +# define ASIO_OS_DEF_SO_RCVBUF 0x1002 +# define ASIO_OS_DEF_SO_SNDLOWAT 0x1003 +# define ASIO_OS_DEF_SO_RCVLOWAT 0x1004 +# define ASIO_OS_DEF_SO_REUSEADDR 0x4 +# define ASIO_OS_DEF_TCP_NODELAY 0x1 +# define ASIO_OS_DEF_IP_MULTICAST_IF 2 +# define ASIO_OS_DEF_IP_MULTICAST_TTL 3 +# define ASIO_OS_DEF_IP_MULTICAST_LOOP 4 +# define ASIO_OS_DEF_IP_ADD_MEMBERSHIP 5 +# define ASIO_OS_DEF_IP_DROP_MEMBERSHIP 6 +# define ASIO_OS_DEF_IP_TTL 7 +# define ASIO_OS_DEF_IPV6_UNICAST_HOPS 4 +# define ASIO_OS_DEF_IPV6_MULTICAST_IF 9 +# define ASIO_OS_DEF_IPV6_MULTICAST_HOPS 10 +# define ASIO_OS_DEF_IPV6_MULTICAST_LOOP 11 +# define ASIO_OS_DEF_IPV6_JOIN_GROUP 12 +# define ASIO_OS_DEF_IPV6_LEAVE_GROUP 13 +# define ASIO_OS_DEF_AI_CANONNAME 0x2 +# define ASIO_OS_DEF_AI_PASSIVE 0x1 +# define ASIO_OS_DEF_AI_NUMERICHOST 0x4 +# define ASIO_OS_DEF_AI_NUMERICSERV 0x8 +# define ASIO_OS_DEF_AI_V4MAPPED 0x800 +# define ASIO_OS_DEF_AI_ALL 0x100 +# define ASIO_OS_DEF_AI_ADDRCONFIG 0x400 +#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) +typedef SOCKET socket_type; +const SOCKET invalid_socket = INVALID_SOCKET; +const int socket_error_retval = SOCKET_ERROR; +const int max_addr_v4_str_len = 256; +const int max_addr_v6_str_len = 256; +typedef sockaddr socket_addr_type; +typedef in_addr in4_addr_type; +typedef ip_mreq in4_mreq_type; +typedef sockaddr_in sockaddr_in4_type; +# if defined(ASIO_HAS_OLD_WIN_SDK) +typedef in6_addr_emulation in6_addr_type; +typedef ipv6_mreq_emulation in6_mreq_type; +typedef sockaddr_in6_emulation sockaddr_in6_type; +typedef sockaddr_storage_emulation sockaddr_storage_type; +typedef addrinfo_emulation addrinfo_type; +# else +typedef in6_addr in6_addr_type; +typedef ipv6_mreq in6_mreq_type; +typedef sockaddr_in6 sockaddr_in6_type; +typedef sockaddr_storage sockaddr_storage_type; +typedef addrinfo addrinfo_type; +# endif +typedef ::linger linger_type; +typedef unsigned long ioctl_arg_type; +typedef u_long u_long_type; +typedef u_short u_short_type; +typedef int signed_size_type; +# define ASIO_OS_DEF(c) ASIO_OS_DEF_##c +# define ASIO_OS_DEF_AF_UNSPEC AF_UNSPEC +# define ASIO_OS_DEF_AF_INET AF_INET +# define ASIO_OS_DEF_AF_INET6 AF_INET6 +# define ASIO_OS_DEF_SOCK_STREAM SOCK_STREAM +# define ASIO_OS_DEF_SOCK_DGRAM SOCK_DGRAM +# define ASIO_OS_DEF_SOCK_RAW SOCK_RAW +# define ASIO_OS_DEF_SOCK_SEQPACKET SOCK_SEQPACKET +# define ASIO_OS_DEF_IPPROTO_IP IPPROTO_IP +# define ASIO_OS_DEF_IPPROTO_IPV6 IPPROTO_IPV6 +# define ASIO_OS_DEF_IPPROTO_TCP IPPROTO_TCP +# define ASIO_OS_DEF_IPPROTO_UDP IPPROTO_UDP +# define ASIO_OS_DEF_IPPROTO_ICMP IPPROTO_ICMP +# define ASIO_OS_DEF_IPPROTO_ICMPV6 IPPROTO_ICMPV6 +# define ASIO_OS_DEF_FIONBIO FIONBIO +# define ASIO_OS_DEF_FIONREAD FIONREAD +# define ASIO_OS_DEF_INADDR_ANY INADDR_ANY +# define ASIO_OS_DEF_MSG_OOB MSG_OOB +# define ASIO_OS_DEF_MSG_PEEK MSG_PEEK +# define ASIO_OS_DEF_MSG_DONTROUTE MSG_DONTROUTE +# define ASIO_OS_DEF_MSG_EOR 0 // Not supported on Windows. +# define ASIO_OS_DEF_SHUT_RD SD_RECEIVE +# define ASIO_OS_DEF_SHUT_WR SD_SEND +# define ASIO_OS_DEF_SHUT_RDWR SD_BOTH +# define ASIO_OS_DEF_SOMAXCONN SOMAXCONN +# define ASIO_OS_DEF_SOL_SOCKET SOL_SOCKET +# define ASIO_OS_DEF_SO_BROADCAST SO_BROADCAST +# define ASIO_OS_DEF_SO_DEBUG SO_DEBUG +# define ASIO_OS_DEF_SO_DONTROUTE SO_DONTROUTE +# define ASIO_OS_DEF_SO_KEEPALIVE SO_KEEPALIVE +# define ASIO_OS_DEF_SO_LINGER SO_LINGER +# define ASIO_OS_DEF_SO_OOBINLINE SO_OOBINLINE +# define ASIO_OS_DEF_SO_SNDBUF SO_SNDBUF +# define ASIO_OS_DEF_SO_RCVBUF SO_RCVBUF +# define ASIO_OS_DEF_SO_SNDLOWAT SO_SNDLOWAT +# define ASIO_OS_DEF_SO_RCVLOWAT SO_RCVLOWAT +# define ASIO_OS_DEF_SO_REUSEADDR SO_REUSEADDR +# define ASIO_OS_DEF_TCP_NODELAY TCP_NODELAY +# define ASIO_OS_DEF_IP_MULTICAST_IF IP_MULTICAST_IF +# define ASIO_OS_DEF_IP_MULTICAST_TTL IP_MULTICAST_TTL +# define ASIO_OS_DEF_IP_MULTICAST_LOOP IP_MULTICAST_LOOP +# define ASIO_OS_DEF_IP_ADD_MEMBERSHIP IP_ADD_MEMBERSHIP +# define ASIO_OS_DEF_IP_DROP_MEMBERSHIP IP_DROP_MEMBERSHIP +# define ASIO_OS_DEF_IP_TTL IP_TTL +# define ASIO_OS_DEF_IPV6_UNICAST_HOPS IPV6_UNICAST_HOPS +# define ASIO_OS_DEF_IPV6_MULTICAST_IF IPV6_MULTICAST_IF +# define ASIO_OS_DEF_IPV6_MULTICAST_HOPS IPV6_MULTICAST_HOPS +# define ASIO_OS_DEF_IPV6_MULTICAST_LOOP IPV6_MULTICAST_LOOP +# define ASIO_OS_DEF_IPV6_JOIN_GROUP IPV6_JOIN_GROUP +# define ASIO_OS_DEF_IPV6_LEAVE_GROUP IPV6_LEAVE_GROUP +# define ASIO_OS_DEF_AI_CANONNAME AI_CANONNAME +# define ASIO_OS_DEF_AI_PASSIVE AI_PASSIVE +# define ASIO_OS_DEF_AI_NUMERICHOST AI_NUMERICHOST +# if defined(AI_NUMERICSERV) +# define ASIO_OS_DEF_AI_NUMERICSERV AI_NUMERICSERV +# else +# define ASIO_OS_DEF_AI_NUMERICSERV 0 +# endif +# if defined(AI_V4MAPPED) +# define ASIO_OS_DEF_AI_V4MAPPED AI_V4MAPPED +# else +# define ASIO_OS_DEF_AI_V4MAPPED 0 +# endif +# if defined(AI_ALL) +# define ASIO_OS_DEF_AI_ALL AI_ALL +# else +# define ASIO_OS_DEF_AI_ALL 0 +# endif +# if defined(AI_ADDRCONFIG) +# define ASIO_OS_DEF_AI_ADDRCONFIG AI_ADDRCONFIG +# else +# define ASIO_OS_DEF_AI_ADDRCONFIG 0 +# endif +# if defined (_WIN32_WINNT) +const int max_iov_len = 64; +# else +const int max_iov_len = 16; +# endif +#else +typedef int socket_type; +const int invalid_socket = -1; +const int socket_error_retval = -1; +const int max_addr_v4_str_len = INET_ADDRSTRLEN; +#if defined(INET6_ADDRSTRLEN) +const int max_addr_v6_str_len = INET6_ADDRSTRLEN + 1 + IF_NAMESIZE; +#else // defined(INET6_ADDRSTRLEN) +const int max_addr_v6_str_len = 256; +#endif // defined(INET6_ADDRSTRLEN) +typedef sockaddr socket_addr_type; +typedef in_addr in4_addr_type; +# if defined(__hpux) +// HP-UX doesn't provide ip_mreq when _XOPEN_SOURCE_EXTENDED is defined. +struct in4_mreq_type +{ + struct in_addr imr_multiaddr; + struct in_addr imr_interface; +}; +# else +typedef ip_mreq in4_mreq_type; +# endif +typedef sockaddr_in sockaddr_in4_type; +typedef in6_addr in6_addr_type; +typedef ipv6_mreq in6_mreq_type; +typedef sockaddr_in6 sockaddr_in6_type; +typedef sockaddr_storage sockaddr_storage_type; +typedef sockaddr_un sockaddr_un_type; +typedef addrinfo addrinfo_type; +typedef ::linger linger_type; +typedef int ioctl_arg_type; +typedef uint32_t u_long_type; +typedef uint16_t u_short_type; +#if defined(ASIO_HAS_SSIZE_T) +typedef ssize_t signed_size_type; +#else // defined(ASIO_HAS_SSIZE_T) +typedef int signed_size_type; +#endif // defined(ASIO_HAS_SSIZE_T) +# define ASIO_OS_DEF(c) ASIO_OS_DEF_##c +# define ASIO_OS_DEF_AF_UNSPEC AF_UNSPEC +# define ASIO_OS_DEF_AF_INET AF_INET +# define ASIO_OS_DEF_AF_INET6 AF_INET6 +# define ASIO_OS_DEF_SOCK_STREAM SOCK_STREAM +# define ASIO_OS_DEF_SOCK_DGRAM SOCK_DGRAM +# define ASIO_OS_DEF_SOCK_RAW SOCK_RAW +# define ASIO_OS_DEF_SOCK_SEQPACKET SOCK_SEQPACKET +# define ASIO_OS_DEF_IPPROTO_IP IPPROTO_IP +# define ASIO_OS_DEF_IPPROTO_IPV6 IPPROTO_IPV6 +# define ASIO_OS_DEF_IPPROTO_TCP IPPROTO_TCP +# define ASIO_OS_DEF_IPPROTO_UDP IPPROTO_UDP +# define ASIO_OS_DEF_IPPROTO_ICMP IPPROTO_ICMP +# define ASIO_OS_DEF_IPPROTO_ICMPV6 IPPROTO_ICMPV6 +# define ASIO_OS_DEF_FIONBIO FIONBIO +# define ASIO_OS_DEF_FIONREAD FIONREAD +# define ASIO_OS_DEF_INADDR_ANY INADDR_ANY +# define ASIO_OS_DEF_MSG_OOB MSG_OOB +# define ASIO_OS_DEF_MSG_PEEK MSG_PEEK +# define ASIO_OS_DEF_MSG_DONTROUTE MSG_DONTROUTE +# define ASIO_OS_DEF_MSG_EOR MSG_EOR +# define ASIO_OS_DEF_SHUT_RD SHUT_RD +# define ASIO_OS_DEF_SHUT_WR SHUT_WR +# define ASIO_OS_DEF_SHUT_RDWR SHUT_RDWR +# define ASIO_OS_DEF_SOMAXCONN SOMAXCONN +# define ASIO_OS_DEF_SOL_SOCKET SOL_SOCKET +# define ASIO_OS_DEF_SO_BROADCAST SO_BROADCAST +# define ASIO_OS_DEF_SO_DEBUG SO_DEBUG +# define ASIO_OS_DEF_SO_DONTROUTE SO_DONTROUTE +# define ASIO_OS_DEF_SO_KEEPALIVE SO_KEEPALIVE +# define ASIO_OS_DEF_SO_LINGER SO_LINGER +# define ASIO_OS_DEF_SO_OOBINLINE SO_OOBINLINE +# define ASIO_OS_DEF_SO_SNDBUF SO_SNDBUF +# define ASIO_OS_DEF_SO_RCVBUF SO_RCVBUF +# define ASIO_OS_DEF_SO_SNDLOWAT SO_SNDLOWAT +# define ASIO_OS_DEF_SO_RCVLOWAT SO_RCVLOWAT +# define ASIO_OS_DEF_SO_REUSEADDR SO_REUSEADDR +# define ASIO_OS_DEF_TCP_NODELAY TCP_NODELAY +# define ASIO_OS_DEF_IP_MULTICAST_IF IP_MULTICAST_IF +# define ASIO_OS_DEF_IP_MULTICAST_TTL IP_MULTICAST_TTL +# define ASIO_OS_DEF_IP_MULTICAST_LOOP IP_MULTICAST_LOOP +# define ASIO_OS_DEF_IP_ADD_MEMBERSHIP IP_ADD_MEMBERSHIP +# define ASIO_OS_DEF_IP_DROP_MEMBERSHIP IP_DROP_MEMBERSHIP +# define ASIO_OS_DEF_IP_TTL IP_TTL +# define ASIO_OS_DEF_IPV6_UNICAST_HOPS IPV6_UNICAST_HOPS +# define ASIO_OS_DEF_IPV6_MULTICAST_IF IPV6_MULTICAST_IF +# define ASIO_OS_DEF_IPV6_MULTICAST_HOPS IPV6_MULTICAST_HOPS +# define ASIO_OS_DEF_IPV6_MULTICAST_LOOP IPV6_MULTICAST_LOOP +# define ASIO_OS_DEF_IPV6_JOIN_GROUP IPV6_JOIN_GROUP +# define ASIO_OS_DEF_IPV6_LEAVE_GROUP IPV6_LEAVE_GROUP +# define ASIO_OS_DEF_AI_CANONNAME AI_CANONNAME +# define ASIO_OS_DEF_AI_PASSIVE AI_PASSIVE +# define ASIO_OS_DEF_AI_NUMERICHOST AI_NUMERICHOST +# if defined(AI_NUMERICSERV) +# define ASIO_OS_DEF_AI_NUMERICSERV AI_NUMERICSERV +# else +# define ASIO_OS_DEF_AI_NUMERICSERV 0 +# endif +// Note: QNX Neutrino 6.3 defines AI_V4MAPPED, AI_ALL and AI_ADDRCONFIG but +// does not implement them. Therefore they are specifically excluded here. +# if defined(AI_V4MAPPED) && !defined(__QNXNTO__) +# define ASIO_OS_DEF_AI_V4MAPPED AI_V4MAPPED +# else +# define ASIO_OS_DEF_AI_V4MAPPED 0 +# endif +# if defined(AI_ALL) && !defined(__QNXNTO__) +# define ASIO_OS_DEF_AI_ALL AI_ALL +# else +# define ASIO_OS_DEF_AI_ALL 0 +# endif +# if defined(AI_ADDRCONFIG) && !defined(__QNXNTO__) +# define ASIO_OS_DEF_AI_ADDRCONFIG AI_ADDRCONFIG +# else +# define ASIO_OS_DEF_AI_ADDRCONFIG 0 +# endif +# if defined(IOV_MAX) +const int max_iov_len = IOV_MAX; +# else +// POSIX platforms are not required to define IOV_MAX. +const int max_iov_len = 16; +# endif +#endif +const int custom_socket_option_level = 0xA5100000; +const int enable_connection_aborted_option = 1; +const int always_fail_option = 2; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_SOCKET_TYPES_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/solaris_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/solaris_fenced_block.hpp new file mode 100644 index 00000000..f7b9f94f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/solaris_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/solaris_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_SOLARIS_FENCED_BLOCK_HPP +#define ASIO_DETAIL_SOLARIS_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(__sun) + +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class solaris_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit solaris_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit solaris_fenced_block(full_t) + { + membar_consumer(); + } + + // Destructor. + ~solaris_fenced_block() + { + membar_producer(); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(__sun) + +#endif // ASIO_DETAIL_SOLARIS_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/static_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/static_mutex.hpp new file mode 100644 index 00000000..6e598e6b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/static_mutex.hpp @@ -0,0 +1,52 @@ +// +// detail/static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STATIC_MUTEX_HPP +#define ASIO_DETAIL_STATIC_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_static_mutex.hpp" +#elif defined(ASIO_WINDOWS) +# include "asio/detail/win_static_mutex.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_static_mutex.hpp" +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +# include "asio/detail/std_static_mutex.hpp" +#else +# error Only Windows and POSIX are supported! +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) +typedef null_static_mutex static_mutex; +# define ASIO_STATIC_MUTEX_INIT ASIO_NULL_STATIC_MUTEX_INIT +#elif defined(ASIO_WINDOWS) +typedef win_static_mutex static_mutex; +# define ASIO_STATIC_MUTEX_INIT ASIO_WIN_STATIC_MUTEX_INIT +#elif defined(ASIO_HAS_PTHREADS) +typedef posix_static_mutex static_mutex; +# define ASIO_STATIC_MUTEX_INIT ASIO_POSIX_STATIC_MUTEX_INIT +#elif defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) +typedef std_static_mutex static_mutex; +# define ASIO_STATIC_MUTEX_INIT ASIO_STD_STATIC_MUTEX_INIT +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_STATIC_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_event.hpp new file mode 100644 index 00000000..4252a9e7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_event.hpp @@ -0,0 +1,176 @@ +// +// detail/std_event.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_EVENT_HPP +#define ASIO_DETAIL_STD_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#include +#include +#include "asio/detail/assert.hpp" +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class std_event + : private noncopyable +{ +public: + // Constructor. + std_event() + : state_(0) + { + } + + // Destructor. + ~std_event() + { + } + + // Signal the event. (Retained for backward compatibility.) + template + void signal(Lock& lock) + { + this->signal_all(lock); + } + + // Signal all waiters. + template + void signal_all(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + state_ |= 1; + cond_.notify_all(); + } + + // Unlock the mutex and signal one waiter. + template + void unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + bool have_waiters = (state_ > 1); + lock.unlock(); + if (have_waiters) + cond_.notify_one(); + } + + // If there's a waiter, unlock the mutex and signal it. + template + bool maybe_unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + if (state_ > 1) + { + lock.unlock(); + cond_.notify_one(); + return true; + } + return false; + } + + // Reset the event. + template + void clear(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + state_ &= ~std::size_t(1); + } + + // Wait for the event to become signalled. + template + void wait(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + unique_lock_adapter u_lock(lock); + while ((state_ & 1) == 0) + { + waiter w(state_); + cond_.wait(u_lock.unique_lock_); + } + } + + // Timed wait for the event to become signalled. + template + bool wait_for_usec(Lock& lock, long usec) + { + ASIO_ASSERT(lock.locked()); + unique_lock_adapter u_lock(lock); + if ((state_ & 1) == 0) + { + waiter w(state_); + cond_.wait_for(u_lock.unique_lock_, std::chrono::microseconds(usec)); + } + return (state_ & 1) != 0; + } + +private: + // Helper class to temporarily adapt a scoped_lock into a unique_lock so that + // it can be passed to std::condition_variable::wait(). + struct unique_lock_adapter + { + template + explicit unique_lock_adapter(Lock& lock) + : unique_lock_(lock.mutex().mutex_, std::adopt_lock) + { + } + + ~unique_lock_adapter() + { + unique_lock_.release(); + } + + std::unique_lock unique_lock_; + }; + + // Helper to increment and decrement the state to track outstanding waiters. + class waiter + { + public: + explicit waiter(std::size_t& state) + : state_(state) + { + state_ += 2; + } + + ~waiter() + { + state_ -= 2; + } + + private: + std::size_t& state_; + }; + + std::condition_variable cond_; + std::size_t state_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#endif // ASIO_DETAIL_STD_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_fenced_block.hpp new file mode 100644 index 00000000..a6ddbc81 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_fenced_block.hpp @@ -0,0 +1,62 @@ +// +// detail/std_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_FENCED_BLOCK_HPP +#define ASIO_DETAIL_STD_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_ATOMIC) + +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class std_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit std_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit std_fenced_block(full_t) + { + std::atomic_thread_fence(std::memory_order_acquire); + } + + // Destructor. + ~std_fenced_block() + { + std::atomic_thread_fence(std::memory_order_release); + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_ATOMIC) + +#endif // ASIO_DETAIL_STD_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_global.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_global.hpp new file mode 100644 index 00000000..0b7eec0f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_global.hpp @@ -0,0 +1,70 @@ +// +// detail/std_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_GLOBAL_HPP +#define ASIO_DETAIL_STD_GLOBAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_CALL_ONCE) + +#include +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct std_global_impl +{ + // Helper function to perform initialisation. + static void do_init() + { + instance_.ptr_ = new T; + } + + // Destructor automatically cleans up the global. + ~std_global_impl() + { + delete ptr_; + } + + static std::once_flag init_once_; + static std_global_impl instance_; + T* ptr_; +}; + +template +std::once_flag std_global_impl::init_once_; + +template +std_global_impl std_global_impl::instance_; + +template +T& std_global() +{ + std::call_once(std_global_impl::init_once_, &std_global_impl::do_init); + return *std_global_impl::instance_.ptr_; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_CALL_ONCE) + +#endif // ASIO_DETAIL_STD_GLOBAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_mutex.hpp new file mode 100644 index 00000000..69509a39 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_mutex.hpp @@ -0,0 +1,73 @@ +// +// detail/std_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_MUTEX_HPP +#define ASIO_DETAIL_STD_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class std_event; + +class std_mutex + : private noncopyable +{ +public: + typedef asio::detail::scoped_lock scoped_lock; + + // Constructor. + std_mutex() + { + } + + // Destructor. + ~std_mutex() + { + } + + // Lock the mutex. + void lock() + { + mutex_.lock(); + } + + // Unlock the mutex. + void unlock() + { + mutex_.unlock(); + } + +private: + friend class std_event; + std::mutex mutex_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#endif // ASIO_DETAIL_STD_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_static_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_static_mutex.hpp new file mode 100644 index 00000000..c92acf98 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_static_mutex.hpp @@ -0,0 +1,81 @@ +// +// detail/std_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_STATIC_MUTEX_HPP +#define ASIO_DETAIL_STD_STATIC_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class std_event; + +class std_static_mutex + : private noncopyable +{ +public: + typedef asio::detail::scoped_lock scoped_lock; + + // Constructor. + std_static_mutex(int) + { + } + + // Destructor. + ~std_static_mutex() + { + } + + // Initialise the mutex. + void init() + { + // Nothing to do. + } + + // Lock the mutex. + void lock() + { + mutex_.lock(); + } + + // Unlock the mutex. + void unlock() + { + mutex_.unlock(); + } + +private: + friend class std_event; + std::mutex mutex_; +}; + +#define ASIO_STD_STATIC_MUTEX_INIT 0 + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_MUTEX_AND_CONDVAR) + +#endif // ASIO_DETAIL_STD_STATIC_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_thread.hpp new file mode 100644 index 00000000..a73a6f92 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/std_thread.hpp @@ -0,0 +1,71 @@ +// +// detail/std_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STD_THREAD_HPP +#define ASIO_DETAIL_STD_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_THREAD) + +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class std_thread + : private noncopyable +{ +public: + // Constructor. + template + std_thread(Function f, unsigned int = 0) + : thread_(f) + { + } + + // Destructor. + ~std_thread() + { + join(); + } + + // Wait for the thread to exit. + void join() + { + if (thread_.joinable()) + thread_.join(); + } + + // Get number of CPUs. + static std::size_t hardware_concurrency() + { + return std::thread::hardware_concurrency(); + } + +private: + std::thread thread_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_THREAD) + +#endif // ASIO_DETAIL_STD_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_executor_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_executor_service.hpp new file mode 100644 index 00000000..dd513cbe --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_executor_service.hpp @@ -0,0 +1,142 @@ +// +// detail/strand_executor_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STRAND_EXECUTOR_SERVICE_HPP +#define ASIO_DETAIL_STRAND_EXECUTOR_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/executor_op.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/scheduler_operation.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Default service implementation for a strand. +class strand_executor_service + : public execution_context_service_base +{ +public: + // The underlying implementation of a strand. + class strand_impl + { + public: + ASIO_DECL ~strand_impl(); + + private: + friend class strand_executor_service; + + // Mutex to protect access to internal data. + mutex* mutex_; + + // Indicates whether the strand is currently "locked" by a handler. This + // means that there is a handler upcall in progress, or that the strand + // itself has been scheduled in order to invoke some pending handlers. + bool locked_; + + // Indicates that the strand has been shut down and will accept no further + // handlers. + bool shutdown_; + + // The handlers that are waiting on the strand but should not be run until + // after the next time the strand is scheduled. This queue must only be + // modified while the mutex is locked. + op_queue waiting_queue_; + + // The handlers that are ready to be run. Logically speaking, these are the + // handlers that hold the strand's lock. The ready queue is only modified + // from within the strand and so may be accessed without locking the mutex. + op_queue ready_queue_; + + // Pointers to adjacent handle implementations in linked list. + strand_impl* next_; + strand_impl* prev_; + + // The strand service in where the implementation is held. + strand_executor_service* service_; + }; + + typedef shared_ptr implementation_type; + + // Construct a new strand service for the specified context. + ASIO_DECL explicit strand_executor_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Create a new strand_executor implementation. + ASIO_DECL implementation_type create_implementation(); + + // Request invocation of the given function. + template + static void dispatch(const implementation_type& impl, Executor& ex, + ASIO_MOVE_ARG(Function) function, const Allocator& a); + + // Request invocation of the given function and return immediately. + template + static void post(const implementation_type& impl, Executor& ex, + ASIO_MOVE_ARG(Function) function, const Allocator& a); + + // Request invocation of the given function and return immediately. + template + static void defer(const implementation_type& impl, Executor& ex, + ASIO_MOVE_ARG(Function) function, const Allocator& a); + + // Determine whether the strand is running in the current thread. + ASIO_DECL static bool running_in_this_thread( + const implementation_type& impl); + +private: + friend class strand_impl; + template class invoker; + + // Adds a function to the strand. Returns true if it acquires the lock. + ASIO_DECL static bool enqueue(const implementation_type& impl, + scheduler_operation* op); + + // Mutex to protect access to the service-wide state. + mutex mutex_; + + // Number of mutexes shared between all strand objects. + enum { num_mutexes = 193 }; + + // Pool of mutexes. + scoped_ptr mutexes_[num_mutexes]; + + // Extra value used when hashing to prevent recycled memory locations from + // getting the same mutex. + std::size_t salt_; + + // The head of a linked list of all implementations. + strand_impl* impl_list_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/strand_executor_service.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/strand_executor_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_STRAND_EXECUTOR_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_service.hpp new file mode 100644 index 00000000..2c9c7c9d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/strand_service.hpp @@ -0,0 +1,142 @@ +// +// detail/strand_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STRAND_SERVICE_HPP +#define ASIO_DETAIL_STRAND_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/io_context.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/scoped_ptr.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Default service implementation for a strand. +class strand_service + : public asio::detail::service_base +{ +private: + // Helper class to re-post the strand on exit. + struct on_do_complete_exit; + + // Helper class to re-post the strand on exit. + struct on_dispatch_exit; + +public: + + // The underlying implementation of a strand. + class strand_impl + : public operation + { + public: + strand_impl(); + + private: + // Only this service will have access to the internal values. + friend class strand_service; + friend struct on_do_complete_exit; + friend struct on_dispatch_exit; + + // Mutex to protect access to internal data. + asio::detail::mutex mutex_; + + // Indicates whether the strand is currently "locked" by a handler. This + // means that there is a handler upcall in progress, or that the strand + // itself has been scheduled in order to invoke some pending handlers. + bool locked_; + + // The handlers that are waiting on the strand but should not be run until + // after the next time the strand is scheduled. This queue must only be + // modified while the mutex is locked. + op_queue waiting_queue_; + + // The handlers that are ready to be run. Logically speaking, these are the + // handlers that hold the strand's lock. The ready queue is only modified + // from within the strand and so may be accessed without locking the mutex. + op_queue ready_queue_; + }; + + typedef strand_impl* implementation_type; + + // Construct a new strand service for the specified io_context. + ASIO_DECL explicit strand_service(asio::io_context& io_context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new strand implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Request the io_context to invoke the given handler. + template + void dispatch(implementation_type& impl, Handler& handler); + + // Request the io_context to invoke the given handler and return immediately. + template + void post(implementation_type& impl, Handler& handler); + + // Determine whether the strand is running in the current thread. + ASIO_DECL bool running_in_this_thread( + const implementation_type& impl) const; + +private: + // Helper function to dispatch a handler. Returns true if the handler should + // be dispatched immediately. + ASIO_DECL bool do_dispatch(implementation_type& impl, operation* op); + + // Helper fiunction to post a handler. + ASIO_DECL void do_post(implementation_type& impl, + operation* op, bool is_continuation); + + ASIO_DECL static void do_complete(void* owner, + operation* base, const asio::error_code& ec, + std::size_t bytes_transferred); + + // The io_context implementation used to post completions. + io_context_impl& io_context_; + + // Mutex to protect access to the array of implementations. + asio::detail::mutex mutex_; + + // Number of implementations shared between all strand objects. +#if defined(ASIO_STRAND_IMPLEMENTATIONS) + enum { num_implementations = ASIO_STRAND_IMPLEMENTATIONS }; +#else // defined(ASIO_STRAND_IMPLEMENTATIONS) + enum { num_implementations = 193 }; +#endif // defined(ASIO_STRAND_IMPLEMENTATIONS) + + // Pool of implementations. + scoped_ptr implementations_[num_implementations]; + + // Extra value used when hashing to prevent recycled memory locations from + // getting the same strand implementation. + std::size_t salt_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/strand_service.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/strand_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_STRAND_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/string_view.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/string_view.hpp new file mode 100644 index 00000000..d59bf8a6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/string_view.hpp @@ -0,0 +1,47 @@ +// +// detail/string_view.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_STRING_VIEW_HPP +#define ASIO_DETAIL_STRING_VIEW_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STRING_VIEW) + +#if defined(ASIO_HAS_STD_STRING_VIEW) +# include +#elif defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +# include +#else // defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +# error ASIO_HAS_STRING_VIEW is set but no string_view is available +#endif // defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) + +namespace asio { + +#if defined(ASIO_HAS_STD_STRING_VIEW) +using std::basic_string_view; +using std::string_view; +#elif defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) +using std::experimental::basic_string_view; +using std::experimental::string_view; +#endif // defined(ASIO_HAS_STD_EXPERIMENTAL_STRING_VIEW) + +} // namespace asio + +# define ASIO_STRING_VIEW_PARAM asio::string_view +#else // defined(ASIO_HAS_STRING_VIEW) +# define ASIO_STRING_VIEW_PARAM const std::string& +#endif // defined(ASIO_HAS_STRING_VIEW) + +#endif // ASIO_DETAIL_STRING_VIEW_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread.hpp new file mode 100644 index 00000000..fe098046 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread.hpp @@ -0,0 +1,60 @@ +// +// detail/thread.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THREAD_HPP +#define ASIO_DETAIL_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_thread.hpp" +#elif defined(ASIO_WINDOWS) +# if defined(UNDER_CE) +# include "asio/detail/wince_thread.hpp" +# elif defined(ASIO_WINDOWS_APP) +# include "asio/detail/winapp_thread.hpp" +# else +# include "asio/detail/win_thread.hpp" +# endif +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_thread.hpp" +#elif defined(ASIO_HAS_STD_THREAD) +# include "asio/detail/std_thread.hpp" +#else +# error Only Windows, POSIX and std::thread are supported! +#endif + +namespace asio { +namespace detail { + +#if !defined(ASIO_HAS_THREADS) +typedef null_thread thread; +#elif defined(ASIO_WINDOWS) +# if defined(UNDER_CE) +typedef wince_thread thread; +# elif defined(ASIO_WINDOWS_APP) +typedef winapp_thread thread; +# else +typedef win_thread thread; +# endif +#elif defined(ASIO_HAS_PTHREADS) +typedef posix_thread thread; +#elif defined(ASIO_HAS_STD_THREAD) +typedef std_thread thread; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_context.hpp new file mode 100644 index 00000000..be3e8390 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_context.hpp @@ -0,0 +1,42 @@ +// +// detail/thread_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THREAD_CONTEXT_HPP +#define ASIO_DETAIL_THREAD_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include +#include "asio/detail/call_stack.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class thread_info_base; + +// Base class for things that manage threads (scheduler, win_iocp_io_context). +class thread_context +{ +public: + // Per-thread call stack to track the state of each thread in the context. + typedef call_stack thread_call_stack; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_THREAD_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_group.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_group.hpp new file mode 100644 index 00000000..11bc14cd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_group.hpp @@ -0,0 +1,95 @@ +// +// detail/thread_group.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THREAD_GROUP_HPP +#define ASIO_DETAIL_THREAD_GROUP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/thread.hpp" + +namespace asio { +namespace detail { + +class thread_group +{ +public: + // Constructor initialises an empty thread group. + thread_group() + : first_(0) + { + } + + // Destructor joins any remaining threads in the group. + ~thread_group() + { + join(); + } + + // Create a new thread in the group. + template + void create_thread(Function f) + { + first_ = new item(f, first_); + } + + // Create new threads in the group. + template + void create_threads(Function f, std::size_t num_threads) + { + for (std::size_t i = 0; i < num_threads; ++i) + create_thread(f); + } + + // Wait for all threads in the group to exit. + void join() + { + while (first_) + { + first_->thread_.join(); + item* tmp = first_; + first_ = first_->next_; + delete tmp; + } + } + + // Test whether the group is empty. + bool empty() const + { + return first_ == 0; + } + +private: + // Structure used to track a single thread in the group. + struct item + { + template + explicit item(Function f, item* next) + : thread_(f), + next_(next) + { + } + + asio::detail::thread thread_; + item* next_; + }; + + // The first thread in the group. + item* first_; +}; + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_THREAD_GROUP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_info_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_info_base.hpp new file mode 100644 index 00000000..8bc809b6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/thread_info_base.hpp @@ -0,0 +1,126 @@ +// +// detail/thread_info_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THREAD_INFO_BASE_HPP +#define ASIO_DETAIL_THREAD_INFO_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class thread_info_base + : private noncopyable +{ +public: + struct default_tag + { + enum { mem_index = 0 }; + }; + + struct awaitable_frame_tag + { + enum { mem_index = 1 }; + }; + + struct executor_function_tag + { + enum { mem_index = 2 }; + }; + + thread_info_base() + { + for (int i = 0; i < max_mem_index; ++i) + reusable_memory_[i] = 0; + } + + ~thread_info_base() + { + for (int i = 0; i < max_mem_index; ++i) + if (reusable_memory_[i]) + ::operator delete(reusable_memory_[i]); + } + + static void* allocate(thread_info_base* this_thread, std::size_t size) + { + return allocate(default_tag(), this_thread, size); + } + + static void deallocate(thread_info_base* this_thread, + void* pointer, std::size_t size) + { + deallocate(default_tag(), this_thread, pointer, size); + } + + template + static void* allocate(Purpose, thread_info_base* this_thread, + std::size_t size) + { + std::size_t chunks = (size + chunk_size - 1) / chunk_size; + + if (this_thread && this_thread->reusable_memory_[Purpose::mem_index]) + { + void* const pointer = this_thread->reusable_memory_[Purpose::mem_index]; + this_thread->reusable_memory_[Purpose::mem_index] = 0; + + unsigned char* const mem = static_cast(pointer); + if (static_cast(mem[0]) >= chunks) + { + mem[size] = mem[0]; + return pointer; + } + + ::operator delete(pointer); + } + + void* const pointer = ::operator new(chunks * chunk_size + 1); + unsigned char* const mem = static_cast(pointer); + mem[size] = (chunks <= UCHAR_MAX) ? static_cast(chunks) : 0; + return pointer; + } + + template + static void deallocate(Purpose, thread_info_base* this_thread, + void* pointer, std::size_t size) + { + if (size <= chunk_size * UCHAR_MAX) + { + if (this_thread && this_thread->reusable_memory_[Purpose::mem_index] == 0) + { + unsigned char* const mem = static_cast(pointer); + mem[0] = mem[size]; + this_thread->reusable_memory_[Purpose::mem_index] = pointer; + return; + } + } + + ::operator delete(pointer); + } + +private: + enum { chunk_size = 4 }; + enum { max_mem_index = 3 }; + void* reusable_memory_[max_mem_index]; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_THREAD_INFO_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_error.hpp new file mode 100644 index 00000000..cbeb77ae --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_error.hpp @@ -0,0 +1,53 @@ +// +// detail/throw_error.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THROW_ERROR_HPP +#define ASIO_DETAIL_THROW_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error_code.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +ASIO_DECL void do_throw_error(const asio::error_code& err); + +ASIO_DECL void do_throw_error(const asio::error_code& err, + const char* location); + +inline void throw_error(const asio::error_code& err) +{ + if (err) + do_throw_error(err); +} + +inline void throw_error(const asio::error_code& err, + const char* location) +{ + if (err) + do_throw_error(err, location); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/throw_error.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_THROW_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_exception.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_exception.hpp new file mode 100644 index 00000000..1680aeeb --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/throw_exception.hpp @@ -0,0 +1,51 @@ +// +// detail/throw_exception.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_THROW_EXCEPTION_HPP +#define ASIO_DETAIL_THROW_EXCEPTION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_THROW_EXCEPTION) +# include +#endif // defined(ASIO_BOOST_THROW_EXCEPTION) + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_BOOST_THROW_EXCEPTION) +using boost::throw_exception; +#else // defined(ASIO_HAS_BOOST_THROW_EXCEPTION) + +// Declare the throw_exception function for all targets. +template +void throw_exception(const Exception& e); + +// Only define the throw_exception function when exceptions are enabled. +// Otherwise, it is up to the application to provide a definition of this +// function. +# if !defined(ASIO_NO_EXCEPTIONS) +template +void throw_exception(const Exception& e) +{ + throw e; +} +# endif // !defined(ASIO_NO_EXCEPTIONS) + +#endif // defined(ASIO_HAS_BOOST_THROW_EXCEPTION) + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_THROW_EXCEPTION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue.hpp new file mode 100644 index 00000000..015d0cd5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue.hpp @@ -0,0 +1,360 @@ +// +// detail/timer_queue.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_QUEUE_HPP +#define ASIO_DETAIL_TIMER_QUEUE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/detail/cstdint.hpp" +#include "asio/detail/date_time_fwd.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class timer_queue + : public timer_queue_base +{ +public: + // The time type. + typedef typename Time_Traits::time_type time_type; + + // The duration type. + typedef typename Time_Traits::duration_type duration_type; + + // Per-timer data. + class per_timer_data + { + public: + per_timer_data() : + heap_index_((std::numeric_limits::max)()), + next_(0), prev_(0) + { + } + + private: + friend class timer_queue; + + // The operations waiting on the timer. + op_queue op_queue_; + + // The index of the timer in the heap. + std::size_t heap_index_; + + // Pointers to adjacent timers in a linked list. + per_timer_data* next_; + per_timer_data* prev_; + }; + + // Constructor. + timer_queue() + : timers_(), + heap_() + { + } + + // Add a new timer to the queue. Returns true if this is the timer that is + // earliest in the queue, in which case the reactor's event demultiplexing + // function call may need to be interrupted and restarted. + bool enqueue_timer(const time_type& time, per_timer_data& timer, wait_op* op) + { + // Enqueue the timer object. + if (timer.prev_ == 0 && &timer != timers_) + { + if (this->is_positive_infinity(time)) + { + // No heap entry is required for timers that never expire. + timer.heap_index_ = (std::numeric_limits::max)(); + } + else + { + // Put the new timer at the correct position in the heap. This is done + // first since push_back() can throw due to allocation failure. + timer.heap_index_ = heap_.size(); + heap_entry entry = { time, &timer }; + heap_.push_back(entry); + up_heap(heap_.size() - 1); + } + + // Insert the new timer into the linked list of active timers. + timer.next_ = timers_; + timer.prev_ = 0; + if (timers_) + timers_->prev_ = &timer; + timers_ = &timer; + } + + // Enqueue the individual timer operation. + timer.op_queue_.push(op); + + // Interrupt reactor only if newly added timer is first to expire. + return timer.heap_index_ == 0 && timer.op_queue_.front() == op; + } + + // Whether there are no timers in the queue. + virtual bool empty() const + { + return timers_ == 0; + } + + // Get the time for the timer that is earliest in the queue. + virtual long wait_duration_msec(long max_duration) const + { + if (heap_.empty()) + return max_duration; + + return this->to_msec( + Time_Traits::to_posix_duration( + Time_Traits::subtract(heap_[0].time_, Time_Traits::now())), + max_duration); + } + + // Get the time for the timer that is earliest in the queue. + virtual long wait_duration_usec(long max_duration) const + { + if (heap_.empty()) + return max_duration; + + return this->to_usec( + Time_Traits::to_posix_duration( + Time_Traits::subtract(heap_[0].time_, Time_Traits::now())), + max_duration); + } + + // Dequeue all timers not later than the current time. + virtual void get_ready_timers(op_queue& ops) + { + if (!heap_.empty()) + { + const time_type now = Time_Traits::now(); + while (!heap_.empty() && !Time_Traits::less_than(now, heap_[0].time_)) + { + per_timer_data* timer = heap_[0].timer_; + ops.push(timer->op_queue_); + remove_timer(*timer); + } + } + } + + // Dequeue all timers. + virtual void get_all_timers(op_queue& ops) + { + while (timers_) + { + per_timer_data* timer = timers_; + timers_ = timers_->next_; + ops.push(timer->op_queue_); + timer->next_ = 0; + timer->prev_ = 0; + } + + heap_.clear(); + } + + // Cancel and dequeue operations for the given timer. + std::size_t cancel_timer(per_timer_data& timer, op_queue& ops, + std::size_t max_cancelled = (std::numeric_limits::max)()) + { + std::size_t num_cancelled = 0; + if (timer.prev_ != 0 || &timer == timers_) + { + while (wait_op* op = (num_cancelled != max_cancelled) + ? timer.op_queue_.front() : 0) + { + op->ec_ = asio::error::operation_aborted; + timer.op_queue_.pop(); + ops.push(op); + ++num_cancelled; + } + if (timer.op_queue_.empty()) + remove_timer(timer); + } + return num_cancelled; + } + + // Move operations from one timer to another, empty timer. + void move_timer(per_timer_data& target, per_timer_data& source) + { + target.op_queue_.push(source.op_queue_); + + target.heap_index_ = source.heap_index_; + source.heap_index_ = (std::numeric_limits::max)(); + + if (target.heap_index_ < heap_.size()) + heap_[target.heap_index_].timer_ = ⌖ + + if (timers_ == &source) + timers_ = ⌖ + if (source.prev_) + source.prev_->next_ = ⌖ + if (source.next_) + source.next_->prev_= ⌖ + target.next_ = source.next_; + target.prev_ = source.prev_; + source.next_ = 0; + source.prev_ = 0; + } + +private: + // Move the item at the given index up the heap to its correct position. + void up_heap(std::size_t index) + { + while (index > 0) + { + std::size_t parent = (index - 1) / 2; + if (!Time_Traits::less_than(heap_[index].time_, heap_[parent].time_)) + break; + swap_heap(index, parent); + index = parent; + } + } + + // Move the item at the given index down the heap to its correct position. + void down_heap(std::size_t index) + { + std::size_t child = index * 2 + 1; + while (child < heap_.size()) + { + std::size_t min_child = (child + 1 == heap_.size() + || Time_Traits::less_than( + heap_[child].time_, heap_[child + 1].time_)) + ? child : child + 1; + if (Time_Traits::less_than(heap_[index].time_, heap_[min_child].time_)) + break; + swap_heap(index, min_child); + index = min_child; + child = index * 2 + 1; + } + } + + // Swap two entries in the heap. + void swap_heap(std::size_t index1, std::size_t index2) + { + heap_entry tmp = heap_[index1]; + heap_[index1] = heap_[index2]; + heap_[index2] = tmp; + heap_[index1].timer_->heap_index_ = index1; + heap_[index2].timer_->heap_index_ = index2; + } + + // Remove a timer from the heap and list of timers. + void remove_timer(per_timer_data& timer) + { + // Remove the timer from the heap. + std::size_t index = timer.heap_index_; + if (!heap_.empty() && index < heap_.size()) + { + if (index == heap_.size() - 1) + { + timer.heap_index_ = (std::numeric_limits::max)(); + heap_.pop_back(); + } + else + { + swap_heap(index, heap_.size() - 1); + timer.heap_index_ = (std::numeric_limits::max)(); + heap_.pop_back(); + if (index > 0 && Time_Traits::less_than( + heap_[index].time_, heap_[(index - 1) / 2].time_)) + up_heap(index); + else + down_heap(index); + } + } + + // Remove the timer from the linked list of active timers. + if (timers_ == &timer) + timers_ = timer.next_; + if (timer.prev_) + timer.prev_->next_ = timer.next_; + if (timer.next_) + timer.next_->prev_= timer.prev_; + timer.next_ = 0; + timer.prev_ = 0; + } + + // Determine if the specified absolute time is positive infinity. + template + static bool is_positive_infinity(const Time_Type&) + { + return false; + } + + // Determine if the specified absolute time is positive infinity. + template + static bool is_positive_infinity( + const boost::date_time::base_time& time) + { + return time.is_pos_infinity(); + } + + // Helper function to convert a duration into milliseconds. + template + long to_msec(const Duration& d, long max_duration) const + { + if (d.ticks() <= 0) + return 0; + int64_t msec = d.total_milliseconds(); + if (msec == 0) + return 1; + if (msec > max_duration) + return max_duration; + return static_cast(msec); + } + + // Helper function to convert a duration into microseconds. + template + long to_usec(const Duration& d, long max_duration) const + { + if (d.ticks() <= 0) + return 0; + int64_t usec = d.total_microseconds(); + if (usec == 0) + return 1; + if (usec > max_duration) + return max_duration; + return static_cast(usec); + } + + // The head of a linked list of all active timers. + per_timer_data* timers_; + + struct heap_entry + { + // The time when the timer should fire. + time_type time_; + + // The associated timer with enqueued operations. + per_timer_data* timer_; + }; + + // The heap of timers, with the earliest timer at the front. + std::vector heap_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_TIMER_QUEUE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_base.hpp new file mode 100644 index 00000000..f0ea3598 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_base.hpp @@ -0,0 +1,68 @@ +// +// detail/timer_queue_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_QUEUE_BASE_HPP +#define ASIO_DETAIL_TIMER_QUEUE_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class timer_queue_base + : private noncopyable +{ +public: + // Constructor. + timer_queue_base() : next_(0) {} + + // Destructor. + virtual ~timer_queue_base() {} + + // Whether there are no timers in the queue. + virtual bool empty() const = 0; + + // Get the time to wait until the next timer. + virtual long wait_duration_msec(long max_duration) const = 0; + + // Get the time to wait until the next timer. + virtual long wait_duration_usec(long max_duration) const = 0; + + // Dequeue all ready timers. + virtual void get_ready_timers(op_queue& ops) = 0; + + // Dequeue all timers. + virtual void get_all_timers(op_queue& ops) = 0; + +private: + friend class timer_queue_set; + + // Next timer queue in the set. + timer_queue_base* next_; +}; + +template +class timer_queue; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_TIMER_QUEUE_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_ptime.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_ptime.hpp new file mode 100644 index 00000000..a67adeb8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_ptime.hpp @@ -0,0 +1,99 @@ +// +// detail/timer_queue_ptime.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_QUEUE_PTIME_HPP +#define ASIO_DETAIL_TIMER_QUEUE_PTIME_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_DATE_TIME) + +#include "asio/time_traits.hpp" +#include "asio/detail/timer_queue.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct forwarding_posix_time_traits : time_traits {}; + +// Template specialisation for the commonly used instantation. +template <> +class timer_queue > + : public timer_queue_base +{ +public: + // The time type. + typedef boost::posix_time::ptime time_type; + + // The duration type. + typedef boost::posix_time::time_duration duration_type; + + // Per-timer data. + typedef timer_queue::per_timer_data + per_timer_data; + + // Constructor. + ASIO_DECL timer_queue(); + + // Destructor. + ASIO_DECL virtual ~timer_queue(); + + // Add a new timer to the queue. Returns true if this is the timer that is + // earliest in the queue, in which case the reactor's event demultiplexing + // function call may need to be interrupted and restarted. + ASIO_DECL bool enqueue_timer(const time_type& time, + per_timer_data& timer, wait_op* op); + + // Whether there are no timers in the queue. + ASIO_DECL virtual bool empty() const; + + // Get the time for the timer that is earliest in the queue. + ASIO_DECL virtual long wait_duration_msec(long max_duration) const; + + // Get the time for the timer that is earliest in the queue. + ASIO_DECL virtual long wait_duration_usec(long max_duration) const; + + // Dequeue all timers not later than the current time. + ASIO_DECL virtual void get_ready_timers(op_queue& ops); + + // Dequeue all timers. + ASIO_DECL virtual void get_all_timers(op_queue& ops); + + // Cancel and dequeue operations for the given timer. + ASIO_DECL std::size_t cancel_timer( + per_timer_data& timer, op_queue& ops, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move operations from one timer to another, empty timer. + ASIO_DECL void move_timer(per_timer_data& target, + per_timer_data& source); + +private: + timer_queue impl_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/timer_queue_ptime.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + +#endif // ASIO_DETAIL_TIMER_QUEUE_PTIME_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_set.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_set.hpp new file mode 100644 index 00000000..51a507c8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_queue_set.hpp @@ -0,0 +1,66 @@ +// +// detail/timer_queue_set.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_QUEUE_SET_HPP +#define ASIO_DETAIL_TIMER_QUEUE_SET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/timer_queue_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class timer_queue_set +{ +public: + // Constructor. + ASIO_DECL timer_queue_set(); + + // Add a timer queue to the set. + ASIO_DECL void insert(timer_queue_base* q); + + // Remove a timer queue from the set. + ASIO_DECL void erase(timer_queue_base* q); + + // Determine whether all queues are empty. + ASIO_DECL bool all_empty() const; + + // Get the wait duration in milliseconds. + ASIO_DECL long wait_duration_msec(long max_duration) const; + + // Get the wait duration in microseconds. + ASIO_DECL long wait_duration_usec(long max_duration) const; + + // Dequeue all ready timers. + ASIO_DECL void get_ready_timers(op_queue& ops); + + // Dequeue all timers. + ASIO_DECL void get_all_timers(op_queue& ops); + +private: + timer_queue_base* first_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/timer_queue_set.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_DETAIL_TIMER_QUEUE_SET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler.hpp new file mode 100644 index 00000000..471e7386 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler.hpp @@ -0,0 +1,35 @@ +// +// detail/timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_SCHEDULER_HPP +#define ASIO_DETAIL_TIMER_SCHEDULER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/timer_scheduler_fwd.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_timer_scheduler.hpp" +#elif defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#elif defined(ASIO_HAS_EPOLL) +# include "asio/detail/epoll_reactor.hpp" +#elif defined(ASIO_HAS_KQUEUE) +# include "asio/detail/kqueue_reactor.hpp" +#elif defined(ASIO_HAS_DEV_POLL) +# include "asio/detail/dev_poll_reactor.hpp" +#else +# include "asio/detail/select_reactor.hpp" +#endif + +#endif // ASIO_DETAIL_TIMER_SCHEDULER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler_fwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler_fwd.hpp new file mode 100644 index 00000000..eaf07df9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/timer_scheduler_fwd.hpp @@ -0,0 +1,40 @@ +// +// detail/timer_scheduler_fwd.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TIMER_SCHEDULER_FWD_HPP +#define ASIO_DETAIL_TIMER_SCHEDULER_FWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_WINDOWS_RUNTIME) +typedef class winrt_timer_scheduler timer_scheduler; +#elif defined(ASIO_HAS_IOCP) +typedef class win_iocp_io_context timer_scheduler; +#elif defined(ASIO_HAS_EPOLL) +typedef class epoll_reactor timer_scheduler; +#elif defined(ASIO_HAS_KQUEUE) +typedef class kqueue_reactor timer_scheduler; +#elif defined(ASIO_HAS_DEV_POLL) +typedef class dev_poll_reactor timer_scheduler; +#else +typedef class select_reactor timer_scheduler; +#endif + +} // namespace detail +} // namespace asio + +#endif // ASIO_DETAIL_TIMER_SCHEDULER_FWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/tss_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/tss_ptr.hpp new file mode 100644 index 00000000..d9903dc5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/tss_ptr.hpp @@ -0,0 +1,69 @@ +// +// detail/tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TSS_PTR_HPP +#define ASIO_DETAIL_TSS_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_THREADS) +# include "asio/detail/null_tss_ptr.hpp" +#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION) +# include "asio/detail/keyword_tss_ptr.hpp" +#elif defined(ASIO_WINDOWS) +# include "asio/detail/win_tss_ptr.hpp" +#elif defined(ASIO_HAS_PTHREADS) +# include "asio/detail/posix_tss_ptr.hpp" +#else +# error Only Windows and POSIX are supported! +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class tss_ptr +#if !defined(ASIO_HAS_THREADS) + : public null_tss_ptr +#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION) + : public keyword_tss_ptr +#elif defined(ASIO_WINDOWS) + : public win_tss_ptr +#elif defined(ASIO_HAS_PTHREADS) + : public posix_tss_ptr +#endif +{ +public: + void operator=(T* value) + { +#if !defined(ASIO_HAS_THREADS) + null_tss_ptr::operator=(value); +#elif defined(ASIO_HAS_THREAD_KEYWORD_EXTENSION) + keyword_tss_ptr::operator=(value); +#elif defined(ASIO_WINDOWS) + win_tss_ptr::operator=(value); +#elif defined(ASIO_HAS_PTHREADS) + posix_tss_ptr::operator=(value); +#endif + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_TSS_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/type_traits.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/type_traits.hpp new file mode 100644 index 00000000..0f7ee6e3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/type_traits.hpp @@ -0,0 +1,89 @@ +// +// detail/type_traits.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_TYPE_TRAITS_HPP +#define ASIO_DETAIL_TYPE_TRAITS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_TYPE_TRAITS) +# include +#else // defined(ASIO_HAS_TYPE_TRAITS) +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +#endif // defined(ASIO_HAS_TYPE_TRAITS) + +namespace asio { + +#if defined(ASIO_HAS_STD_TYPE_TRAITS) +using std::add_const; +using std::conditional; +using std::decay; +using std::declval; +using std::enable_if; +using std::false_type; +using std::integral_constant; +using std::is_base_of; +using std::is_class; +using std::is_const; +using std::is_convertible; +using std::is_function; +using std::is_same; +using std::remove_pointer; +using std::remove_reference; +#if defined(ASIO_HAS_STD_INVOKE_RESULT) +template struct result_of; +template +struct result_of : std::invoke_result {}; +#else // defined(ASIO_HAS_STD_INVOKE_RESULT) +using std::result_of; +#endif // defined(ASIO_HAS_STD_INVOKE_RESULT) +using std::true_type; +#else // defined(ASIO_HAS_STD_TYPE_TRAITS) +using boost::add_const; +template +struct enable_if : boost::enable_if_c {}; +using boost::conditional; +using boost::decay; +using boost::declval; +using boost::false_type; +using boost::integral_constant; +using boost::is_base_of; +using boost::is_class; +using boost::is_const; +using boost::is_convertible; +using boost::is_function; +using boost::is_same; +using boost::remove_pointer; +using boost::remove_reference; +using boost::result_of; +using boost::true_type; +#endif // defined(ASIO_HAS_STD_TYPE_TRAITS) + +} // namespace asio + +#endif // ASIO_DETAIL_TYPE_TRAITS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/variadic_templates.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/variadic_templates.hpp new file mode 100644 index 00000000..cd52c04f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/variadic_templates.hpp @@ -0,0 +1,151 @@ +// +// detail/variadic_templates.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_VARIADIC_TEMPLATES_HPP +#define ASIO_DETAIL_VARIADIC_TEMPLATES_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +# define ASIO_VARIADIC_TPARAMS(n) ASIO_VARIADIC_TPARAMS_##n + +# define ASIO_VARIADIC_TPARAMS_1 \ + typename T1 +# define ASIO_VARIADIC_TPARAMS_2 \ + typename T1, typename T2 +# define ASIO_VARIADIC_TPARAMS_3 \ + typename T1, typename T2, typename T3 +# define ASIO_VARIADIC_TPARAMS_4 \ + typename T1, typename T2, typename T3, typename T4 +# define ASIO_VARIADIC_TPARAMS_5 \ + typename T1, typename T2, typename T3, typename T4, typename T5 + +# define ASIO_VARIADIC_TARGS(n) ASIO_VARIADIC_TARGS_##n + +# define ASIO_VARIADIC_TARGS_1 T1 +# define ASIO_VARIADIC_TARGS_2 T1, T2 +# define ASIO_VARIADIC_TARGS_3 T1, T2, T3 +# define ASIO_VARIADIC_TARGS_4 T1, T2, T3, T4 +# define ASIO_VARIADIC_TARGS_5 T1, T2, T3, T4, T5 + +# define ASIO_VARIADIC_BYVAL_PARAMS(n) \ + ASIO_VARIADIC_BYVAL_PARAMS_##n + +# define ASIO_VARIADIC_BYVAL_PARAMS_1 T1 x1 +# define ASIO_VARIADIC_BYVAL_PARAMS_2 T1 x1, T2 x2 +# define ASIO_VARIADIC_BYVAL_PARAMS_3 T1 x1, T2 x2, T3 x3 +# define ASIO_VARIADIC_BYVAL_PARAMS_4 T1 x1, T2 x2, T3 x3, T4 x4 +# define ASIO_VARIADIC_BYVAL_PARAMS_5 T1 x1, T2 x2, T3 x3, T4 x4, T5 x5 + +# define ASIO_VARIADIC_BYVAL_ARGS(n) \ + ASIO_VARIADIC_BYVAL_ARGS_##n + +# define ASIO_VARIADIC_BYVAL_ARGS_1 x1 +# define ASIO_VARIADIC_BYVAL_ARGS_2 x1, x2 +# define ASIO_VARIADIC_BYVAL_ARGS_3 x1, x2, x3 +# define ASIO_VARIADIC_BYVAL_ARGS_4 x1, x2, x3, x4 +# define ASIO_VARIADIC_BYVAL_ARGS_5 x1, x2, x3, x4, x5 + +# define ASIO_VARIADIC_CONSTREF_PARAMS(n) \ + ASIO_VARIADIC_CONSTREF_PARAMS_##n + +# define ASIO_VARIADIC_CONSTREF_PARAMS_1 \ + const T1& x1 +# define ASIO_VARIADIC_CONSTREF_PARAMS_2 \ + const T1& x1, const T2& x2 +# define ASIO_VARIADIC_CONSTREF_PARAMS_3 \ + const T1& x1, const T2& x2, const T3& x3 +# define ASIO_VARIADIC_CONSTREF_PARAMS_4 \ + const T1& x1, const T2& x2, const T3& x3, const T4& x4 +# define ASIO_VARIADIC_CONSTREF_PARAMS_5 \ + const T1& x1, const T2& x2, const T3& x3, const T4& x4, const T5& x5 + +# define ASIO_VARIADIC_MOVE_PARAMS(n) \ + ASIO_VARIADIC_MOVE_PARAMS_##n + +# define ASIO_VARIADIC_MOVE_PARAMS_1 \ + ASIO_MOVE_ARG(T1) x1 +# define ASIO_VARIADIC_MOVE_PARAMS_2 \ + ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2 +# define ASIO_VARIADIC_MOVE_PARAMS_3 \ + ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ + ASIO_MOVE_ARG(T3) x3 +# define ASIO_VARIADIC_MOVE_PARAMS_4 \ + ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ + ASIO_MOVE_ARG(T3) x3, ASIO_MOVE_ARG(T4) x4 +# define ASIO_VARIADIC_MOVE_PARAMS_5 \ + ASIO_MOVE_ARG(T1) x1, ASIO_MOVE_ARG(T2) x2, \ + ASIO_MOVE_ARG(T3) x3, ASIO_MOVE_ARG(T4) x4, \ + ASIO_MOVE_ARG(T5) x5 + +# define ASIO_VARIADIC_MOVE_ARGS(n) \ + ASIO_VARIADIC_MOVE_ARGS_##n + +# define ASIO_VARIADIC_MOVE_ARGS_1 \ + ASIO_MOVE_CAST(T1)(x1) +# define ASIO_VARIADIC_MOVE_ARGS_2 \ + ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2) +# define ASIO_VARIADIC_MOVE_ARGS_3 \ + ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ + ASIO_MOVE_CAST(T3)(x3) +# define ASIO_VARIADIC_MOVE_ARGS_4 \ + ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ + ASIO_MOVE_CAST(T3)(x3), ASIO_MOVE_CAST(T4)(x4) +# define ASIO_VARIADIC_MOVE_ARGS_5 \ + ASIO_MOVE_CAST(T1)(x1), ASIO_MOVE_CAST(T2)(x2), \ + ASIO_MOVE_CAST(T3)(x3), ASIO_MOVE_CAST(T4)(x4), \ + ASIO_MOVE_CAST(T5)(x5) + +# define ASIO_VARIADIC_MOVE_DECLVAL(n) \ + ASIO_VARIADIC_MOVE_DECLVAL_##n + +# define ASIO_VARIADIC_MOVE_DECLVAL_1 \ + declval() +# define ASIO_VARIADIC_MOVE_DECLVAL_2 \ + declval(), declval() +# define ASIO_VARIADIC_MOVE_DECLVAL_3 \ + declval(), declval(), \ + declval() +# define ASIO_VARIADIC_MOVE_DECLVAL_4 \ + declval(), declval(), \ + declval(), declval() +# define ASIO_VARIADIC_MOVE_DECLVAL_5 \ + declval(), declval(), \ + declval(), declval(), \ + declval() + +# define ASIO_VARIADIC_DECAY(n) \ + ASIO_VARIADIC_DECAY_##n + +# define ASIO_VARIADIC_DECAY_1 \ + typename decay::type +# define ASIO_VARIADIC_DECAY_2 \ + typename decay::type, typename decay::type +# define ASIO_VARIADIC_DECAY_3 \ + typename decay::type, typename decay::type, \ + typename decay::type +# define ASIO_VARIADIC_DECAY_4 \ + typename decay::type, typename decay::type, \ + typename decay::type, typename decay::type +# define ASIO_VARIADIC_DECAY_5 \ + typename decay::type, typename decay::type, \ + typename decay::type, typename decay::type, \ + typename decay::type + +# define ASIO_VARIADIC_GENERATE(m) m(1) m(2) m(3) m(4) m(5) + +#endif // !defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#endif // ASIO_DETAIL_VARIADIC_TEMPLATES_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_handler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_handler.hpp new file mode 100644 index 00000000..be49a966 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_handler.hpp @@ -0,0 +1,87 @@ +// +// detail/wait_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WAIT_HANDLER_HPP +#define ASIO_DETAIL_WAIT_HANDLER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_work.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/wait_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class wait_handler : public wait_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(wait_handler); + + wait_handler(Handler& h, const IoExecutor& ex) + : wait_op(&wait_handler::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(h)), + io_executor_(ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& /*ec*/, + std::size_t /*bytes_transferred*/) + { + // Take ownership of the handler object. + wait_handler* h(static_cast(base)); + ptr p = { asio::detail::addressof(h->handler_), h, h }; + handler_work w(h->handler_, h->io_executor_); + + ASIO_HANDLER_COMPLETION((*h)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(h->handler_, h->ec_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WAIT_HANDLER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_op.hpp new file mode 100644 index 00000000..a443cebd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wait_op.hpp @@ -0,0 +1,45 @@ +// +// detail/wait_op.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WAIT_OP_HPP +#define ASIO_DETAIL_WAIT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class wait_op + : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + +protected: + wait_op(func_type func) + : operation(func) + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WAIT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_event.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_event.hpp new file mode 100644 index 00000000..678b290f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_event.hpp @@ -0,0 +1,151 @@ +// +// detail/win_event.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_EVENT_HPP +#define ASIO_DETAIL_WIN_EVENT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) + +#include "asio/detail/assert.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_event + : private noncopyable +{ +public: + // Constructor. + ASIO_DECL win_event(); + + // Destructor. + ASIO_DECL ~win_event(); + + // Signal the event. (Retained for backward compatibility.) + template + void signal(Lock& lock) + { + this->signal_all(lock); + } + + // Signal all waiters. + template + void signal_all(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + state_ |= 1; + ::SetEvent(events_[0]); + } + + // Unlock the mutex and signal one waiter. + template + void unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + bool have_waiters = (state_ > 1); + lock.unlock(); + if (have_waiters) + ::SetEvent(events_[1]); + } + + // If there's a waiter, unlock the mutex and signal it. + template + bool maybe_unlock_and_signal_one(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + state_ |= 1; + if (state_ > 1) + { + lock.unlock(); + ::SetEvent(events_[1]); + return true; + } + return false; + } + + // Reset the event. + template + void clear(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + (void)lock; + ::ResetEvent(events_[0]); + state_ &= ~std::size_t(1); + } + + // Wait for the event to become signalled. + template + void wait(Lock& lock) + { + ASIO_ASSERT(lock.locked()); + while ((state_ & 1) == 0) + { + state_ += 2; + lock.unlock(); +#if defined(ASIO_WINDOWS_APP) + ::WaitForMultipleObjectsEx(2, events_, false, INFINITE, false); +#else // defined(ASIO_WINDOWS_APP) + ::WaitForMultipleObjects(2, events_, false, INFINITE); +#endif // defined(ASIO_WINDOWS_APP) + lock.lock(); + state_ -= 2; + } + } + + // Timed wait for the event to become signalled. + template + bool wait_for_usec(Lock& lock, long usec) + { + ASIO_ASSERT(lock.locked()); + if ((state_ & 1) == 0) + { + state_ += 2; + lock.unlock(); + DWORD msec = usec > 0 ? (usec < 1000 ? 1 : usec / 1000) : 0; +#if defined(ASIO_WINDOWS_APP) + ::WaitForMultipleObjectsEx(2, events_, false, msec, false); +#else // defined(ASIO_WINDOWS_APP) + ::WaitForMultipleObjects(2, events_, false, msec); +#endif // defined(ASIO_WINDOWS_APP) + lock.lock(); + state_ -= 2; + } + return (state_ & 1) != 0; + } + +private: + HANDLE events_[2]; + std::size_t state_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_event.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + +#endif // ASIO_DETAIL_WIN_EVENT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fd_set_adapter.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fd_set_adapter.hpp new file mode 100644 index 00000000..cc8bde9c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fd_set_adapter.hpp @@ -0,0 +1,149 @@ +// +// detail/win_fd_set_adapter.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_FD_SET_ADAPTER_HPP +#define ASIO_DETAIL_WIN_FD_SET_ADAPTER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/reactor_op_queue.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Adapts the FD_SET type to meet the Descriptor_Set concept's requirements. +class win_fd_set_adapter : noncopyable +{ +public: + enum { default_fd_set_size = 1024 }; + + win_fd_set_adapter() + : capacity_(default_fd_set_size), + max_descriptor_(invalid_socket) + { + fd_set_ = static_cast(::operator new( + sizeof(win_fd_set) - sizeof(SOCKET) + + sizeof(SOCKET) * (capacity_))); + fd_set_->fd_count = 0; + } + + ~win_fd_set_adapter() + { + ::operator delete(fd_set_); + } + + void reset() + { + fd_set_->fd_count = 0; + max_descriptor_ = invalid_socket; + } + + bool set(socket_type descriptor) + { + for (u_int i = 0; i < fd_set_->fd_count; ++i) + if (fd_set_->fd_array[i] == descriptor) + return true; + + reserve(fd_set_->fd_count + 1); + fd_set_->fd_array[fd_set_->fd_count++] = descriptor; + return true; + } + + void set(reactor_op_queue& operations, op_queue&) + { + reactor_op_queue::iterator i = operations.begin(); + while (i != operations.end()) + { + reactor_op_queue::iterator op_iter = i++; + reserve(fd_set_->fd_count + 1); + fd_set_->fd_array[fd_set_->fd_count++] = op_iter->first; + } + } + + bool is_set(socket_type descriptor) const + { + return !!__WSAFDIsSet(descriptor, + const_cast(reinterpret_cast(fd_set_))); + } + + operator fd_set*() + { + return reinterpret_cast(fd_set_); + } + + socket_type max_descriptor() const + { + return max_descriptor_; + } + + void perform(reactor_op_queue& operations, + op_queue& ops) const + { + for (u_int i = 0; i < fd_set_->fd_count; ++i) + operations.perform_operations(fd_set_->fd_array[i], ops); + } + +private: + // This structure is defined to be compatible with the Windows API fd_set + // structure, but without being dependent on the value of FD_SETSIZE. We use + // the "struct hack" to allow the number of descriptors to be varied at + // runtime. + struct win_fd_set + { + u_int fd_count; + SOCKET fd_array[1]; + }; + + // Increase the fd_set_ capacity to at least the specified number of elements. + void reserve(u_int n) + { + if (n <= capacity_) + return; + + u_int new_capacity = capacity_ + capacity_ / 2; + if (new_capacity < n) + new_capacity = n; + + win_fd_set* new_fd_set = static_cast(::operator new( + sizeof(win_fd_set) - sizeof(SOCKET) + + sizeof(SOCKET) * (new_capacity))); + + new_fd_set->fd_count = fd_set_->fd_count; + for (u_int i = 0; i < fd_set_->fd_count; ++i) + new_fd_set->fd_array[i] = fd_set_->fd_array[i]; + + ::operator delete(fd_set_); + fd_set_ = new_fd_set; + capacity_ = new_capacity; + } + + win_fd_set* fd_set_; + u_int capacity_; + socket_type max_descriptor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#endif // ASIO_DETAIL_WIN_FD_SET_ADAPTER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fenced_block.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fenced_block.hpp new file mode 100644 index 00000000..9fa84653 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_fenced_block.hpp @@ -0,0 +1,90 @@ +// +// detail/win_fenced_block.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_FENCED_BLOCK_HPP +#define ASIO_DETAIL_WIN_FENCED_BLOCK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) && !defined(UNDER_CE) + +#include "asio/detail/socket_types.hpp" +#include "asio/detail/noncopyable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_fenced_block + : private noncopyable +{ +public: + enum half_t { half }; + enum full_t { full }; + + // Constructor for a half fenced block. + explicit win_fenced_block(half_t) + { + } + + // Constructor for a full fenced block. + explicit win_fenced_block(full_t) + { +#if defined(__BORLANDC__) + LONG barrier = 0; + ::InterlockedExchange(&barrier, 1); +#elif defined(ASIO_MSVC) \ + && ((ASIO_MSVC < 1400) || !defined(MemoryBarrier)) +# if defined(_M_IX86) +# pragma warning(push) +# pragma warning(disable:4793) + LONG barrier; + __asm { xchg barrier, eax } +# pragma warning(pop) +# endif // defined(_M_IX86) +#else + MemoryBarrier(); +#endif + } + + // Destructor. + ~win_fenced_block() + { +#if defined(__BORLANDC__) + LONG barrier = 0; + ::InterlockedExchange(&barrier, 1); +#elif defined(ASIO_MSVC) \ + && ((ASIO_MSVC < 1400) || !defined(MemoryBarrier)) +# if defined(_M_IX86) +# pragma warning(push) +# pragma warning(disable:4793) + LONG barrier; + __asm { xchg barrier, eax } +# pragma warning(pop) +# endif // defined(_M_IX86) +#else + MemoryBarrier(); +#endif + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS) && !defined(UNDER_CE) + +#endif // ASIO_DETAIL_WIN_FENCED_BLOCK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_global.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_global.hpp new file mode 100644 index 00000000..2d5ce754 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_global.hpp @@ -0,0 +1,71 @@ +// +// detail/win_global.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_GLOBAL_HPP +#define ASIO_DETAIL_WIN_GLOBAL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/static_mutex.hpp" +#include "asio/detail/tss_ptr.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +struct win_global_impl +{ + // Destructor automatically cleans up the global. + ~win_global_impl() + { + delete ptr_; + } + + static win_global_impl instance_; + static static_mutex mutex_; + T* ptr_; + static tss_ptr tss_ptr_; +}; + +template +win_global_impl win_global_impl::instance_ = { 0 }; + +template +static_mutex win_global_impl::mutex_ = ASIO_STATIC_MUTEX_INIT; + +template +tss_ptr win_global_impl::tss_ptr_; + +template +T& win_global() +{ + if (static_cast(win_global_impl::tss_ptr_) == 0) + { + win_global_impl::mutex_.init(); + static_mutex::scoped_lock lock(win_global_impl::mutex_); + if (win_global_impl::instance_.ptr_ == 0) + win_global_impl::instance_.ptr_ = new T; + win_global_impl::tss_ptr_ = win_global_impl::instance_.ptr_; + } + + return *win_global_impl::tss_ptr_; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WIN_GLOBAL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_read_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_read_op.hpp new file mode 100644 index 00000000..a54e3608 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_read_op.hpp @@ -0,0 +1,113 @@ +// +// detail/win_iocp_handle_read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_HANDLE_READ_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_HANDLE_READ_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/error.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_handle_read_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_handle_read_op); + + win_iocp_handle_read_op(const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_handle_read_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_handle_read_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + if (owner) + { + // Check whether buffers are still valid. + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + // Map non-portable errors to their portable counterparts. + if (ec.value() == ERROR_HANDLE_EOF) + ec = asio::error::eof; + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + MutableBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_HANDLE_READ_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_service.hpp new file mode 100644 index 00000000..63274549 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_service.hpp @@ -0,0 +1,335 @@ +// +// detail/win_iocp_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_HANDLE_SERVICE_HPP +#define ASIO_DETAIL_WIN_IOCP_HANDLE_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/cstdint.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/win_iocp_handle_read_op.hpp" +#include "asio/detail/win_iocp_handle_write_op.hpp" +#include "asio/detail/win_iocp_io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_iocp_handle_service : + public execution_context_service_base +{ +public: + // The native type of a stream handle. + typedef HANDLE native_handle_type; + + // The implementation type of the stream handle. + class implementation_type + { + public: + // Default constructor. + implementation_type() + : handle_(INVALID_HANDLE_VALUE), + safe_cancellation_thread_id_(0), + next_(0), + prev_(0) + { + } + + private: + // Only this service will have access to the internal values. + friend class win_iocp_handle_service; + + // The native stream handle representation. + native_handle_type handle_; + + // The ID of the thread from which it is safe to cancel asynchronous + // operations. 0 means no asynchronous operations have been started yet. + // ~0 means asynchronous operations have been started from more than one + // thread, and cancellation is not supported for the handle. + DWORD safe_cancellation_thread_id_; + + // Pointers to adjacent handle implementations in linked list. + implementation_type* next_; + implementation_type* prev_; + }; + + ASIO_DECL win_iocp_handle_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new handle implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Move-construct a new handle implementation. + ASIO_DECL void move_construct(implementation_type& impl, + implementation_type& other_impl); + + // Move-assign from another handle implementation. + ASIO_DECL void move_assign(implementation_type& impl, + win_iocp_handle_service& other_service, + implementation_type& other_impl); + + // Destroy a handle implementation. + ASIO_DECL void destroy(implementation_type& impl); + + // Assign a native handle to a handle implementation. + ASIO_DECL asio::error_code assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec); + + // Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return impl.handle_ != INVALID_HANDLE_VALUE; + } + + // Destroy a handle implementation. + ASIO_DECL asio::error_code close(implementation_type& impl, + asio::error_code& ec); + + // Get the native handle representation. + native_handle_type native_handle(const implementation_type& impl) const + { + return impl.handle_; + } + + // Cancel all operations associated with the handle. + ASIO_DECL asio::error_code cancel(implementation_type& impl, + asio::error_code& ec); + + // Write the given data. Returns the number of bytes written. + template + size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return write_some_at(impl, 0, buffers, ec); + } + + // Write the given data at the specified offset. Returns the number of bytes + // written. + template + size_t write_some_at(implementation_type& impl, uint64_t offset, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + asio::const_buffer buffer = + buffer_sequence_adapter::first(buffers); + + return do_write(impl, offset, buffer, ec); + } + + // Start an asynchronous write. The data being written must be valid for the + // lifetime of the asynchronous operation. + template + void async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_write_op< + ConstBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((iocp_service_.context(), *p.p, "handle", &impl, + reinterpret_cast(impl.handle_), "async_write_some")); + + start_write_op(impl, 0, + buffer_sequence_adapter::first(buffers), p.p); + p.v = p.p = 0; + } + + // Start an asynchronous write at a specified offset. The data being written + // must be valid for the lifetime of the asynchronous operation. + template + void async_write_some_at(implementation_type& impl, + uint64_t offset, const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_write_op< + ConstBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((iocp_service_.context(), *p.p, "handle", &impl, + reinterpret_cast(impl.handle_), "async_write_some_at")); + + start_write_op(impl, offset, + buffer_sequence_adapter::first(buffers), p.p); + p.v = p.p = 0; + } + + // Read some data. Returns the number of bytes received. + template + size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return read_some_at(impl, 0, buffers, ec); + } + + // Read some data at a specified offset. Returns the number of bytes received. + template + size_t read_some_at(implementation_type& impl, uint64_t offset, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + asio::mutable_buffer buffer = + buffer_sequence_adapter::first(buffers); + + return do_read(impl, offset, buffer, ec); + } + + // Start an asynchronous read. The buffer for the data being received must be + // valid for the lifetime of the asynchronous operation. + template + void async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_read_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((iocp_service_.context(), *p.p, "handle", &impl, + reinterpret_cast(impl.handle_), "async_read_some")); + + start_read_op(impl, 0, + buffer_sequence_adapter::first(buffers), p.p); + p.v = p.p = 0; + } + + // Start an asynchronous read at a specified offset. The buffer for the data + // being received must be valid for the lifetime of the asynchronous + // operation. + template + void async_read_some_at(implementation_type& impl, + uint64_t offset, const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_handle_read_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((iocp_service_.context(), *p.p, "handle", &impl, + reinterpret_cast(impl.handle_), "async_read_some_at")); + + start_read_op(impl, offset, + buffer_sequence_adapter::first(buffers), p.p); + p.v = p.p = 0; + } + +private: + // Prevent the use of the null_buffers type with this service. + size_t write_some(implementation_type& impl, + const null_buffers& buffers, asio::error_code& ec); + size_t write_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, asio::error_code& ec); + template + void async_write_some(implementation_type& impl, + const null_buffers& buffers, Handler& handler, + const IoExecutor& io_ex); + template + void async_write_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, Handler& handler, const IoExecutor& io_ex); + size_t read_some(implementation_type& impl, + const null_buffers& buffers, asio::error_code& ec); + size_t read_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, asio::error_code& ec); + template + void async_read_some(implementation_type& impl, + const null_buffers& buffers, Handler& handler, + const IoExecutor& io_ex); + template + void async_read_some_at(implementation_type& impl, uint64_t offset, + const null_buffers& buffers, Handler& handler, const IoExecutor& io_ex); + + // Helper class for waiting for synchronous operations to complete. + class overlapped_wrapper; + + // Helper function to perform a synchronous write operation. + ASIO_DECL size_t do_write(implementation_type& impl, + uint64_t offset, const asio::const_buffer& buffer, + asio::error_code& ec); + + // Helper function to start a write operation. + ASIO_DECL void start_write_op(implementation_type& impl, + uint64_t offset, const asio::const_buffer& buffer, + operation* op); + + // Helper function to perform a synchronous write operation. + ASIO_DECL size_t do_read(implementation_type& impl, + uint64_t offset, const asio::mutable_buffer& buffer, + asio::error_code& ec); + + // Helper function to start a read operation. + ASIO_DECL void start_read_op(implementation_type& impl, + uint64_t offset, const asio::mutable_buffer& buffer, + operation* op); + + // Update the ID of the thread from which cancellation is safe. + ASIO_DECL void update_cancellation_thread_id(implementation_type& impl); + + // Helper function to close a handle when the associated object is being + // destroyed. + ASIO_DECL void close_for_destruction(implementation_type& impl); + + // The IOCP service used for running asynchronous operations and dispatching + // handlers. + win_iocp_io_context& iocp_service_; + + // Mutex to protect access to the linked list of implementations. + mutex mutex_; + + // The head of a linked list of all implementations. + implementation_type* impl_list_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_iocp_handle_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_HANDLE_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_write_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_write_op.hpp new file mode 100644 index 00000000..9bb88141 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_handle_write_op.hpp @@ -0,0 +1,106 @@ +// +// detail/win_iocp_handle_write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_HANDLE_WRITE_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_HANDLE_WRITE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/error.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_handle_write_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_handle_write_op); + + win_iocp_handle_write_op(const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_handle_write_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& ec, std::size_t bytes_transferred) + { + // Take ownership of the operation object. + win_iocp_handle_write_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + if (owner) + { + // Check whether buffers are still valid. + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + ConstBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_HANDLE_WRITE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_io_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_io_context.hpp new file mode 100644 index 00000000..e2094164 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_io_context.hpp @@ -0,0 +1,338 @@ +// +// detail/win_iocp_io_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP +#define ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/limits.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/thread.hpp" +#include "asio/detail/thread_context.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/detail/win_iocp_operation.hpp" +#include "asio/detail/win_iocp_thread_info.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class wait_op; + +class win_iocp_io_context + : public execution_context_service_base, + public thread_context +{ +public: + // Constructor. Specifies a concurrency hint that is passed through to the + // underlying I/O completion port. + ASIO_DECL win_iocp_io_context(asio::execution_context& ctx, + int concurrency_hint = -1, bool own_thread = true); + + // Destructor. + ASIO_DECL ~win_iocp_io_context(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Initialise the task. Nothing to do here. + void init_task() + { + } + + // Register a handle with the IO completion port. + ASIO_DECL asio::error_code register_handle( + HANDLE handle, asio::error_code& ec); + + // Run the event loop until stopped or no more work. + ASIO_DECL size_t run(asio::error_code& ec); + + // Run until stopped or one operation is performed. + ASIO_DECL size_t run_one(asio::error_code& ec); + + // Run until timeout, interrupted, or one operation is performed. + ASIO_DECL size_t wait_one(long usec, asio::error_code& ec); + + // Poll for operations without blocking. + ASIO_DECL size_t poll(asio::error_code& ec); + + // Poll for one operation without blocking. + ASIO_DECL size_t poll_one(asio::error_code& ec); + + // Stop the event processing loop. + ASIO_DECL void stop(); + + // Determine whether the io_context is stopped. + bool stopped() const + { + return ::InterlockedExchangeAdd(&stopped_, 0) != 0; + } + + // Restart in preparation for a subsequent run invocation. + void restart() + { + ::InterlockedExchange(&stopped_, 0); + } + + // Notify that some work has started. + void work_started() + { + ::InterlockedIncrement(&outstanding_work_); + } + + // Notify that some work has finished. + void work_finished() + { + if (::InterlockedDecrement(&outstanding_work_) == 0) + stop(); + } + + // Return whether a handler can be dispatched immediately. + bool can_dispatch() + { + return thread_call_stack::contains(this) != 0; + } + + // Request invocation of the given operation and return immediately. Assumes + // that work_started() has not yet been called for the operation. + void post_immediate_completion(win_iocp_operation* op, bool) + { + work_started(); + post_deferred_completion(op); + } + + // Request invocation of the given operation and return immediately. Assumes + // that work_started() was previously called for the operation. + ASIO_DECL void post_deferred_completion(win_iocp_operation* op); + + // Request invocation of the given operation and return immediately. Assumes + // that work_started() was previously called for the operations. + ASIO_DECL void post_deferred_completions( + op_queue& ops); + + // Request invocation of the given operation using the thread-private queue + // and return immediately. Assumes that work_started() has not yet been + // called for the operation. + void post_private_immediate_completion(win_iocp_operation* op) + { + post_immediate_completion(op, false); + } + + // Request invocation of the given operation using the thread-private queue + // and return immediately. Assumes that work_started() was previously called + // for the operation. + void post_private_deferred_completion(win_iocp_operation* op) + { + post_deferred_completion(op); + } + + // Enqueue the given operation following a failed attempt to dispatch the + // operation for immediate invocation. + void do_dispatch(operation* op) + { + post_immediate_completion(op, false); + } + + // Process unfinished operations as part of a shutdown operation. Assumes + // that work_started() was previously called for the operations. + ASIO_DECL void abandon_operations(op_queue& ops); + + // Called after starting an overlapped I/O operation that did not complete + // immediately. The caller must have already called work_started() prior to + // starting the operation. + ASIO_DECL void on_pending(win_iocp_operation* op); + + // Called after starting an overlapped I/O operation that completed + // immediately. The caller must have already called work_started() prior to + // starting the operation. + ASIO_DECL void on_completion(win_iocp_operation* op, + DWORD last_error = 0, DWORD bytes_transferred = 0); + + // Called after starting an overlapped I/O operation that completed + // immediately. The caller must have already called work_started() prior to + // starting the operation. + ASIO_DECL void on_completion(win_iocp_operation* op, + const asio::error_code& ec, DWORD bytes_transferred = 0); + + // Add a new timer queue to the service. + template + void add_timer_queue(timer_queue& timer_queue); + + // Remove a timer queue from the service. + template + void remove_timer_queue(timer_queue& timer_queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer associated with the given token. Returns the number of + // handlers that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& to, + typename timer_queue::per_timer_data& from); + + // Get the concurrency hint that was used to initialise the io_context. + int concurrency_hint() const + { + return concurrency_hint_; + } + +private: +#if defined(WINVER) && (WINVER < 0x0500) + typedef DWORD dword_ptr_t; + typedef ULONG ulong_ptr_t; +#else // defined(WINVER) && (WINVER < 0x0500) + typedef DWORD_PTR dword_ptr_t; + typedef ULONG_PTR ulong_ptr_t; +#endif // defined(WINVER) && (WINVER < 0x0500) + + // Dequeues at most one operation from the I/O completion port, and then + // executes it. Returns the number of operations that were dequeued (i.e. + // either 0 or 1). + ASIO_DECL size_t do_one(DWORD msec, asio::error_code& ec); + + // Helper to calculate the GetQueuedCompletionStatus timeout. + ASIO_DECL static DWORD get_gqcs_timeout(); + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // Called to recalculate and update the timeout. + ASIO_DECL void update_timeout(); + + // Helper class to call work_finished() on block exit. + struct work_finished_on_block_exit; + + // Helper class for managing a HANDLE. + struct auto_handle + { + HANDLE handle; + auto_handle() : handle(0) {} + ~auto_handle() { if (handle) ::CloseHandle(handle); } + }; + + // The IO completion port used for queueing operations. + auto_handle iocp_; + + // The count of unfinished work. + long outstanding_work_; + + // Flag to indicate whether the event loop has been stopped. + mutable long stopped_; + + // Flag to indicate whether there is an in-flight stop event. Every event + // posted using PostQueuedCompletionStatus consumes non-paged pool, so to + // avoid exhausting this resouce we limit the number of outstanding events. + long stop_event_posted_; + + // Flag to indicate whether the service has been shut down. + long shutdown_; + + enum + { + // Timeout to use with GetQueuedCompletionStatus on older versions of + // Windows. Some versions of windows have a "bug" where a call to + // GetQueuedCompletionStatus can appear stuck even though there are events + // waiting on the queue. Using a timeout helps to work around the issue. + default_gqcs_timeout = 500, + + // Maximum waitable timer timeout, in milliseconds. + max_timeout_msec = 5 * 60 * 1000, + + // Maximum waitable timer timeout, in microseconds. + max_timeout_usec = max_timeout_msec * 1000, + + // Completion key value used to wake up a thread to dispatch timers or + // completed operations. + wake_for_dispatch = 1, + + // Completion key value to indicate that an operation has posted with the + // original last_error and bytes_transferred values stored in the fields of + // the OVERLAPPED structure. + overlapped_contains_result = 2 + }; + + // Timeout to use with GetQueuedCompletionStatus. + const DWORD gqcs_timeout_; + + // Helper class to run the scheduler in its own thread. + struct thread_function; + friend struct thread_function; + + // Function object for processing timeouts in a background thread. + struct timer_thread_function; + friend struct timer_thread_function; + + // Background thread used for processing timeouts. + scoped_ptr timer_thread_; + + // A waitable timer object used for waiting for timeouts. + auto_handle waitable_timer_; + + // Non-zero if timers or completed operations need to be dispatched. + long dispatch_required_; + + // Mutex for protecting access to the timer queues and completed operations. + mutex dispatch_mutex_; + + // The timer queues. + timer_queue_set timer_queues_; + + // The operations that are ready to dispatch. + op_queue completed_ops_; + + // The concurrency hint used to initialise the io_context. + const int concurrency_hint_; + + // The thread that is running the io_context. + scoped_ptr thread_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/win_iocp_io_context.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_iocp_io_context.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_IO_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_null_buffers_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_null_buffers_op.hpp new file mode 100644 index 00000000..99a31665 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_null_buffers_op.hpp @@ -0,0 +1,123 @@ +// +// detail/win_iocp_null_buffers_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_NULL_BUFFERS_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_NULL_BUFFERS_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_null_buffers_op : public reactor_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_null_buffers_op); + + win_iocp_null_buffers_op(socket_ops::weak_cancel_token_type cancel_token, + Handler& handler, const IoExecutor& io_ex) + : reactor_op(&win_iocp_null_buffers_op::do_perform, + &win_iocp_null_buffers_op::do_complete), + cancel_token_(cancel_token), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static status do_perform(reactor_op*) + { + return done; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_null_buffers_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // The reactor may have stored a result in the operation object. + if (o->ec_) + ec = o->ec_; + + // Map non-portable errors to their portable counterparts. + if (ec.value() == ERROR_NETNAME_DELETED) + { + if (o->cancel_token_.expired()) + ec = asio::error::operation_aborted; + else + ec = asio::error::connection_reset; + } + else if (ec.value() == ERROR_PORT_UNREACHABLE) + { + ec = asio::error::connection_refused; + } + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_NULL_BUFFERS_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_operation.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_operation.hpp new file mode 100644 index 00000000..34d31987 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_operation.hpp @@ -0,0 +1,96 @@ +// +// detail/win_iocp_operation.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_OPERATION_HPP +#define ASIO_DETAIL_WIN_IOCP_OPERATION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/handler_tracking.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/error_code.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_iocp_io_context; + +// Base class for all operations. A function pointer is used instead of virtual +// functions to avoid the associated overhead. +class win_iocp_operation + : public OVERLAPPED + ASIO_ALSO_INHERIT_TRACKED_HANDLER +{ +public: + typedef win_iocp_operation operation_type; + + void complete(void* owner, const asio::error_code& ec, + std::size_t bytes_transferred) + { + func_(owner, this, ec, bytes_transferred); + } + + void destroy() + { + func_(0, this, asio::error_code(), 0); + } + +protected: + typedef void (*func_type)( + void*, win_iocp_operation*, + const asio::error_code&, std::size_t); + + win_iocp_operation(func_type func) + : next_(0), + func_(func) + { + reset(); + } + + // Prevents deletion through this type. + ~win_iocp_operation() + { + } + + void reset() + { + Internal = 0; + InternalHigh = 0; + Offset = 0; + OffsetHigh = 0; + hEvent = 0; + ready_ = 0; + } + +private: + friend class op_queue_access; + friend class win_iocp_io_context; + win_iocp_operation* next_; + func_type func_; + long ready_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_OPERATION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_op.hpp new file mode 100644 index 00000000..5a28acf0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_op.hpp @@ -0,0 +1,92 @@ +// +// detail/win_iocp_overlapped_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_OVERLAPPED_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_OVERLAPPED_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/error.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_overlapped_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_overlapped_op); + + win_iocp_overlapped_op(Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_overlapped_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& ec, std::size_t bytes_transferred) + { + // Take ownership of the operation object. + win_iocp_overlapped_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_OVERLAPPED_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_ptr.hpp new file mode 100644 index 00000000..e1ee5b02 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_overlapped_ptr.hpp @@ -0,0 +1,159 @@ +// +// detail/win_iocp_overlapped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_OVERLAPPED_PTR_HPP +#define ASIO_DETAIL_WIN_IOCP_OVERLAPPED_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/io_context.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/io_object_executor.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/win_iocp_overlapped_op.hpp" +#include "asio/detail/win_iocp_io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Wraps a handler to create an OVERLAPPED object for use with overlapped I/O. +class win_iocp_overlapped_ptr + : private noncopyable +{ +public: + // Construct an empty win_iocp_overlapped_ptr. + win_iocp_overlapped_ptr() + : ptr_(0), + iocp_service_(0) + { + } + + // Construct an win_iocp_overlapped_ptr to contain the specified handler. + template + explicit win_iocp_overlapped_ptr(const Executor& ex, + ASIO_MOVE_ARG(Handler) handler) + : ptr_(0), + iocp_service_(0) + { + this->reset(ex, ASIO_MOVE_CAST(Handler)(handler)); + } + + // Destructor automatically frees the OVERLAPPED object unless released. + ~win_iocp_overlapped_ptr() + { + reset(); + } + + // Reset to empty. + void reset() + { + if (ptr_) + { + ptr_->destroy(); + ptr_ = 0; + iocp_service_->work_finished(); + iocp_service_ = 0; + } + } + + // Reset to contain the specified handler, freeing any current OVERLAPPED + // object. + template + void reset(const Executor& ex, Handler handler) + { + const bool native = is_same::value; + win_iocp_io_context* iocp_service = this->get_iocp_service(ex); + + typedef win_iocp_overlapped_op > op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_object_executor(ex, native)); + + ASIO_HANDLER_CREATION((ex.context(), *p.p, + "iocp_service", iocp_service, 0, "overlapped")); + + iocp_service->work_started(); + reset(); + ptr_ = p.p; + p.v = p.p = 0; + iocp_service_ = iocp_service; + } + + // Get the contained OVERLAPPED object. + OVERLAPPED* get() + { + return ptr_; + } + + // Get the contained OVERLAPPED object. + const OVERLAPPED* get() const + { + return ptr_; + } + + // Release ownership of the OVERLAPPED object. + OVERLAPPED* release() + { + if (ptr_) + iocp_service_->on_pending(ptr_); + + OVERLAPPED* tmp = ptr_; + ptr_ = 0; + iocp_service_ = 0; + return tmp; + } + + // Post completion notification for overlapped operation. Releases ownership. + void complete(const asio::error_code& ec, + std::size_t bytes_transferred) + { + if (ptr_) + { + iocp_service_->on_completion(ptr_, ec, + static_cast(bytes_transferred)); + ptr_ = 0; + iocp_service_ = 0; + } + } + +private: + template + static win_iocp_io_context* get_iocp_service(const Executor& ex) + { + return &use_service(ex.context()); + } + + static win_iocp_io_context* get_iocp_service( + const io_context::executor_type& ex) + { + return &ex.context().impl_; + } + + win_iocp_operation* ptr_; + win_iocp_io_context* iocp_service_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_OVERLAPPED_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_serial_port_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_serial_port_service.hpp new file mode 100644 index 00000000..06ef407b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_serial_port_service.hpp @@ -0,0 +1,232 @@ +// +// detail/win_iocp_serial_port_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP +#define ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) && defined(ASIO_HAS_SERIAL_PORT) + +#include +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/win_iocp_handle_service.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Extend win_iocp_handle_service to provide serial port support. +class win_iocp_serial_port_service : + public execution_context_service_base +{ +public: + // The native type of a serial port. + typedef win_iocp_handle_service::native_handle_type native_handle_type; + + // The implementation type of the serial port. + typedef win_iocp_handle_service::implementation_type implementation_type; + + // Constructor. + ASIO_DECL win_iocp_serial_port_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new serial port implementation. + void construct(implementation_type& impl) + { + handle_service_.construct(impl); + } + + // Move-construct a new serial port implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) + { + handle_service_.move_construct(impl, other_impl); + } + + // Move-assign from another serial port implementation. + void move_assign(implementation_type& impl, + win_iocp_serial_port_service& other_service, + implementation_type& other_impl) + { + handle_service_.move_assign(impl, + other_service.handle_service_, other_impl); + } + + // Destroy a serial port implementation. + void destroy(implementation_type& impl) + { + handle_service_.destroy(impl); + } + + // Open the serial port using the specified device name. + ASIO_DECL asio::error_code open(implementation_type& impl, + const std::string& device, asio::error_code& ec); + + // Assign a native handle to a serial port implementation. + asio::error_code assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec) + { + return handle_service_.assign(impl, handle, ec); + } + + // Determine whether the serial port is open. + bool is_open(const implementation_type& impl) const + { + return handle_service_.is_open(impl); + } + + // Destroy a serial port implementation. + asio::error_code close(implementation_type& impl, + asio::error_code& ec) + { + return handle_service_.close(impl, ec); + } + + // Get the native serial port representation. + native_handle_type native_handle(implementation_type& impl) + { + return handle_service_.native_handle(impl); + } + + // Cancel all operations associated with the handle. + asio::error_code cancel(implementation_type& impl, + asio::error_code& ec) + { + return handle_service_.cancel(impl, ec); + } + + // Set an option on the serial port. + template + asio::error_code set_option(implementation_type& impl, + const SettableSerialPortOption& option, asio::error_code& ec) + { + return do_set_option(impl, + &win_iocp_serial_port_service::store_option, + &option, ec); + } + + // Get an option from the serial port. + template + asio::error_code get_option(const implementation_type& impl, + GettableSerialPortOption& option, asio::error_code& ec) const + { + return do_get_option(impl, + &win_iocp_serial_port_service::load_option, + &option, ec); + } + + // Send a break sequence to the serial port. + asio::error_code send_break(implementation_type&, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Write the given data. Returns the number of bytes sent. + template + size_t write_some(implementation_type& impl, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return handle_service_.write_some(impl, buffers, ec); + } + + // Start an asynchronous write. The data being written must be valid for the + // lifetime of the asynchronous operation. + template + void async_write_some(implementation_type& impl, + const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + handle_service_.async_write_some(impl, buffers, handler, io_ex); + } + + // Read some data. Returns the number of bytes received. + template + size_t read_some(implementation_type& impl, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return handle_service_.read_some(impl, buffers, ec); + } + + // Start an asynchronous read. The buffer for the data being received must be + // valid for the lifetime of the asynchronous operation. + template + void async_read_some(implementation_type& impl, + const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + { + handle_service_.async_read_some(impl, buffers, handler, io_ex); + } + +private: + // Function pointer type for storing a serial port option. + typedef asio::error_code (*store_function_type)( + const void*, ::DCB&, asio::error_code&); + + // Helper function template to store a serial port option. + template + static asio::error_code store_option(const void* option, + ::DCB& storage, asio::error_code& ec) + { + static_cast(option)->store(storage, ec); + return ec; + } + + // Helper function to set a serial port option. + ASIO_DECL asio::error_code do_set_option( + implementation_type& impl, store_function_type store, + const void* option, asio::error_code& ec); + + // Function pointer type for loading a serial port option. + typedef asio::error_code (*load_function_type)( + void*, const ::DCB&, asio::error_code&); + + // Helper function template to load a serial port option. + template + static asio::error_code load_option(void* option, + const ::DCB& storage, asio::error_code& ec) + { + static_cast(option)->load(storage, ec); + return ec; + } + + // Helper function to get a serial port option. + ASIO_DECL asio::error_code do_get_option( + const implementation_type& impl, load_function_type load, + void* option, asio::error_code& ec) const; + + // The implementation used for initiating asynchronous operations. + win_iocp_handle_service handle_service_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_iocp_serial_port_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_IOCP) && defined(ASIO_HAS_SERIAL_PORT) + +#endif // ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_accept_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_accept_op.hpp new file mode 100644 index 00000000..c7da5c1d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_accept_op.hpp @@ -0,0 +1,306 @@ +// +// detail/win_iocp_socket_accept_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/win_iocp_socket_service_base.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_accept_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_accept_op); + + win_iocp_socket_accept_op(win_iocp_socket_service_base& socket_service, + socket_type socket, Socket& peer, const Protocol& protocol, + typename Protocol::endpoint* peer_endpoint, + bool enable_connection_aborted, Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_socket_accept_op::do_complete), + socket_service_(socket_service), + socket_(socket), + peer_(peer), + protocol_(protocol), + peer_endpoint_(peer_endpoint), + enable_connection_aborted_(enable_connection_aborted), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + socket_holder& new_socket() + { + return new_socket_; + } + + void* output_buffer() + { + return output_buffer_; + } + + DWORD address_length() + { + return sizeof(sockaddr_storage_type) + 16; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t /*bytes_transferred*/) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_accept_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + if (owner) + { + typename Protocol::endpoint peer_endpoint; + std::size_t addr_len = peer_endpoint.capacity(); + socket_ops::complete_iocp_accept(o->socket_, + o->output_buffer(), o->address_length(), + peer_endpoint.data(), &addr_len, + o->new_socket_.get(), ec); + + // Restart the accept operation if we got the connection_aborted error + // and the enable_connection_aborted socket option is not set. + if (ec == asio::error::connection_aborted + && !o->enable_connection_aborted_) + { + o->reset(); + o->socket_service_.restart_accept_op(o->socket_, + o->new_socket_, o->protocol_.family(), + o->protocol_.type(), o->protocol_.protocol(), + o->output_buffer(), o->address_length(), o); + p.v = p.p = 0; + return; + } + + // If the socket was successfully accepted, transfer ownership of the + // socket to the peer object. + if (!ec) + { + o->peer_.assign(o->protocol_, + typename Socket::native_handle_type( + o->new_socket_.get(), peer_endpoint), ec); + if (!ec) + o->new_socket_.release(); + } + + // Pass endpoint back to caller. + if (o->peer_endpoint_) + *o->peer_endpoint_ = peer_endpoint; + } + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, ec); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + win_iocp_socket_service_base& socket_service_; + socket_type socket_; + socket_holder new_socket_; + Socket& peer_; + Protocol protocol_; + typename Protocol::endpoint* peer_endpoint_; + unsigned char output_buffer_[(sizeof(sockaddr_storage_type) + 16) * 2]; + bool enable_connection_aborted_; + Handler handler_; + IoExecutor io_executor_; +}; + +#if defined(ASIO_HAS_MOVE) + +template +class win_iocp_socket_move_accept_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_move_accept_op); + + win_iocp_socket_move_accept_op( + win_iocp_socket_service_base& socket_service, socket_type socket, + const Protocol& protocol, const PeerIoExecutor& peer_io_ex, + typename Protocol::endpoint* peer_endpoint, + bool enable_connection_aborted, Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_socket_move_accept_op::do_complete), + socket_service_(socket_service), + socket_(socket), + peer_(peer_io_ex), + protocol_(protocol), + peer_endpoint_(peer_endpoint), + enable_connection_aborted_(enable_connection_aborted), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + socket_holder& new_socket() + { + return new_socket_; + } + + void* output_buffer() + { + return output_buffer_; + } + + DWORD address_length() + { + return sizeof(sockaddr_storage_type) + 16; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t /*bytes_transferred*/) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_move_accept_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + if (owner) + { + typename Protocol::endpoint peer_endpoint; + std::size_t addr_len = peer_endpoint.capacity(); + socket_ops::complete_iocp_accept(o->socket_, + o->output_buffer(), o->address_length(), + peer_endpoint.data(), &addr_len, + o->new_socket_.get(), ec); + + // Restart the accept operation if we got the connection_aborted error + // and the enable_connection_aborted socket option is not set. + if (ec == asio::error::connection_aborted + && !o->enable_connection_aborted_) + { + o->reset(); + o->socket_service_.restart_accept_op(o->socket_, + o->new_socket_, o->protocol_.family(), + o->protocol_.type(), o->protocol_.protocol(), + o->output_buffer(), o->address_length(), o); + p.v = p.p = 0; + return; + } + + // If the socket was successfully accepted, transfer ownership of the + // socket to the peer object. + if (!ec) + { + o->peer_.assign(o->protocol_, + typename Protocol::socket::native_handle_type( + o->new_socket_.get(), peer_endpoint), ec); + if (!ec) + o->new_socket_.release(); + } + + // Pass endpoint back to caller. + if (o->peer_endpoint_) + *o->peer_endpoint_ = peer_endpoint; + } + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::move_binder2 + handler(0, ASIO_MOVE_CAST(Handler)(o->handler_), ec, + ASIO_MOVE_CAST(peer_socket_type)(o->peer_)); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + typedef typename Protocol::socket::template + rebind_executor::other peer_socket_type; + + win_iocp_socket_service_base& socket_service_; + socket_type socket_; + socket_holder new_socket_; + peer_socket_type peer_; + Protocol protocol_; + typename Protocol::endpoint* peer_endpoint_; + unsigned char output_buffer_[(sizeof(sockaddr_storage_type) + 16) * 2]; + bool enable_connection_aborted_; + Handler handler_; + IoExecutor io_executor_; +}; + +#endif // defined(ASIO_HAS_MOVE) + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_ACCEPT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_connect_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_connect_op.hpp new file mode 100644 index 00000000..a836351d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_connect_op.hpp @@ -0,0 +1,130 @@ +// +// detail/win_iocp_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_CONNECT_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_CONNECT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_iocp_socket_connect_op_base : public reactor_op +{ +public: + win_iocp_socket_connect_op_base(socket_type socket, func_type complete_func) + : reactor_op(&win_iocp_socket_connect_op_base::do_perform, complete_func), + socket_(socket), + connect_ex_(false) + { + } + + static status do_perform(reactor_op* base) + { + win_iocp_socket_connect_op_base* o( + static_cast(base)); + + return socket_ops::non_blocking_connect( + o->socket_, o->ec_) ? done : not_done; + } + + socket_type socket_; + bool connect_ex_; +}; + +template +class win_iocp_socket_connect_op : public win_iocp_socket_connect_op_base +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_connect_op); + + win_iocp_socket_connect_op(socket_type socket, + Handler& handler, const IoExecutor& io_ex) + : win_iocp_socket_connect_op_base(socket, + &win_iocp_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t /*bytes_transferred*/) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_connect_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + if (owner) + { + if (o->connect_ex_) + socket_ops::complete_iocp_connect(o->socket_, ec); + else + ec = o->ec_; + } + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, ec); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_CONNECT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recv_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recv_op.hpp new file mode 100644 index 00000000..72817052 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recv_op.hpp @@ -0,0 +1,120 @@ +// +// detail/win_iocp_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_RECV_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_RECV_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_recv_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_recv_op); + + win_iocp_socket_recv_op(socket_ops::state_type state, + socket_ops::weak_cancel_token_type cancel_token, + const MutableBufferSequence& buffers, Handler& handler, + const IoExecutor& io_ex) + : operation(&win_iocp_socket_recv_op::do_complete), + state_(state), + cancel_token_(cancel_token), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_recv_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + socket_ops::complete_iocp_recv(o->state_, o->cancel_token_, + buffer_sequence_adapter::all_empty(o->buffers_), + ec, bytes_transferred); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + socket_ops::state_type state_; + socket_ops::weak_cancel_token_type cancel_token_; + MutableBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_RECV_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvfrom_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvfrom_op.hpp new file mode 100644 index 00000000..551a8825 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvfrom_op.hpp @@ -0,0 +1,129 @@ +// +// detail/win_iocp_socket_recvfrom_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_recvfrom_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_recvfrom_op); + + win_iocp_socket_recvfrom_op(Endpoint& endpoint, + socket_ops::weak_cancel_token_type cancel_token, + const MutableBufferSequence& buffers, Handler& handler, + const IoExecutor& io_ex) + : operation(&win_iocp_socket_recvfrom_op::do_complete), + endpoint_(endpoint), + endpoint_size_(static_cast(endpoint.capacity())), + cancel_token_(cancel_token), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + int& endpoint_size() + { + return endpoint_size_; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_recvfrom_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + socket_ops::complete_iocp_recvfrom(o->cancel_token_, ec); + + // Record the size of the endpoint returned by the operation. + o->endpoint_.resize(o->endpoint_size_); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Endpoint& endpoint_; + int endpoint_size_; + socket_ops::weak_cancel_token_type cancel_token_; + MutableBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_RECVFROM_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvmsg_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvmsg_op.hpp new file mode 100644 index 00000000..8fb5d14c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_recvmsg_op.hpp @@ -0,0 +1,121 @@ +// +// detail/win_iocp_socket_recvmsg_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_RECVMSG_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_RECVMSG_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" +#include "asio/socket_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_recvmsg_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_recvmsg_op); + + win_iocp_socket_recvmsg_op( + socket_ops::weak_cancel_token_type cancel_token, + const MutableBufferSequence& buffers, + socket_base::message_flags& out_flags, + Handler& handler, const IoExecutor& io_ex) + : operation(&win_iocp_socket_recvmsg_op::do_complete), + cancel_token_(cancel_token), + buffers_(buffers), + out_flags_(out_flags), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_recvmsg_op* o( + static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + socket_ops::complete_iocp_recvmsg(o->cancel_token_, ec); + o->out_flags_ = 0; + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + MutableBufferSequence buffers_; + socket_base::message_flags& out_flags_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_RECVMSG_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_send_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_send_op.hpp new file mode 100644 index 00000000..45d7117c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_send_op.hpp @@ -0,0 +1,114 @@ +// +// detail/win_iocp_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_SEND_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_SEND_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_send_op : public operation +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_socket_send_op); + + win_iocp_socket_send_op(socket_ops::weak_cancel_token_type cancel_token, + const ConstBufferSequence& buffers, Handler& handler, + const IoExecutor& io_ex) + : operation(&win_iocp_socket_send_op::do_complete), + cancel_token_(cancel_token), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t bytes_transferred) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_socket_send_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + socket_ops::complete_iocp_send(o->cancel_token_, ec); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, ec, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + ConstBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_SEND_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service.hpp new file mode 100644 index 00000000..efbad6f6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service.hpp @@ -0,0 +1,581 @@ +// +// detail/win_iocp_socket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/select_reactor.hpp" +#include "asio/detail/socket_holder.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/win_iocp_io_context.hpp" +#include "asio/detail/win_iocp_null_buffers_op.hpp" +#include "asio/detail/win_iocp_socket_accept_op.hpp" +#include "asio/detail/win_iocp_socket_connect_op.hpp" +#include "asio/detail/win_iocp_socket_recvfrom_op.hpp" +#include "asio/detail/win_iocp_socket_send_op.hpp" +#include "asio/detail/win_iocp_socket_service_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_socket_service : + public execution_context_service_base >, + public win_iocp_socket_service_base +{ +public: + // The protocol type. + typedef Protocol protocol_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The native type of a socket. + class native_handle_type + { + public: + native_handle_type(socket_type s) + : socket_(s), + have_remote_endpoint_(false) + { + } + + native_handle_type(socket_type s, const endpoint_type& ep) + : socket_(s), + have_remote_endpoint_(true), + remote_endpoint_(ep) + { + } + + void operator=(socket_type s) + { + socket_ = s; + have_remote_endpoint_ = false; + remote_endpoint_ = endpoint_type(); + } + + operator socket_type() const + { + return socket_; + } + + bool have_remote_endpoint() const + { + return have_remote_endpoint_; + } + + endpoint_type remote_endpoint() const + { + return remote_endpoint_; + } + + private: + socket_type socket_; + bool have_remote_endpoint_; + endpoint_type remote_endpoint_; + }; + + // The implementation type of the socket. + struct implementation_type : + win_iocp_socket_service_base::base_implementation_type + { + // Default constructor. + implementation_type() + : protocol_(endpoint_type().protocol()), + have_remote_endpoint_(false), + remote_endpoint_() + { + } + + // The protocol associated with the socket. + protocol_type protocol_; + + // Whether we have a cached remote endpoint. + bool have_remote_endpoint_; + + // A cached remote endpoint. + endpoint_type remote_endpoint_; + }; + + // Constructor. + win_iocp_socket_service(execution_context& context) + : execution_context_service_base< + win_iocp_socket_service >(context), + win_iocp_socket_service_base(context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + this->base_shutdown(); + } + + // Move-construct a new socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) ASIO_NOEXCEPT + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + + impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_; + other_impl.have_remote_endpoint_ = false; + + impl.remote_endpoint_ = other_impl.remote_endpoint_; + other_impl.remote_endpoint_ = endpoint_type(); + } + + // Move-assign from another socket implementation. + void move_assign(implementation_type& impl, + win_iocp_socket_service_base& other_service, + implementation_type& other_impl) + { + this->base_move_assign(impl, other_service, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + + impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_; + other_impl.have_remote_endpoint_ = false; + + impl.remote_endpoint_ = other_impl.remote_endpoint_; + other_impl.remote_endpoint_ = endpoint_type(); + } + + // Move-construct a new socket implementation from another protocol type. + template + void converting_move_construct(implementation_type& impl, + win_iocp_socket_service&, + typename win_iocp_socket_service< + Protocol1>::implementation_type& other_impl) + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = protocol_type(other_impl.protocol_); + other_impl.protocol_ = typename Protocol1::endpoint().protocol(); + + impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_; + other_impl.have_remote_endpoint_ = false; + + impl.remote_endpoint_ = other_impl.remote_endpoint_; + other_impl.remote_endpoint_ = typename Protocol1::endpoint(); + } + + // Open a new socket implementation. + asio::error_code open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (!do_open(impl, protocol.family(), + protocol.type(), protocol.protocol(), ec)) + { + impl.protocol_ = protocol; + impl.have_remote_endpoint_ = false; + impl.remote_endpoint_ = endpoint_type(); + } + return ec; + } + + // Assign a native socket to a socket implementation. + asio::error_code assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + if (!do_assign(impl, protocol.type(), native_socket, ec)) + { + impl.protocol_ = protocol; + impl.have_remote_endpoint_ = native_socket.have_remote_endpoint(); + impl.remote_endpoint_ = native_socket.remote_endpoint(); + } + return ec; + } + + // Get the native socket representation. + native_handle_type native_handle(implementation_type& impl) + { + if (impl.have_remote_endpoint_) + return native_handle_type(impl.socket_, impl.remote_endpoint_); + return native_handle_type(impl.socket_); + } + + // Bind the socket to the specified local endpoint. + asio::error_code bind(implementation_type& impl, + const endpoint_type& endpoint, asio::error_code& ec) + { + socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec); + return ec; + } + + // Set a socket option. + template + asio::error_code set_option(implementation_type& impl, + const Option& option, asio::error_code& ec) + { + socket_ops::setsockopt(impl.socket_, impl.state_, + option.level(impl.protocol_), option.name(impl.protocol_), + option.data(impl.protocol_), option.size(impl.protocol_), ec); + return ec; + } + + // Set a socket option. + template + asio::error_code get_option(const implementation_type& impl, + Option& option, asio::error_code& ec) const + { + std::size_t size = option.size(impl.protocol_); + socket_ops::getsockopt(impl.socket_, impl.state_, + option.level(impl.protocol_), option.name(impl.protocol_), + option.data(impl.protocol_), &size, ec); + if (!ec) + option.resize(impl.protocol_, size); + return ec; + } + + // Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint; + std::size_t addr_len = endpoint.capacity(); + if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec)) + return endpoint_type(); + endpoint.resize(addr_len); + return endpoint; + } + + // Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint = impl.remote_endpoint_; + std::size_t addr_len = endpoint.capacity(); + if (socket_ops::getpeername(impl.socket_, endpoint.data(), + &addr_len, impl.have_remote_endpoint_, ec)) + return endpoint_type(); + endpoint.resize(addr_len); + return endpoint; + } + + // Disable sends or receives on the socket. + asio::error_code shutdown(base_implementation_type& impl, + socket_base::shutdown_type what, asio::error_code& ec) + { + socket_ops::shutdown(impl.socket_, what, ec); + return ec; + } + + // Send a datagram to the specified endpoint. Returns the number of bytes + // sent. + template + size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers, + const endpoint_type& destination, socket_base::message_flags flags, + asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_sendto(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, + destination.data(), destination.size(), ec); + } + + // Wait until data can be sent without blocking. + size_t send_to(implementation_type& impl, const null_buffers&, + const endpoint_type&, socket_base::message_flags, + asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send_to(implementation_type& impl, + const ConstBufferSequence& buffers, const endpoint_type& destination, + socket_base::message_flags flags, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_send_op< + ConstBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_send_to")); + + buffer_sequence_adapter bufs(buffers); + + start_send_to_op(impl, bufs.buffers(), bufs.count(), + destination.data(), static_cast(destination.size()), + flags, p.p); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send_to(implementation_type& impl, const null_buffers&, + const endpoint_type&, socket_base::message_flags, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_send_to(null_buffers)")); + + start_reactor_op(impl, select_reactor::write_op, p.p); + p.v = p.p = 0; + } + + // Receive a datagram with the endpoint of the sender. Returns the number of + // bytes received. + template + size_t receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + std::size_t addr_len = sender_endpoint.capacity(); + std::size_t bytes_recvd = socket_ops::sync_recvfrom( + impl.socket_, impl.state_, bufs.buffers(), bufs.count(), + flags, sender_endpoint.data(), &addr_len, ec); + + if (!ec) + sender_endpoint.resize(addr_len); + + return bytes_recvd; + } + + // Wait until data can be received without blocking. + size_t receive_from(implementation_type& impl, + const null_buffers&, endpoint_type& sender_endpoint, + socket_base::message_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + // Reset endpoint since it can be given no sensible value at this time. + sender_endpoint = endpoint_type(); + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received and + // the sender_endpoint object must both be valid for the lifetime of the + // asynchronous operation. + template + void async_receive_from(implementation_type& impl, + const MutableBufferSequence& buffers, endpoint_type& sender_endp, + socket_base::message_flags flags, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recvfrom_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(sender_endp, impl.cancel_token_, + buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive_from")); + + buffer_sequence_adapter bufs(buffers); + + start_receive_from_op(impl, bufs.buffers(), bufs.count(), + sender_endp.data(), flags, &p.p->endpoint_size(), p.p); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive_from(implementation_type& impl, const null_buffers&, + endpoint_type& sender_endpoint, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive_from(null_buffers)")); + + // Reset endpoint since it can be given no sensible value at this time. + sender_endpoint = endpoint_type(); + + start_null_buffers_receive_op(impl, flags, p.p); + p.v = p.p = 0; + } + + // Accept a new connection. + template + asio::error_code accept(implementation_type& impl, Socket& peer, + endpoint_type* peer_endpoint, asio::error_code& ec) + { + // We cannot accept a socket that is already open. + if (peer.is_open()) + { + ec = asio::error::already_open; + return ec; + } + + std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0; + socket_holder new_socket(socket_ops::sync_accept(impl.socket_, + impl.state_, peer_endpoint ? peer_endpoint->data() : 0, + peer_endpoint ? &addr_len : 0, ec)); + + // On success, assign new connection to peer socket object. + if (new_socket.get() != invalid_socket) + { + if (peer_endpoint) + peer_endpoint->resize(addr_len); + peer.assign(impl.protocol_, new_socket.get(), ec); + if (!ec) + new_socket.release(); + } + + return ec; + } + + // Start an asynchronous accept. The peer and peer_endpoint objects + // must be valid until the accept's handler is invoked. + template + void async_accept(implementation_type& impl, Socket& peer, + endpoint_type* peer_endpoint, Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_accept_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + bool enable_connection_aborted = + (impl.state_ & socket_ops::enable_connection_aborted) != 0; + p.p = new (p.v) op(*this, impl.socket_, peer, impl.protocol_, + peer_endpoint, enable_connection_aborted, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_accept")); + + start_accept_op(impl, peer.is_open(), p.p->new_socket(), + impl.protocol_.family(), impl.protocol_.type(), + impl.protocol_.protocol(), p.p->output_buffer(), + p.p->address_length(), p.p); + p.v = p.p = 0; + } + +#if defined(ASIO_HAS_MOVE) + // Start an asynchronous accept. The peer and peer_endpoint objects + // must be valid until the accept's handler is invoked. + template + void async_move_accept(implementation_type& impl, + const PeerIoExecutor& peer_io_ex, endpoint_type* peer_endpoint, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_move_accept_op< + protocol_type, PeerIoExecutor, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + bool enable_connection_aborted = + (impl.state_ & socket_ops::enable_connection_aborted) != 0; + p.p = new (p.v) op(*this, impl.socket_, impl.protocol_, + peer_io_ex, peer_endpoint, enable_connection_aborted, + handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_accept")); + + start_accept_op(impl, false, p.p->new_socket(), + impl.protocol_.family(), impl.protocol_.type(), + impl.protocol_.protocol(), p.p->output_buffer(), + p.p->address_length(), p.p); + p.v = p.p = 0; + } +#endif // defined(ASIO_HAS_MOVE) + + // Connect the socket to the specified endpoint. + asio::error_code connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + socket_ops::sync_connect(impl.socket_, + peer_endpoint.data(), peer_endpoint.size(), ec); + return ec; + } + + // Start an asynchronous connect. + template + void async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_connect_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.socket_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_connect")); + + start_connect_op(impl, impl.protocol_.family(), impl.protocol_.type(), + peer_endpoint.data(), static_cast(peer_endpoint.size()), p.p); + p.v = p.p = 0; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service_base.hpp new file mode 100644 index 00000000..0f35c81f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_socket_service_base.hpp @@ -0,0 +1,600 @@ +// +// detail/win_iocp_socket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP +#define ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/operation.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/select_reactor.hpp" +#include "asio/detail/socket_holder.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/win_iocp_io_context.hpp" +#include "asio/detail/win_iocp_null_buffers_op.hpp" +#include "asio/detail/win_iocp_socket_connect_op.hpp" +#include "asio/detail/win_iocp_socket_send_op.hpp" +#include "asio/detail/win_iocp_socket_recv_op.hpp" +#include "asio/detail/win_iocp_socket_recvmsg_op.hpp" +#include "asio/detail/win_iocp_wait_op.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_iocp_socket_service_base +{ +public: + // The implementation type of the socket. + struct base_implementation_type + { + // The native socket representation. + socket_type socket_; + + // The current state of the socket. + socket_ops::state_type state_; + + // We use a shared pointer as a cancellation token here to work around the + // broken Windows support for cancellation. MSDN says that when you call + // closesocket any outstanding WSARecv or WSASend operations will complete + // with the error ERROR_OPERATION_ABORTED. In practice they complete with + // ERROR_NETNAME_DELETED, which means you can't tell the difference between + // a local cancellation and the socket being hard-closed by the peer. + socket_ops::shared_cancel_token_type cancel_token_; + + // Per-descriptor data used by the reactor. + select_reactor::per_descriptor_data reactor_data_; + +#if defined(ASIO_ENABLE_CANCELIO) + // The ID of the thread from which it is safe to cancel asynchronous + // operations. 0 means no asynchronous operations have been started yet. + // ~0 means asynchronous operations have been started from more than one + // thread, and cancellation is not supported for the socket. + DWORD safe_cancellation_thread_id_; +#endif // defined(ASIO_ENABLE_CANCELIO) + + // Pointers to adjacent socket implementations in linked list. + base_implementation_type* next_; + base_implementation_type* prev_; + }; + + // Constructor. + ASIO_DECL win_iocp_socket_service_base(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void base_shutdown(); + + // Construct a new socket implementation. + ASIO_DECL void construct(base_implementation_type& impl); + + // Move-construct a new socket implementation. + ASIO_DECL void base_move_construct(base_implementation_type& impl, + base_implementation_type& other_impl) ASIO_NOEXCEPT; + + // Move-assign from another socket implementation. + ASIO_DECL void base_move_assign(base_implementation_type& impl, + win_iocp_socket_service_base& other_service, + base_implementation_type& other_impl); + + // Destroy a socket implementation. + ASIO_DECL void destroy(base_implementation_type& impl); + + // Determine whether the socket is open. + bool is_open(const base_implementation_type& impl) const + { + return impl.socket_ != invalid_socket; + } + + // Destroy a socket implementation. + ASIO_DECL asio::error_code close( + base_implementation_type& impl, asio::error_code& ec); + + // Release ownership of the socket. + ASIO_DECL socket_type release( + base_implementation_type& impl, asio::error_code& ec); + + // Cancel all operations associated with the socket. + ASIO_DECL asio::error_code cancel( + base_implementation_type& impl, asio::error_code& ec); + + // Determine whether the socket is at the out-of-band data mark. + bool at_mark(const base_implementation_type& impl, + asio::error_code& ec) const + { + return socket_ops::sockatmark(impl.socket_, ec); + } + + // Determine the number of bytes available for reading. + std::size_t available(const base_implementation_type& impl, + asio::error_code& ec) const + { + return socket_ops::available(impl.socket_, ec); + } + + // Place the socket into the state where it will listen for new connections. + asio::error_code listen(base_implementation_type& impl, + int backlog, asio::error_code& ec) + { + socket_ops::listen(impl.socket_, backlog, ec); + return ec; + } + + // Perform an IO control command on the socket. + template + asio::error_code io_control(base_implementation_type& impl, + IO_Control_Command& command, asio::error_code& ec) + { + socket_ops::ioctl(impl.socket_, impl.state_, command.name(), + static_cast(command.data()), ec); + return ec; + } + + // Gets the non-blocking mode of the socket. + bool non_blocking(const base_implementation_type& impl) const + { + return (impl.state_ & socket_ops::user_set_non_blocking) != 0; + } + + // Sets the non-blocking mode of the socket. + asio::error_code non_blocking(base_implementation_type& impl, + bool mode, asio::error_code& ec) + { + socket_ops::set_user_non_blocking(impl.socket_, impl.state_, mode, ec); + return ec; + } + + // Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const base_implementation_type& impl) const + { + return (impl.state_ & socket_ops::internal_non_blocking) != 0; + } + + // Sets the non-blocking mode of the native socket implementation. + asio::error_code native_non_blocking(base_implementation_type& impl, + bool mode, asio::error_code& ec) + { + socket_ops::set_internal_non_blocking(impl.socket_, impl.state_, mode, ec); + return ec; + } + + // Wait for the socket to become ready to read, ready to write, or to have + // pending error conditions. + asio::error_code wait(base_implementation_type& impl, + socket_base::wait_type w, asio::error_code& ec) + { + switch (w) + { + case socket_base::wait_read: + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + break; + case socket_base::wait_write: + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + break; + case socket_base::wait_error: + socket_ops::poll_error(impl.socket_, impl.state_, -1, ec); + break; + default: + ec = asio::error::invalid_argument; + break; + } + + return ec; + } + + // Asynchronously wait for the socket to become ready to read, ready to + // write, or to have pending error conditions. + template + void async_wait(base_implementation_type& impl, + socket_base::wait_type w, Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_wait_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_wait")); + + switch (w) + { + case socket_base::wait_read: + start_null_buffers_receive_op(impl, 0, p.p); + break; + case socket_base::wait_write: + start_reactor_op(impl, select_reactor::write_op, p.p); + break; + case socket_base::wait_error: + start_reactor_op(impl, select_reactor::except_op, p.p); + break; + default: + p.p->ec_ = asio::error::invalid_argument; + iocp_service_.post_immediate_completion(p.p, is_continuation); + break; + } + + p.v = p.p = 0; + } + + // Send the given data to the peer. Returns the number of bytes sent. + template + size_t send(base_implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_send(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); + } + + // Wait until data can be sent without blocking. + size_t send(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_write(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send(base_implementation_type& impl, + const ConstBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_send_op< + ConstBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_send")); + + buffer_sequence_adapter bufs(buffers); + + start_send_op(impl, bufs.buffers(), bufs.count(), flags, + (impl.state_ & socket_ops::stream_oriented) != 0 && bufs.all_empty(), + p.p); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_send(null_buffers)")); + + start_reactor_op(impl, select_reactor::write_op, p.p); + p.v = p.p = 0; + } + + // Receive some data from the peer. Returns the number of bytes received. + template + size_t receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_recv(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), flags, bufs.all_empty(), ec); + } + + // Wait until data can be received without blocking. + size_t receive(base_implementation_type& impl, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recv_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.state_, impl.cancel_token_, + buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive")); + + buffer_sequence_adapter bufs(buffers); + + start_receive_op(impl, bufs.buffers(), bufs.count(), flags, + (impl.state_ & socket_ops::stream_oriented) != 0 && bufs.all_empty(), + p.p); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive(null_buffers)")); + + start_null_buffers_receive_op(impl, flags, p.p); + p.v = p.p = 0; + } + + // Receive some data with associated flags. Returns the number of bytes + // received. + template + size_t receive_with_flags(base_implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + buffer_sequence_adapter bufs(buffers); + + return socket_ops::sync_recvmsg(impl.socket_, impl.state_, + bufs.buffers(), bufs.count(), in_flags, out_flags, ec); + } + + // Wait until data can be received without blocking. + size_t receive_with_flags(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags, + socket_base::message_flags& out_flags, asio::error_code& ec) + { + // Wait for socket to become ready. + socket_ops::poll_read(impl.socket_, impl.state_, -1, ec); + + // Clear out_flags, since we cannot give it any other sensible value when + // performing a null_buffers operation. + out_flags = 0; + + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive_with_flags(base_implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_socket_recvmsg_op< + MutableBufferSequence, Handler, IoExecutor> op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, + buffers, out_flags, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive_with_flags")); + + buffer_sequence_adapter bufs(buffers); + + start_receive_op(impl, bufs.buffers(), bufs.count(), in_flags, false, p.p); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive_with_flags(base_implementation_type& impl, + const null_buffers&, socket_base::message_flags in_flags, + socket_base::message_flags& out_flags, Handler& handler, + const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef win_iocp_null_buffers_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(impl.cancel_token_, handler, io_ex); + + ASIO_HANDLER_CREATION((context_, *p.p, "socket", + &impl, impl.socket_, "async_receive_with_flags(null_buffers)")); + + // Reset out_flags since it can be given no sensible value at this time. + out_flags = 0; + + start_null_buffers_receive_op(impl, in_flags, p.p); + p.v = p.p = 0; + } + + // Helper function to restart an asynchronous accept operation. + ASIO_DECL void restart_accept_op(socket_type s, + socket_holder& new_socket, int family, int type, int protocol, + void* output_buffer, DWORD address_length, operation* op); + +protected: + // Open a new socket implementation. + ASIO_DECL asio::error_code do_open( + base_implementation_type& impl, int family, int type, + int protocol, asio::error_code& ec); + + // Assign a native socket to a socket implementation. + ASIO_DECL asio::error_code do_assign( + base_implementation_type& impl, int type, + socket_type native_socket, asio::error_code& ec); + + // Helper function to start an asynchronous send operation. + ASIO_DECL void start_send_op(base_implementation_type& impl, + WSABUF* buffers, std::size_t buffer_count, + socket_base::message_flags flags, bool noop, operation* op); + + // Helper function to start an asynchronous send_to operation. + ASIO_DECL void start_send_to_op(base_implementation_type& impl, + WSABUF* buffers, std::size_t buffer_count, + const socket_addr_type* addr, int addrlen, + socket_base::message_flags flags, operation* op); + + // Helper function to start an asynchronous receive operation. + ASIO_DECL void start_receive_op(base_implementation_type& impl, + WSABUF* buffers, std::size_t buffer_count, + socket_base::message_flags flags, bool noop, operation* op); + + // Helper function to start an asynchronous null_buffers receive operation. + ASIO_DECL void start_null_buffers_receive_op( + base_implementation_type& impl, + socket_base::message_flags flags, reactor_op* op); + + // Helper function to start an asynchronous receive_from operation. + ASIO_DECL void start_receive_from_op(base_implementation_type& impl, + WSABUF* buffers, std::size_t buffer_count, socket_addr_type* addr, + socket_base::message_flags flags, int* addrlen, operation* op); + + // Helper function to start an asynchronous accept operation. + ASIO_DECL void start_accept_op(base_implementation_type& impl, + bool peer_is_open, socket_holder& new_socket, int family, int type, + int protocol, void* output_buffer, DWORD address_length, operation* op); + + // Start an asynchronous read or write operation using the reactor. + ASIO_DECL void start_reactor_op(base_implementation_type& impl, + int op_type, reactor_op* op); + + // Start the asynchronous connect operation using the reactor. + ASIO_DECL void start_connect_op(base_implementation_type& impl, + int family, int type, const socket_addr_type* remote_addr, + std::size_t remote_addrlen, win_iocp_socket_connect_op_base* op); + + // Helper function to close a socket when the associated object is being + // destroyed. + ASIO_DECL void close_for_destruction(base_implementation_type& impl); + + // Update the ID of the thread from which cancellation is safe. + ASIO_DECL void update_cancellation_thread_id( + base_implementation_type& impl); + + // Helper function to get the reactor. If no reactor has been created yet, a + // new one is obtained from the execution context and a pointer to it is + // cached in this service. + ASIO_DECL select_reactor& get_reactor(); + + // The type of a ConnectEx function pointer, as old SDKs may not provide it. + typedef BOOL (PASCAL *connect_ex_fn)(SOCKET, + const socket_addr_type*, int, void*, DWORD, DWORD*, OVERLAPPED*); + + // Helper function to get the ConnectEx pointer. If no ConnectEx pointer has + // been obtained yet, one is obtained using WSAIoctl and the pointer is + // cached. Returns a null pointer if ConnectEx is not available. + ASIO_DECL connect_ex_fn get_connect_ex( + base_implementation_type& impl, int type); + + // The type of a NtSetInformationFile function pointer. + typedef LONG (NTAPI *nt_set_info_fn)(HANDLE, ULONG_PTR*, void*, ULONG, ULONG); + + // Helper function to get the NtSetInformationFile function pointer. If no + // NtSetInformationFile pointer has been obtained yet, one is obtained using + // GetProcAddress and the pointer is cached. Returns a null pointer if + // NtSetInformationFile is not available. + ASIO_DECL nt_set_info_fn get_nt_set_info(); + + // Helper function to emulate InterlockedCompareExchangePointer functionality + // for: + // - very old Platform SDKs; and + // - platform SDKs where MSVC's /Wp64 option causes spurious warnings. + ASIO_DECL void* interlocked_compare_exchange_pointer( + void** dest, void* exch, void* cmp); + + // Helper function to emulate InterlockedExchangePointer functionality for: + // - very old Platform SDKs; and + // - platform SDKs where MSVC's /Wp64 option causes spurious warnings. + ASIO_DECL void* interlocked_exchange_pointer(void** dest, void* val); + + // The execution context used to obtain the reactor, if required. + execution_context& context_; + + // The IOCP service used for running asynchronous operations and dispatching + // handlers. + win_iocp_io_context& iocp_service_; + + // The reactor used for performing connect operations. This object is created + // only if needed. + select_reactor* reactor_; + + // Pointer to ConnectEx implementation. + void* connect_ex_; + + // Pointer to NtSetInformationFile implementation. + void* nt_set_info_; + + // Mutex to protect access to the linked list of implementations. + asio::detail::mutex mutex_; + + // The head of a linked list of all implementations. + base_implementation_type* impl_list_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_iocp_socket_service_base.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_thread_info.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_thread_info.hpp new file mode 100644 index 00000000..ccb63a55 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_thread_info.hpp @@ -0,0 +1,34 @@ +// +// detail/win_iocp_thread_info.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP +#define ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/thread_info_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct win_iocp_thread_info : public thread_info_base +{ +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_wait_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_wait_op.hpp new file mode 100644 index 00000000..528dc3c0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_iocp_wait_op.hpp @@ -0,0 +1,123 @@ +// +// detail/win_iocp_wait_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_IOCP_WAIT_OP_HPP +#define ASIO_DETAIL_WIN_IOCP_WAIT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_IOCP) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/reactor_op.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class win_iocp_wait_op : public reactor_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(win_iocp_wait_op); + + win_iocp_wait_op(socket_ops::weak_cancel_token_type cancel_token, + Handler& handler, const IoExecutor& io_ex) + : reactor_op(&win_iocp_wait_op::do_perform, + &win_iocp_wait_op::do_complete), + cancel_token_(cancel_token), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static status do_perform(reactor_op*) + { + return done; + } + + static void do_complete(void* owner, operation* base, + const asio::error_code& result_ec, + std::size_t /*bytes_transferred*/) + { + asio::error_code ec(result_ec); + + // Take ownership of the operation object. + win_iocp_wait_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // The reactor may have stored a result in the operation object. + if (o->ec_) + ec = o->ec_; + + // Map non-portable errors to their portable counterparts. + if (ec.value() == ERROR_NETNAME_DELETED) + { + if (o->cancel_token_.expired()) + ec = asio::error::operation_aborted; + else + ec = asio::error::connection_reset; + } + else if (ec.value() == ERROR_PORT_UNREACHABLE) + { + ec = asio::error::connection_refused; + } + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, ec); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + socket_ops::weak_cancel_token_type cancel_token_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_IOCP) + +#endif // ASIO_DETAIL_WIN_IOCP_WAIT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_mutex.hpp new file mode 100644 index 00000000..769e60aa --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_mutex.hpp @@ -0,0 +1,78 @@ +// +// detail/win_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_MUTEX_HPP +#define ASIO_DETAIL_WIN_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_lock.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_mutex + : private noncopyable +{ +public: + typedef asio::detail::scoped_lock scoped_lock; + + // Constructor. + ASIO_DECL win_mutex(); + + // Destructor. + ~win_mutex() + { + ::DeleteCriticalSection(&crit_section_); + } + + // Lock the mutex. + void lock() + { + ::EnterCriticalSection(&crit_section_); + } + + // Unlock the mutex. + void unlock() + { + ::LeaveCriticalSection(&crit_section_); + } + +private: + // Initialisation must be performed in a separate function to the constructor + // since the compiler does not support the use of structured exceptions and + // C++ exceptions in the same function. + ASIO_DECL int do_init(); + + ::CRITICAL_SECTION crit_section_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_mutex.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + +#endif // ASIO_DETAIL_WIN_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_object_handle_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_object_handle_service.hpp new file mode 100644 index 00000000..3decb0db --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_object_handle_service.hpp @@ -0,0 +1,195 @@ +// +// detail/win_object_handle_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2011 Boris Schaeling (boris@highscore.de) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP +#define ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/wait_handler.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class win_object_handle_service : + public execution_context_service_base +{ +public: + // The native type of an object handle. + typedef HANDLE native_handle_type; + + // The implementation type of the object handle. + class implementation_type + { + public: + // Default constructor. + implementation_type() + : handle_(INVALID_HANDLE_VALUE), + wait_handle_(INVALID_HANDLE_VALUE), + owner_(0), + next_(0), + prev_(0) + { + } + + private: + // Only this service will have access to the internal values. + friend class win_object_handle_service; + + // The native object handle representation. May be accessed or modified + // without locking the mutex. + native_handle_type handle_; + + // The handle used to unregister the wait operation. The mutex must be + // locked when accessing or modifying this member. + HANDLE wait_handle_; + + // The operations waiting on the object handle. If there is a registered + // wait then the mutex must be locked when accessing or modifying this + // member + op_queue op_queue_; + + // The service instance that owns the object handle implementation. + win_object_handle_service* owner_; + + // Pointers to adjacent handle implementations in linked list. The mutex + // must be locked when accessing or modifying these members. + implementation_type* next_; + implementation_type* prev_; + }; + + // Constructor. + ASIO_DECL win_object_handle_service(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Construct a new handle implementation. + ASIO_DECL void construct(implementation_type& impl); + + // Move-construct a new handle implementation. + ASIO_DECL void move_construct(implementation_type& impl, + implementation_type& other_impl); + + // Move-assign from another handle implementation. + ASIO_DECL void move_assign(implementation_type& impl, + win_object_handle_service& other_service, + implementation_type& other_impl); + + // Destroy a handle implementation. + ASIO_DECL void destroy(implementation_type& impl); + + // Assign a native handle to a handle implementation. + ASIO_DECL asio::error_code assign(implementation_type& impl, + const native_handle_type& handle, asio::error_code& ec); + + // Determine whether the handle is open. + bool is_open(const implementation_type& impl) const + { + return impl.handle_ != INVALID_HANDLE_VALUE && impl.handle_ != 0; + } + + // Destroy a handle implementation. + ASIO_DECL asio::error_code close(implementation_type& impl, + asio::error_code& ec); + + // Get the native handle representation. + native_handle_type native_handle(const implementation_type& impl) const + { + return impl.handle_; + } + + // Cancel all operations associated with the handle. + ASIO_DECL asio::error_code cancel(implementation_type& impl, + asio::error_code& ec); + + // Perform a synchronous wait for the object to enter a signalled state. + ASIO_DECL void wait(implementation_type& impl, + asio::error_code& ec); + + /// Start an asynchronous wait. + template + void async_wait(implementation_type& impl, + Handler& handler, const IoExecutor& io_ex) + { + // Allocate and construct an operation to wrap the handler. + typedef wait_handler op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), *p.p, "object_handle", + &impl, reinterpret_cast(impl.wait_handle_), "async_wait")); + + start_wait_op(impl, p.p); + p.v = p.p = 0; + } + +private: + // Helper function to start an asynchronous wait operation. + ASIO_DECL void start_wait_op(implementation_type& impl, wait_op* op); + + // Helper function to register a wait operation. + ASIO_DECL void register_wait_callback( + implementation_type& impl, mutex::scoped_lock& lock); + + // Callback function invoked when the registered wait completes. + static ASIO_DECL VOID CALLBACK wait_callback( + PVOID param, BOOLEAN timeout); + + // The scheduler used to post completions. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + + // Mutex to protect access to internal state. + mutex mutex_; + + // The head of a linked list of all implementations. + implementation_type* impl_list_; + + // Flag to indicate that the dispatcher has been shut down. + bool shutdown_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_object_handle_service.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + +#endif // ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_static_mutex.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_static_mutex.hpp new file mode 100644 index 00000000..81eda822 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_static_mutex.hpp @@ -0,0 +1,74 @@ +// +// detail/win_static_mutex.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_STATIC_MUTEX_HPP +#define ASIO_DETAIL_WIN_STATIC_MUTEX_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) + +#include "asio/detail/scoped_lock.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct win_static_mutex +{ + typedef asio::detail::scoped_lock scoped_lock; + + // Initialise the mutex. + ASIO_DECL void init(); + + // Initialisation must be performed in a separate function to the "public" + // init() function since the compiler does not support the use of structured + // exceptions and C++ exceptions in the same function. + ASIO_DECL int do_init(); + + // Lock the mutex. + void lock() + { + ::EnterCriticalSection(&crit_section_); + } + + // Unlock the mutex. + void unlock() + { + ::LeaveCriticalSection(&crit_section_); + } + + bool initialised_; + ::CRITICAL_SECTION crit_section_; +}; + +#if defined(UNDER_CE) +# define ASIO_WIN_STATIC_MUTEX_INIT { false, { 0, 0, 0, 0, 0 } } +#else // defined(UNDER_CE) +# define ASIO_WIN_STATIC_MUTEX_INIT { false, { 0, 0, 0, 0, 0, 0 } } +#endif // defined(UNDER_CE) + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_static_mutex.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + +#endif // ASIO_DETAIL_WIN_STATIC_MUTEX_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_thread.hpp new file mode 100644 index 00000000..ddba812c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_thread.hpp @@ -0,0 +1,147 @@ +// +// detail/win_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_THREAD_HPP +#define ASIO_DETAIL_WIN_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) \ + && !defined(ASIO_WINDOWS_APP) \ + && !defined(UNDER_CE) + +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +ASIO_DECL unsigned int __stdcall win_thread_function(void* arg); + +#if defined(WINVER) && (WINVER < 0x0500) +ASIO_DECL void __stdcall apc_function(ULONG data); +#else +ASIO_DECL void __stdcall apc_function(ULONG_PTR data); +#endif + +template +class win_thread_base +{ +public: + static bool terminate_threads() + { + return ::InterlockedExchangeAdd(&terminate_threads_, 0) != 0; + } + + static void set_terminate_threads(bool b) + { + ::InterlockedExchange(&terminate_threads_, b ? 1 : 0); + } + +private: + static long terminate_threads_; +}; + +template +long win_thread_base::terminate_threads_ = 0; + +class win_thread + : private noncopyable, + public win_thread_base +{ +public: + // Constructor. + template + win_thread(Function f, unsigned int stack_size = 0) + : thread_(0), + exit_event_(0) + { + start_thread(new func(f), stack_size); + } + + // Destructor. + ASIO_DECL ~win_thread(); + + // Wait for the thread to exit. + ASIO_DECL void join(); + + // Get number of CPUs. + ASIO_DECL static std::size_t hardware_concurrency(); + +private: + friend ASIO_DECL unsigned int __stdcall win_thread_function(void* arg); + +#if defined(WINVER) && (WINVER < 0x0500) + friend ASIO_DECL void __stdcall apc_function(ULONG); +#else + friend ASIO_DECL void __stdcall apc_function(ULONG_PTR); +#endif + + class func_base + { + public: + virtual ~func_base() {} + virtual void run() = 0; + ::HANDLE entry_event_; + ::HANDLE exit_event_; + }; + + struct auto_func_base_ptr + { + func_base* ptr; + ~auto_func_base_ptr() { delete ptr; } + }; + + template + class func + : public func_base + { + public: + func(Function f) + : f_(f) + { + } + + virtual void run() + { + f_(); + } + + private: + Function f_; + }; + + ASIO_DECL void start_thread(func_base* arg, unsigned int stack_size); + + ::HANDLE thread_; + ::HANDLE exit_event_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_thread.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + // && !defined(ASIO_WINDOWS_APP) + // && !defined(UNDER_CE) + +#endif // ASIO_DETAIL_WIN_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_tss_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_tss_ptr.hpp new file mode 100644 index 00000000..dbe8b78e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/win_tss_ptr.hpp @@ -0,0 +1,79 @@ +// +// detail/win_tss_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WIN_TSS_PTR_HPP +#define ASIO_DETAIL_WIN_TSS_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Helper function to create thread-specific storage. +ASIO_DECL DWORD win_tss_ptr_create(); + +template +class win_tss_ptr + : private noncopyable +{ +public: + // Constructor. + win_tss_ptr() + : tss_key_(win_tss_ptr_create()) + { + } + + // Destructor. + ~win_tss_ptr() + { + ::TlsFree(tss_key_); + } + + // Get the value. + operator T*() const + { + return static_cast(::TlsGetValue(tss_key_)); + } + + // Set the value. + void operator=(T* value) + { + ::TlsSetValue(tss_key_, value); + } + +private: + // Thread-specific storage to allow unlocked access to determine whether a + // thread is a member of the pool. + DWORD tss_key_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/win_tss_ptr.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) + +#endif // ASIO_DETAIL_WIN_TSS_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winapp_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winapp_thread.hpp new file mode 100644 index 00000000..aac44cde --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winapp_thread.hpp @@ -0,0 +1,124 @@ +// +// detail/winapp_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINAPP_THREAD_HPP +#define ASIO_DETAIL_WINAPP_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) && defined(ASIO_WINDOWS_APP) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +DWORD WINAPI winapp_thread_function(LPVOID arg); + +class winapp_thread + : private noncopyable +{ +public: + // Constructor. + template + winapp_thread(Function f, unsigned int = 0) + { + scoped_ptr arg(new func(f)); + DWORD thread_id = 0; + thread_ = ::CreateThread(0, 0, winapp_thread_function, + arg.get(), 0, &thread_id); + if (!thread_) + { + DWORD last_error = ::GetLastError(); + asio::error_code ec(last_error, + asio::error::get_system_category()); + asio::detail::throw_error(ec, "thread"); + } + arg.release(); + } + + // Destructor. + ~winapp_thread() + { + ::CloseHandle(thread_); + } + + // Wait for the thread to exit. + void join() + { + ::WaitForSingleObjectEx(thread_, INFINITE, false); + } + + // Get number of CPUs. + static std::size_t hardware_concurrency() + { + SYSTEM_INFO system_info; + ::GetNativeSystemInfo(&system_info); + return system_info.dwNumberOfProcessors; + } + +private: + friend DWORD WINAPI winapp_thread_function(LPVOID arg); + + class func_base + { + public: + virtual ~func_base() {} + virtual void run() = 0; + }; + + template + class func + : public func_base + { + public: + func(Function f) + : f_(f) + { + } + + virtual void run() + { + f_(); + } + + private: + Function f_; + }; + + ::HANDLE thread_; +}; + +inline DWORD WINAPI winapp_thread_function(LPVOID arg) +{ + scoped_ptr func( + static_cast(arg)); + func->run(); + return 0; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS) && defined(ASIO_WINDOWS_APP) + +#endif // ASIO_DETAIL_WINAPP_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wince_thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wince_thread.hpp new file mode 100644 index 00000000..c2386644 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wince_thread.hpp @@ -0,0 +1,124 @@ +// +// detail/wince_thread.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINCE_THREAD_HPP +#define ASIO_DETAIL_WINCE_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) && defined(UNDER_CE) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +DWORD WINAPI wince_thread_function(LPVOID arg); + +class wince_thread + : private noncopyable +{ +public: + // Constructor. + template + wince_thread(Function f, unsigned int = 0) + { + scoped_ptr arg(new func(f)); + DWORD thread_id = 0; + thread_ = ::CreateThread(0, 0, wince_thread_function, + arg.get(), 0, &thread_id); + if (!thread_) + { + DWORD last_error = ::GetLastError(); + asio::error_code ec(last_error, + asio::error::get_system_category()); + asio::detail::throw_error(ec, "thread"); + } + arg.release(); + } + + // Destructor. + ~wince_thread() + { + ::CloseHandle(thread_); + } + + // Wait for the thread to exit. + void join() + { + ::WaitForSingleObject(thread_, INFINITE); + } + + // Get number of CPUs. + static std::size_t hardware_concurrency() + { + SYSTEM_INFO system_info; + ::GetSystemInfo(&system_info); + return system_info.dwNumberOfProcessors; + } + +private: + friend DWORD WINAPI wince_thread_function(LPVOID arg); + + class func_base + { + public: + virtual ~func_base() {} + virtual void run() = 0; + }; + + template + class func + : public func_base + { + public: + func(Function f) + : f_(f) + { + } + + virtual void run() + { + f_(); + } + + private: + Function f_; + }; + + ::HANDLE thread_; +}; + +inline DWORD WINAPI wince_thread_function(LPVOID arg) +{ + scoped_ptr func( + static_cast(arg)); + func->run(); + return 0; +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS) && defined(UNDER_CE) + +#endif // ASIO_DETAIL_WINCE_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_manager.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_manager.hpp new file mode 100644 index 00000000..cf624baf --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_manager.hpp @@ -0,0 +1,305 @@ +// +// detail/winrt_async_manager.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_ASYNC_MANAGER_HPP +#define ASIO_DETAIL_WINRT_ASYNC_MANAGER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/winrt_async_op.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class winrt_async_manager + : public execution_context_service_base +{ +public: + // Constructor. + winrt_async_manager(execution_context& context) + : execution_context_service_base(context), + scheduler_(use_service(context)), + outstanding_ops_(1) + { + } + + // Destructor. + ~winrt_async_manager() + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + if (--outstanding_ops_ > 0) + { + // Block until last operation is complete. + std::future f = promise_.get_future(); + f.wait(); + } + } + + void sync(Windows::Foundation::IAsyncAction^ action, + asio::error_code& ec) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto promise = std::make_shared>(); + auto future = promise->get_future(); + + action->Completed = ref new AsyncActionCompletedHandler( + [promise](IAsyncAction^ action, AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + promise->set_value(asio::error::operation_aborted); + break; + case AsyncStatus::Error: + case AsyncStatus::Completed: + default: + asio::error_code ec( + action->ErrorCode.Value, + asio::system_category()); + promise->set_value(ec); + break; + } + }); + + ec = future.get(); + } + + template + TResult sync(Windows::Foundation::IAsyncOperation^ operation, + asio::error_code& ec) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto promise = std::make_shared>(); + auto future = promise->get_future(); + + operation->Completed = ref new AsyncOperationCompletedHandler( + [promise](IAsyncOperation^ operation, AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + promise->set_value(asio::error::operation_aborted); + break; + case AsyncStatus::Error: + case AsyncStatus::Completed: + default: + asio::error_code ec( + operation->ErrorCode.Value, + asio::system_category()); + promise->set_value(ec); + break; + } + }); + + ec = future.get(); + return operation->GetResults(); + } + + template + TResult sync( + Windows::Foundation::IAsyncOperationWithProgress< + TResult, TProgress>^ operation, + asio::error_code& ec) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto promise = std::make_shared>(); + auto future = promise->get_future(); + + operation->Completed + = ref new AsyncOperationWithProgressCompletedHandler( + [promise](IAsyncOperationWithProgress^ operation, + AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + promise->set_value(asio::error::operation_aborted); + break; + case AsyncStatus::Started: + break; + case AsyncStatus::Error: + case AsyncStatus::Completed: + default: + asio::error_code ec( + operation->ErrorCode.Value, + asio::system_category()); + promise->set_value(ec); + break; + } + }); + + ec = future.get(); + return operation->GetResults(); + } + + void async(Windows::Foundation::IAsyncAction^ action, + winrt_async_op* handler) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto on_completed = ref new AsyncActionCompletedHandler( + [this, handler](IAsyncAction^ action, AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + handler->ec_ = asio::error::operation_aborted; + break; + case AsyncStatus::Started: + return; + case AsyncStatus::Completed: + case AsyncStatus::Error: + default: + handler->ec_ = asio::error_code( + action->ErrorCode.Value, + asio::system_category()); + break; + } + scheduler_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + scheduler_.work_started(); + ++outstanding_ops_; + action->Completed = on_completed; + } + + template + void async(Windows::Foundation::IAsyncOperation^ operation, + winrt_async_op* handler) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto on_completed = ref new AsyncOperationCompletedHandler( + [this, handler](IAsyncOperation^ operation, AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + handler->ec_ = asio::error::operation_aborted; + break; + case AsyncStatus::Started: + return; + case AsyncStatus::Completed: + handler->result_ = operation->GetResults(); + // Fall through. + case AsyncStatus::Error: + default: + handler->ec_ = asio::error_code( + operation->ErrorCode.Value, + asio::system_category()); + break; + } + scheduler_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + scheduler_.work_started(); + ++outstanding_ops_; + operation->Completed = on_completed; + } + + template + void async( + Windows::Foundation::IAsyncOperationWithProgress< + TResult, TProgress>^ operation, + winrt_async_op* handler) + { + using namespace Windows::Foundation; + using Windows::Foundation::AsyncStatus; + + auto on_completed + = ref new AsyncOperationWithProgressCompletedHandler( + [this, handler](IAsyncOperationWithProgress< + TResult, TProgress>^ operation, AsyncStatus status) + { + switch (status) + { + case AsyncStatus::Canceled: + handler->ec_ = asio::error::operation_aborted; + break; + case AsyncStatus::Started: + return; + case AsyncStatus::Completed: + handler->result_ = operation->GetResults(); + // Fall through. + case AsyncStatus::Error: + default: + handler->ec_ = asio::error_code( + operation->ErrorCode.Value, + asio::system_category()); + break; + } + scheduler_.post_deferred_completion(handler); + if (--outstanding_ops_ == 0) + promise_.set_value(); + }); + + scheduler_.work_started(); + ++outstanding_ops_; + operation->Completed = on_completed; + } + +private: + // The scheduler implementation used to post completed handlers. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + + // Count of outstanding operations. + atomic_count outstanding_ops_; + + // Used to keep wait for outstanding operations to complete. + std::promise promise_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_ASYNC_MANAGER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_op.hpp new file mode 100644 index 00000000..f90f26f9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_async_op.hpp @@ -0,0 +1,65 @@ +// +// detail/winrt_async_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_ASYNC_OP_HPP +#define ASIO_DETAIL_WINRT_ASYNC_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/operation.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_async_op + : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + + // The result of the operation, to be passed to the completion handler. + TResult result_; + +protected: + winrt_async_op(func_type complete_func) + : operation(complete_func), + result_() + { + } +}; + +template <> +class winrt_async_op + : public operation +{ +public: + // The error code to be passed to the completion handler. + asio::error_code ec_; + +protected: + winrt_async_op(func_type complete_func) + : operation(complete_func) + { + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WINRT_ASYNC_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolve_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolve_op.hpp new file mode 100644 index 00000000..c6e9bc7b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolve_op.hpp @@ -0,0 +1,121 @@ +// +// detail/winrt_resolve_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_RESOLVE_OP_HPP +#define ASIO_DETAIL_WINRT_RESOLVE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/winrt_async_op.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_resolve_op : + public winrt_async_op< + Windows::Foundation::Collections::IVectorView< + Windows::Networking::EndpointPair^>^> +{ +public: + ASIO_DEFINE_HANDLER_PTR(winrt_resolve_op); + + typedef typename Protocol::endpoint endpoint_type; + typedef asio::ip::basic_resolver_query query_type; + typedef asio::ip::basic_resolver_results results_type; + + winrt_resolve_op(const query_type& query, + Handler& handler, const IoExecutor& io_ex) + : winrt_async_op< + Windows::Foundation::Collections::IVectorView< + Windows::Networking::EndpointPair^>^>( + &winrt_resolve_op::do_complete), + query_(query), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code&, std::size_t) + { + // Take ownership of the operation object. + winrt_resolve_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + results_type results = results_type(); + if (!o->ec_) + { + try + { + results = results_type::create(o->result_, o->query_.hints(), + o->query_.host_name(), o->query_.service_name()); + } + catch (Platform::Exception^ e) + { + o->ec_ = asio::error_code(e->HResult, + asio::system_category()); + } + } + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, results); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + query_type query_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_RESOLVE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolver_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolver_service.hpp new file mode 100644 index 00000000..1f4b70a2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_resolver_service.hpp @@ -0,0 +1,212 @@ +// +// detail/winrt_resolver_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_RESOLVER_SERVICE_HPP +#define ASIO_DETAIL_WINRT_RESOLVER_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/post.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/winrt_async_manager.hpp" +#include "asio/detail/winrt_resolve_op.hpp" +#include "asio/detail/winrt_utils.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_resolver_service : + public execution_context_service_base > +{ +public: + // The implementation type of the resolver. A cancellation token is used to + // indicate to the asynchronous operation that the operation has been + // cancelled. + typedef socket_ops::shared_cancel_token_type implementation_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The query type. + typedef asio::ip::basic_resolver_query query_type; + + // The results type. + typedef asio::ip::basic_resolver_results results_type; + + // Constructor. + winrt_resolver_service(execution_context& context) + : execution_context_service_base< + winrt_resolver_service >(context), + scheduler_(use_service(context)), + async_manager_(use_service(context)) + { + } + + // Destructor. + ~winrt_resolver_service() + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + } + + // Perform any fork-related housekeeping. + void notify_fork(execution_context::fork_event) + { + } + + // Construct a new resolver implementation. + void construct(implementation_type&) + { + } + + // Move-construct a new resolver implementation. + void move_construct(implementation_type&, + implementation_type&) + { + } + + // Move-assign from another resolver implementation. + void move_assign(implementation_type&, + winrt_resolver_service&, implementation_type&) + { + } + + // Destroy a resolver implementation. + void destroy(implementation_type&) + { + } + + // Cancel pending asynchronous operations. + void cancel(implementation_type&) + { + } + + // Resolve a query to a list of entries. + results_type resolve(implementation_type&, + const query_type& query, asio::error_code& ec) + { + try + { + using namespace Windows::Networking::Sockets; + auto endpoint_pairs = async_manager_.sync( + DatagramSocket::GetEndpointPairsAsync( + winrt_utils::host_name(query.host_name()), + winrt_utils::string(query.service_name())), ec); + + if (ec) + return results_type(); + + return results_type::create( + endpoint_pairs, query.hints(), + query.host_name(), query.service_name()); + } + catch (Platform::Exception^ e) + { + ec = asio::error_code(e->HResult, + asio::system_category()); + return results_type(); + } + } + + // Asynchronously resolve a query to a list of entries. + template + void async_resolve(implementation_type& impl, const query_type& query, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef winrt_resolve_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(query, handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "resolver", &impl, 0, "async_resolve")); + (void)impl; + + try + { + using namespace Windows::Networking::Sockets; + async_manager_.async(DatagramSocket::GetEndpointPairsAsync( + winrt_utils::host_name(query.host_name()), + winrt_utils::string(query.service_name())), p.p); + p.v = p.p = 0; + } + catch (Platform::Exception^ e) + { + p.p->ec_ = asio::error_code( + e->HResult, asio::system_category()); + scheduler_.post_immediate_completion(p.p, is_continuation); + p.v = p.p = 0; + } + } + + // Resolve an endpoint to a list of entries. + results_type resolve(implementation_type&, + const endpoint_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return results_type(); + } + + // Asynchronously resolve an endpoint to a list of entries. + template + void async_resolve(implementation_type&, const endpoint_type&, + Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const results_type results; + asio::post(io_ex, detail::bind_handler(handler, ec, results)); + } + +private: + // The scheduler implementation used for delivering completions. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + + winrt_async_manager& async_manager_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_RESOLVER_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_connect_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_connect_op.hpp new file mode 100644 index 00000000..c5ef90f8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_connect_op.hpp @@ -0,0 +1,94 @@ +// +// detail/winrt_socket_connect_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_SOCKET_CONNECT_OP_HPP +#define ASIO_DETAIL_WINRT_SOCKET_CONNECT_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/winrt_async_op.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_socket_connect_op : + public winrt_async_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(winrt_socket_connect_op); + + winrt_socket_connect_op(Handler& handler, const IoExecutor& io_ex) + : winrt_async_op(&winrt_socket_connect_op::do_complete), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code&, std::size_t) + { + // Take ownership of the operation object. + winrt_socket_connect_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder1 + handler(o->handler_, o->ec_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_SOCKET_CONNECT_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_recv_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_recv_op.hpp new file mode 100644 index 00000000..613edab0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_recv_op.hpp @@ -0,0 +1,115 @@ +// +// detail/winrt_socket_recv_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_SOCKET_RECV_OP_HPP +#define ASIO_DETAIL_WINRT_SOCKET_RECV_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/winrt_async_op.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_socket_recv_op : + public winrt_async_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(winrt_socket_recv_op); + + winrt_socket_recv_op(const MutableBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : winrt_async_op( + &winrt_socket_recv_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code&, std::size_t) + { + // Take ownership of the operation object. + winrt_socket_recv_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + std::size_t bytes_transferred = o->result_ ? o->result_->Length : 0; + if (bytes_transferred == 0 && !o->ec_ && + !buffer_sequence_adapter::all_empty(o->buffers_)) + { + o->ec_ = asio::error::eof; + } + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, bytes_transferred); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + MutableBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_SOCKET_RECV_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_send_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_send_op.hpp new file mode 100644 index 00000000..c19254a2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_socket_send_op.hpp @@ -0,0 +1,106 @@ +// +// detail/winrt_socket_send_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_SOCKET_SEND_OP_HPP +#define ASIO_DETAIL_WINRT_SOCKET_SEND_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/winrt_async_op.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_socket_send_op : + public winrt_async_op +{ +public: + ASIO_DEFINE_HANDLER_PTR(winrt_socket_send_op); + + winrt_socket_send_op(const ConstBufferSequence& buffers, + Handler& handler, const IoExecutor& io_ex) + : winrt_async_op(&winrt_socket_send_op::do_complete), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + io_executor_(io_ex) + { + handler_work::start(handler_, io_executor_); + } + + static void do_complete(void* owner, operation* base, + const asio::error_code&, std::size_t) + { + // Take ownership of the operation object. + winrt_socket_send_op* o(static_cast(base)); + ptr p = { asio::detail::addressof(o->handler_), o, o }; + handler_work w(o->handler_, o->io_executor_); + + ASIO_HANDLER_COMPLETION((*o)); + +#if defined(ASIO_ENABLE_BUFFER_DEBUGGING) + // Check whether buffers are still valid. + if (owner) + { + buffer_sequence_adapter::validate(o->buffers_); + } +#endif // defined(ASIO_ENABLE_BUFFER_DEBUGGING) + + // Make a copy of the handler so that the memory can be deallocated before + // the upcall is made. Even if we're not about to make an upcall, a + // sub-object of the handler may be the true owner of the memory associated + // with the handler. Consequently, a local copy of the handler is required + // to ensure that any owning sub-object remains valid until after we have + // deallocated the memory here. + detail::binder2 + handler(o->handler_, o->ec_, o->result_); + p.h = asio::detail::addressof(handler.handler_); + p.reset(); + + // Make the upcall if required. + if (owner) + { + fenced_block b(fenced_block::half); + ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); + w.complete(handler, handler.handler_); + ASIO_HANDLER_INVOCATION_END; + } + } + +private: + ConstBufferSequence buffers_; + Handler handler_; + IoExecutor io_executor_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_SOCKET_SEND_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service.hpp new file mode 100644 index 00000000..2b3163dc --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service.hpp @@ -0,0 +1,250 @@ +// +// detail/winrt_ssocket_service.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_SSOCKET_SERVICE_HPP +#define ASIO_DETAIL_WINRT_SSOCKET_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/winrt_socket_connect_op.hpp" +#include "asio/detail/winrt_ssocket_service_base.hpp" +#include "asio/detail/winrt_utils.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class winrt_ssocket_service : + public execution_context_service_base >, + public winrt_ssocket_service_base +{ +public: + // The protocol type. + typedef Protocol protocol_type; + + // The endpoint type. + typedef typename Protocol::endpoint endpoint_type; + + // The native type of a socket. + typedef Windows::Networking::Sockets::StreamSocket^ native_handle_type; + + // The implementation type of the socket. + struct implementation_type : base_implementation_type + { + // Default constructor. + implementation_type() + : base_implementation_type(), + protocol_(endpoint_type().protocol()) + { + } + + // The protocol associated with the socket. + protocol_type protocol_; + }; + + // Constructor. + winrt_ssocket_service(execution_context& context) + : execution_context_service_base >(context), + winrt_ssocket_service_base(context) + { + } + + // Destroy all user-defined handler objects owned by the service. + void shutdown() + { + this->base_shutdown(); + } + + // Move-construct a new socket implementation. + void move_construct(implementation_type& impl, + implementation_type& other_impl) ASIO_NOEXCEPT + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + } + + // Move-assign from another socket implementation. + void move_assign(implementation_type& impl, + winrt_ssocket_service& other_service, + implementation_type& other_impl) + { + this->base_move_assign(impl, other_service, other_impl); + + impl.protocol_ = other_impl.protocol_; + other_impl.protocol_ = endpoint_type().protocol(); + } + + // Move-construct a new socket implementation from another protocol type. + template + void converting_move_construct(implementation_type& impl, + winrt_ssocket_service&, + typename winrt_ssocket_service< + Protocol1>::implementation_type& other_impl) + { + this->base_move_construct(impl, other_impl); + + impl.protocol_ = protocol_type(other_impl.protocol_); + other_impl.protocol_ = typename Protocol1::endpoint().protocol(); + } + + // Open a new socket implementation. + asio::error_code open(implementation_type& impl, + const protocol_type& protocol, asio::error_code& ec) + { + if (is_open(impl)) + { + ec = asio::error::already_open; + return ec; + } + + try + { + impl.socket_ = ref new Windows::Networking::Sockets::StreamSocket; + impl.protocol_ = protocol; + ec = asio::error_code(); + } + catch (Platform::Exception^ e) + { + ec = asio::error_code(e->HResult, + asio::system_category()); + } + + return ec; + } + + // Assign a native socket to a socket implementation. + asio::error_code assign(implementation_type& impl, + const protocol_type& protocol, const native_handle_type& native_socket, + asio::error_code& ec) + { + if (is_open(impl)) + { + ec = asio::error::already_open; + return ec; + } + + impl.socket_ = native_socket; + impl.protocol_ = protocol; + ec = asio::error_code(); + + return ec; + } + + // Bind the socket to the specified local endpoint. + asio::error_code bind(implementation_type&, + const endpoint_type&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Get the local endpoint. + endpoint_type local_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint; + endpoint.resize(do_get_endpoint(impl, true, + endpoint.data(), endpoint.size(), ec)); + return endpoint; + } + + // Get the remote endpoint. + endpoint_type remote_endpoint(const implementation_type& impl, + asio::error_code& ec) const + { + endpoint_type endpoint; + endpoint.resize(do_get_endpoint(impl, false, + endpoint.data(), endpoint.size(), ec)); + return endpoint; + } + + // Disable sends or receives on the socket. + asio::error_code shutdown(implementation_type&, + socket_base::shutdown_type, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Set a socket option. + template + asio::error_code set_option(implementation_type& impl, + const Option& option, asio::error_code& ec) + { + return do_set_option(impl, option.level(impl.protocol_), + option.name(impl.protocol_), option.data(impl.protocol_), + option.size(impl.protocol_), ec); + } + + // Get a socket option. + template + asio::error_code get_option(const implementation_type& impl, + Option& option, asio::error_code& ec) const + { + std::size_t size = option.size(impl.protocol_); + do_get_option(impl, option.level(impl.protocol_), + option.name(impl.protocol_), + option.data(impl.protocol_), &size, ec); + if (!ec) + option.resize(impl.protocol_, size); + return ec; + } + + // Connect the socket to the specified endpoint. + asio::error_code connect(implementation_type& impl, + const endpoint_type& peer_endpoint, asio::error_code& ec) + { + return do_connect(impl, peer_endpoint.data(), ec); + } + + // Start an asynchronous connect. + template + void async_connect(implementation_type& impl, + const endpoint_type& peer_endpoint, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef winrt_socket_connect_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "socket", &impl, 0, "async_connect")); + + start_connect_op(impl, peer_endpoint.data(), p.p, is_continuation); + p.v = p.p = 0; + } +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_SSOCKET_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service_base.hpp new file mode 100644 index 00000000..3c9be6ed --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_ssocket_service_base.hpp @@ -0,0 +1,362 @@ +// +// detail/winrt_ssocket_service_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP +#define ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/buffer.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/socket_base.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/winrt_async_manager.hpp" +#include "asio/detail/winrt_socket_recv_op.hpp" +#include "asio/detail/winrt_socket_send_op.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class winrt_ssocket_service_base +{ +public: + // The native type of a socket. + typedef Windows::Networking::Sockets::StreamSocket^ native_handle_type; + + // The implementation type of the socket. + struct base_implementation_type + { + // Default constructor. + base_implementation_type() + : socket_(nullptr), + next_(0), + prev_(0) + { + } + + // The underlying native socket. + native_handle_type socket_; + + // Pointers to adjacent socket implementations in linked list. + base_implementation_type* next_; + base_implementation_type* prev_; + }; + + // Constructor. + ASIO_DECL winrt_ssocket_service_base(execution_context& context); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void base_shutdown(); + + // Construct a new socket implementation. + ASIO_DECL void construct(base_implementation_type&); + + // Move-construct a new socket implementation. + ASIO_DECL void base_move_construct(base_implementation_type& impl, + base_implementation_type& other_impl) ASIO_NOEXCEPT; + + // Move-assign from another socket implementation. + ASIO_DECL void base_move_assign(base_implementation_type& impl, + winrt_ssocket_service_base& other_service, + base_implementation_type& other_impl); + + // Destroy a socket implementation. + ASIO_DECL void destroy(base_implementation_type& impl); + + // Determine whether the socket is open. + bool is_open(const base_implementation_type& impl) const + { + return impl.socket_ != nullptr; + } + + // Destroy a socket implementation. + ASIO_DECL asio::error_code close( + base_implementation_type& impl, asio::error_code& ec); + + // Release ownership of the socket. + ASIO_DECL native_handle_type release( + base_implementation_type& impl, asio::error_code& ec); + + // Get the native socket representation. + native_handle_type native_handle(base_implementation_type& impl) + { + return impl.socket_; + } + + // Cancel all operations associated with the socket. + asio::error_code cancel(base_implementation_type&, + asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Determine whether the socket is at the out-of-band data mark. + bool at_mark(const base_implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return false; + } + + // Determine the number of bytes available for reading. + std::size_t available(const base_implementation_type&, + asio::error_code& ec) const + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Perform an IO control command on the socket. + template + asio::error_code io_control(base_implementation_type&, + IO_Control_Command&, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Gets the non-blocking mode of the socket. + bool non_blocking(const base_implementation_type&) const + { + return false; + } + + // Sets the non-blocking mode of the socket. + asio::error_code non_blocking(base_implementation_type&, + bool, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Gets the non-blocking mode of the native socket implementation. + bool native_non_blocking(const base_implementation_type&) const + { + return false; + } + + // Sets the non-blocking mode of the native socket implementation. + asio::error_code native_non_blocking(base_implementation_type&, + bool, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return ec; + } + + // Send the given data to the peer. + template + std::size_t send(base_implementation_type& impl, + const ConstBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return do_send(impl, + buffer_sequence_adapter::first(buffers), flags, ec); + } + + // Wait until data can be sent without blocking. + std::size_t send(base_implementation_type&, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous send. The data being sent must be valid for the + // lifetime of the asynchronous operation. + template + void async_send(base_implementation_type& impl, + const ConstBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef winrt_socket_send_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "socket", &impl, 0, "async_send")); + + start_send_op(impl, + buffer_sequence_adapter::first(buffers), + flags, p.p, is_continuation); + p.v = p.p = 0; + } + + // Start an asynchronous wait until data can be sent without blocking. + template + void async_send(base_implementation_type&, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, + detail::bind_handler(handler, ec, bytes_transferred)); + } + + // Receive some data from the peer. Returns the number of bytes received. + template + std::size_t receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, + socket_base::message_flags flags, asio::error_code& ec) + { + return do_receive(impl, + buffer_sequence_adapter::first(buffers), flags, ec); + } + + // Wait until data can be received without blocking. + std::size_t receive(base_implementation_type&, const null_buffers&, + socket_base::message_flags, asio::error_code& ec) + { + ec = asio::error::operation_not_supported; + return 0; + } + + // Start an asynchronous receive. The buffer for the data being received + // must be valid for the lifetime of the asynchronous operation. + template + void async_receive(base_implementation_type& impl, + const MutableBufferSequence& buffers, socket_base::message_flags flags, + Handler& handler, const IoExecutor& io_ex) + { + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler); + + // Allocate and construct an operation to wrap the handler. + typedef winrt_socket_recv_op op; + typename op::ptr p = { asio::detail::addressof(handler), + op::ptr::allocate(handler), 0 }; + p.p = new (p.v) op(buffers, handler, io_ex); + + ASIO_HANDLER_CREATION((scheduler_.context(), + *p.p, "socket", &impl, 0, "async_receive")); + + start_receive_op(impl, + buffer_sequence_adapter::first(buffers), + flags, p.p, is_continuation); + p.v = p.p = 0; + } + + // Wait until data can be received without blocking. + template + void async_receive(base_implementation_type&, const null_buffers&, + socket_base::message_flags, Handler& handler, const IoExecutor& io_ex) + { + asio::error_code ec = asio::error::operation_not_supported; + const std::size_t bytes_transferred = 0; + asio::post(io_ex, + detail::bind_handler(handler, ec, bytes_transferred)); + } + +protected: + // Helper function to obtain endpoints associated with the connection. + ASIO_DECL std::size_t do_get_endpoint( + const base_implementation_type& impl, bool local, + void* addr, std::size_t addr_len, asio::error_code& ec) const; + + // Helper function to set a socket option. + ASIO_DECL asio::error_code do_set_option( + base_implementation_type& impl, + int level, int optname, const void* optval, + std::size_t optlen, asio::error_code& ec); + + // Helper function to get a socket option. + ASIO_DECL void do_get_option( + const base_implementation_type& impl, + int level, int optname, void* optval, + std::size_t* optlen, asio::error_code& ec) const; + + // Helper function to perform a synchronous connect. + ASIO_DECL asio::error_code do_connect( + base_implementation_type& impl, + const void* addr, asio::error_code& ec); + + // Helper function to start an asynchronous connect. + ASIO_DECL void start_connect_op( + base_implementation_type& impl, const void* addr, + winrt_async_op* op, bool is_continuation); + + // Helper function to perform a synchronous send. + ASIO_DECL std::size_t do_send( + base_implementation_type& impl, const asio::const_buffer& data, + socket_base::message_flags flags, asio::error_code& ec); + + // Helper function to start an asynchronous send. + ASIO_DECL void start_send_op(base_implementation_type& impl, + const asio::const_buffer& data, socket_base::message_flags flags, + winrt_async_op* op, bool is_continuation); + + // Helper function to perform a synchronous receive. + ASIO_DECL std::size_t do_receive( + base_implementation_type& impl, const asio::mutable_buffer& data, + socket_base::message_flags flags, asio::error_code& ec); + + // Helper function to start an asynchronous receive. + ASIO_DECL void start_receive_op(base_implementation_type& impl, + const asio::mutable_buffer& data, socket_base::message_flags flags, + winrt_async_op* op, + bool is_continuation); + + // The scheduler implementation used for delivering completions. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + + // The manager that keeps track of outstanding operations. + winrt_async_manager& async_manager_; + + // Mutex to protect access to the linked list of implementations. + asio::detail::mutex mutex_; + + // The head of a linked list of all implementations. + base_implementation_type* impl_list_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/winrt_ssocket_service_base.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_SSOCKET_SERVICE_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_timer_scheduler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_timer_scheduler.hpp new file mode 100644 index 00000000..9f1bb8f3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_timer_scheduler.hpp @@ -0,0 +1,147 @@ +// +// detail/winrt_timer_scheduler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_TIMER_SCHEDULER_HPP +#define ASIO_DETAIL_WINRT_TIMER_SCHEDULER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include +#include "asio/detail/event.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/mutex.hpp" +#include "asio/detail/op_queue.hpp" +#include "asio/detail/thread.hpp" +#include "asio/detail/timer_queue_base.hpp" +#include "asio/detail/timer_queue_set.hpp" +#include "asio/detail/wait_op.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else // defined(ASIO_HAS_IOCP) +# include "asio/detail/scheduler.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/thread.hpp" +#endif // defined(ASIO_HAS_IOCP) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class winrt_timer_scheduler + : public execution_context_service_base +{ +public: + // Constructor. + ASIO_DECL winrt_timer_scheduler(execution_context& context); + + // Destructor. + ASIO_DECL ~winrt_timer_scheduler(); + + // Destroy all user-defined handler objects owned by the service. + ASIO_DECL void shutdown(); + + // Recreate internal descriptors following a fork. + ASIO_DECL void notify_fork(execution_context::fork_event fork_ev); + + // Initialise the task. No effect as this class uses its own thread. + ASIO_DECL void init_task(); + + // Add a new timer queue to the reactor. + template + void add_timer_queue(timer_queue& queue); + + // Remove a timer queue from the reactor. + template + void remove_timer_queue(timer_queue& queue); + + // Schedule a new operation in the given timer queue to expire at the + // specified absolute time. + template + void schedule_timer(timer_queue& queue, + const typename Time_Traits::time_type& time, + typename timer_queue::per_timer_data& timer, wait_op* op); + + // Cancel the timer operations associated with the given token. Returns the + // number of operations that have been posted or dispatched. + template + std::size_t cancel_timer(timer_queue& queue, + typename timer_queue::per_timer_data& timer, + std::size_t max_cancelled = (std::numeric_limits::max)()); + + // Move the timer operations associated with the given timer. + template + void move_timer(timer_queue& queue, + typename timer_queue::per_timer_data& to, + typename timer_queue::per_timer_data& from); + +private: + // Run the select loop in the thread. + ASIO_DECL void run_thread(); + + // Entry point for the select loop thread. + ASIO_DECL static void call_run_thread(winrt_timer_scheduler* reactor); + + // Helper function to add a new timer queue. + ASIO_DECL void do_add_timer_queue(timer_queue_base& queue); + + // Helper function to remove a timer queue. + ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue); + + // The scheduler implementation used to post completions. +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context scheduler_impl; +#else + typedef class scheduler scheduler_impl; +#endif + scheduler_impl& scheduler_; + + // Mutex used to protect internal variables. + asio::detail::mutex mutex_; + + // Event used to wake up background thread. + asio::detail::event event_; + + // The timer queues. + timer_queue_set timer_queues_; + + // The background thread that is waiting for timers to expire. + asio::detail::thread* thread_; + + // Does the background thread need to stop. + bool stop_thread_; + + // Whether the service has been shut down. + bool shutdown_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/detail/impl/winrt_timer_scheduler.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/winrt_timer_scheduler.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_TIMER_SCHEDULER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_utils.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_utils.hpp new file mode 100644 index 00000000..bfdccb4d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winrt_utils.hpp @@ -0,0 +1,106 @@ +// +// detail/winrt_utils.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINRT_UTILS_HPP +#define ASIO_DETAIL_WINRT_UTILS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) + +#include +#include +#include +#include +#include +#include +#include +#include "asio/buffer.hpp" +#include "asio/error_code.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/socket_ops.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { +namespace winrt_utils { + +inline Platform::String^ string(const char* from) +{ + std::wstring tmp(from, from + std::strlen(from)); + return ref new Platform::String(tmp.c_str()); +} + +inline Platform::String^ string(const std::string& from) +{ + std::wstring tmp(from.begin(), from.end()); + return ref new Platform::String(tmp.c_str()); +} + +inline std::string string(Platform::String^ from) +{ + std::wstring_convert> converter; + return converter.to_bytes(from->Data()); +} + +inline Platform::String^ string(unsigned short from) +{ + return string(std::to_string(from)); +} + +template +inline Platform::String^ string(const T& from) +{ + return string(from.to_string()); +} + +inline int integer(Platform::String^ from) +{ + return _wtoi(from->Data()); +} + +template +inline Windows::Networking::HostName^ host_name(const T& from) +{ + return ref new Windows::Networking::HostName((string)(from)); +} + +template +inline Windows::Storage::Streams::IBuffer^ buffer_dup( + const ConstBufferSequence& buffers) +{ + using Microsoft::WRL::ComPtr; + using asio::buffer_size; + std::size_t size = buffer_size(buffers); + auto b = ref new Windows::Storage::Streams::Buffer(size); + ComPtr insp = reinterpret_cast(b); + ComPtr bacc; + insp.As(&bacc); + byte* bytes = nullptr; + bacc->Buffer(&bytes); + asio::buffer_copy(asio::buffer(bytes, size), buffers); + b->Length = size; + return b; +} + +} // namespace winrt_utils +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#endif // ASIO_DETAIL_WINRT_UTILS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winsock_init.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winsock_init.hpp new file mode 100644 index 00000000..f95b9843 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/winsock_init.hpp @@ -0,0 +1,128 @@ +// +// detail/winsock_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WINSOCK_INIT_HPP +#define ASIO_DETAIL_WINSOCK_INIT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class winsock_init_base +{ +protected: + // Structure to track result of initialisation and number of uses. POD is used + // to ensure that the values are zero-initialised prior to any code being run. + struct data + { + long init_count_; + long result_; + }; + + ASIO_DECL static void startup(data& d, + unsigned char major, unsigned char minor); + + ASIO_DECL static void manual_startup(data& d); + + ASIO_DECL static void cleanup(data& d); + + ASIO_DECL static void manual_cleanup(data& d); + + ASIO_DECL static void throw_on_error(data& d); +}; + +template +class winsock_init : private winsock_init_base +{ +public: + winsock_init(bool allow_throw = true) + { + startup(data_, Major, Minor); + if (allow_throw) + throw_on_error(data_); + } + + winsock_init(const winsock_init&) + { + startup(data_, Major, Minor); + throw_on_error(data_); + } + + ~winsock_init() + { + cleanup(data_); + } + + // This class may be used to indicate that user code will manage Winsock + // initialisation and cleanup. This may be required in the case of a DLL, for + // example, where it is not safe to initialise Winsock from global object + // constructors. + // + // To prevent asio from initialising Winsock, the object must be constructed + // before any Asio's own global objects. With MSVC, this may be accomplished + // by adding the following code to the DLL: + // + // #pragma warning(push) + // #pragma warning(disable:4073) + // #pragma init_seg(lib) + // asio::detail::winsock_init<>::manual manual_winsock_init; + // #pragma warning(pop) + class manual + { + public: + manual() + { + manual_startup(data_); + } + + manual(const manual&) + { + manual_startup(data_); + } + + ~manual() + { + manual_cleanup(data_); + } + }; + +private: + friend class manual; + static data data_; +}; + +template +winsock_init_base::data winsock_init::data_; + +// Static variable to ensure that winsock is initialised before main, and +// therefore before any other threads can get started. +static const winsock_init<>& winsock_init_instance = winsock_init<>(false); + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/detail/impl/winsock_init.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) + +#endif // ASIO_DETAIL_WINSOCK_INIT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/work_dispatcher.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/work_dispatcher.hpp new file mode 100644 index 00000000..243b8e48 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/work_dispatcher.hpp @@ -0,0 +1,73 @@ +// +// detail/work_dispatcher.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WORK_DISPATCHER_HPP +#define ASIO_DETAIL_WORK_DISPATCHER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_executor.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/executor_work_guard.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class work_dispatcher +{ +public: + template + explicit work_dispatcher(ASIO_MOVE_ARG(CompletionHandler) handler) + : work_((get_associated_executor)(handler)), + handler_(ASIO_MOVE_CAST(CompletionHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + work_dispatcher(const work_dispatcher& other) + : work_(other.work_), + handler_(other.handler_) + { + } + + work_dispatcher(work_dispatcher&& other) + : work_(ASIO_MOVE_CAST(executor_work_guard< + typename associated_executor::type>)(other.work_)), + handler_(ASIO_MOVE_CAST(Handler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + typename associated_allocator::type alloc( + (get_associated_allocator)(handler_)); + work_.get_executor().dispatch( + ASIO_MOVE_CAST(Handler)(handler_), alloc); + work_.reset(); + } + +private: + executor_work_guard::type> work_; + Handler handler_; +}; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WORK_DISPATCHER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wrapped_handler.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wrapped_handler.hpp new file mode 100644 index 00000000..c9387d24 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/detail/wrapped_handler.hpp @@ -0,0 +1,291 @@ +// +// detail/wrapped_handler.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DETAIL_WRAPPED_HANDLER_HPP +#define ASIO_DETAIL_WRAPPED_HANDLER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +struct is_continuation_delegated +{ + template + bool operator()(Dispatcher&, Handler& handler) const + { + return asio_handler_cont_helpers::is_continuation(handler); + } +}; + +struct is_continuation_if_running +{ + template + bool operator()(Dispatcher& dispatcher, Handler&) const + { + return dispatcher.running_in_this_thread(); + } +}; + +template +class wrapped_handler +{ +public: + typedef void result_type; + + wrapped_handler(Dispatcher dispatcher, Handler& handler) + : dispatcher_(dispatcher), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + wrapped_handler(const wrapped_handler& other) + : dispatcher_(other.dispatcher_), + handler_(other.handler_) + { + } + + wrapped_handler(wrapped_handler&& other) + : dispatcher_(other.dispatcher_), + handler_(ASIO_MOVE_CAST(Handler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + dispatcher_.dispatch(ASIO_MOVE_CAST(Handler)(handler_)); + } + + void operator()() const + { + dispatcher_.dispatch(handler_); + } + + template + void operator()(const Arg1& arg1) + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1)); + } + + template + void operator()(const Arg1& arg1) const + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2) + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1, arg2)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2) const + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1, arg2)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1, arg2, arg3)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) const + { + dispatcher_.dispatch(detail::bind_handler(handler_, arg1, arg2, arg3)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, + const Arg4& arg4) + { + dispatcher_.dispatch( + detail::bind_handler(handler_, arg1, arg2, arg3, arg4)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, + const Arg4& arg4) const + { + dispatcher_.dispatch( + detail::bind_handler(handler_, arg1, arg2, arg3, arg4)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, + const Arg4& arg4, const Arg5& arg5) + { + dispatcher_.dispatch( + detail::bind_handler(handler_, arg1, arg2, arg3, arg4, arg5)); + } + + template + void operator()(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, + const Arg4& arg4, const Arg5& arg5) const + { + dispatcher_.dispatch( + detail::bind_handler(handler_, arg1, arg2, arg3, arg4, arg5)); + } + +//private: + Dispatcher dispatcher_; + Handler handler_; +}; + +template +class rewrapped_handler +{ +public: + explicit rewrapped_handler(Handler& handler, const Context& context) + : context_(context), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + } + + explicit rewrapped_handler(const Handler& handler, const Context& context) + : context_(context), + handler_(handler) + { + } + +#if defined(ASIO_HAS_MOVE) + rewrapped_handler(const rewrapped_handler& other) + : context_(other.context_), + handler_(other.handler_) + { + } + + rewrapped_handler(rewrapped_handler&& other) + : context_(ASIO_MOVE_CAST(Context)(other.context_)), + handler_(ASIO_MOVE_CAST(Handler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()() + { + handler_(); + } + + void operator()() const + { + handler_(); + } + +//private: + Context context_; + Handler handler_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + wrapped_handler* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + wrapped_handler* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + wrapped_handler* this_handler) +{ + return IsContinuation()(this_handler->dispatcher_, this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + wrapped_handler* this_handler) +{ + this_handler->dispatcher_.dispatch( + rewrapped_handler( + function, this_handler->handler_)); +} + +template +inline void asio_handler_invoke(const Function& function, + wrapped_handler* this_handler) +{ + this_handler->dispatcher_.dispatch( + rewrapped_handler( + function, this_handler->handler_)); +} + +template +inline void* asio_handler_allocate(std::size_t size, + rewrapped_handler* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->context_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + rewrapped_handler* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->context_); +} + +template +inline bool asio_handler_is_continuation( + rewrapped_handler* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->context_); +} + +template +inline void asio_handler_invoke(Function& function, + rewrapped_handler* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->context_); +} + +template +inline void asio_handler_invoke(const Function& function, + rewrapped_handler* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->context_); +} + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_DETAIL_WRAPPED_HANDLER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/dispatch.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/dispatch.hpp new file mode 100644 index 00000000..27244ee7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/dispatch.hpp @@ -0,0 +1,118 @@ +// +// dispatch.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_DISPATCH_HPP +#define ASIO_DISPATCH_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the object's associated + * executor. The function object may be called from the current thread prior to + * returning from dispatch(). Otherwise, it is queued for execution. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex by performing + * get_associated_executor(handler). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Performs ex.dispatch(std::move(handler), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + ASIO_MOVE_ARG(CompletionToken) token); + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the specified executor. + * The function object may be called from the current thread prior to returning + * from dispatch(). Otherwise, it is queued for execution. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex1 by performing + * get_associated_executor(handler). + * + * @li Creates a work object @c w by performing make_work(ex1). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Constructs a function object @c f with a function call operator that + * performs ex1.dispatch(std::move(handler), alloc) followed by + * w.reset(). + * + * @li Performs Executor(ex).dispatch(std::move(f), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + const Executor& ex, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); + +/// Submits a completion token or function object for execution. +/** + * @returns dispatch(ctx.get_executor(), + * forward(token)). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + ExecutionContext& ctx, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN( + typename ExecutionContext::executor_type), + typename enable_if::value>::type* = 0); + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/dispatch.hpp" + +#endif // ASIO_DISPATCH_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error.hpp new file mode 100644 index 00000000..c70c52fe --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error.hpp @@ -0,0 +1,356 @@ +// +// error.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_ERROR_HPP +#define ASIO_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error_code.hpp" +#include "asio/system_error.hpp" +#if defined(ASIO_WINDOWS) \ + || defined(__CYGWIN__) \ + || defined(ASIO_WINDOWS_RUNTIME) +# include +#else +# include +# include +#endif + +#if defined(GENERATING_DOCUMENTATION) +/// INTERNAL ONLY. +# define ASIO_NATIVE_ERROR(e) implementation_defined +/// INTERNAL ONLY. +# define ASIO_SOCKET_ERROR(e) implementation_defined +/// INTERNAL ONLY. +# define ASIO_NETDB_ERROR(e) implementation_defined +/// INTERNAL ONLY. +# define ASIO_GETADDRINFO_ERROR(e) implementation_defined +/// INTERNAL ONLY. +# define ASIO_WIN_OR_POSIX(e_win, e_posix) implementation_defined +#elif defined(ASIO_WINDOWS_RUNTIME) +# define ASIO_NATIVE_ERROR(e) __HRESULT_FROM_WIN32(e) +# define ASIO_SOCKET_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) +# define ASIO_NETDB_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) +# define ASIO_GETADDRINFO_ERROR(e) __HRESULT_FROM_WIN32(WSA ## e) +# define ASIO_WIN_OR_POSIX(e_win, e_posix) e_win +#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# define ASIO_NATIVE_ERROR(e) e +# define ASIO_SOCKET_ERROR(e) WSA ## e +# define ASIO_NETDB_ERROR(e) WSA ## e +# define ASIO_GETADDRINFO_ERROR(e) WSA ## e +# define ASIO_WIN_OR_POSIX(e_win, e_posix) e_win +#else +# define ASIO_NATIVE_ERROR(e) e +# define ASIO_SOCKET_ERROR(e) e +# define ASIO_NETDB_ERROR(e) e +# define ASIO_GETADDRINFO_ERROR(e) e +# define ASIO_WIN_OR_POSIX(e_win, e_posix) e_posix +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace error { + +enum basic_errors +{ + /// Permission denied. + access_denied = ASIO_SOCKET_ERROR(EACCES), + + /// Address family not supported by protocol. + address_family_not_supported = ASIO_SOCKET_ERROR(EAFNOSUPPORT), + + /// Address already in use. + address_in_use = ASIO_SOCKET_ERROR(EADDRINUSE), + + /// Transport endpoint is already connected. + already_connected = ASIO_SOCKET_ERROR(EISCONN), + + /// Operation already in progress. + already_started = ASIO_SOCKET_ERROR(EALREADY), + + /// Broken pipe. + broken_pipe = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_BROKEN_PIPE), + ASIO_NATIVE_ERROR(EPIPE)), + + /// A connection has been aborted. + connection_aborted = ASIO_SOCKET_ERROR(ECONNABORTED), + + /// Connection refused. + connection_refused = ASIO_SOCKET_ERROR(ECONNREFUSED), + + /// Connection reset by peer. + connection_reset = ASIO_SOCKET_ERROR(ECONNRESET), + + /// Bad file descriptor. + bad_descriptor = ASIO_SOCKET_ERROR(EBADF), + + /// Bad address. + fault = ASIO_SOCKET_ERROR(EFAULT), + + /// No route to host. + host_unreachable = ASIO_SOCKET_ERROR(EHOSTUNREACH), + + /// Operation now in progress. + in_progress = ASIO_SOCKET_ERROR(EINPROGRESS), + + /// Interrupted system call. + interrupted = ASIO_SOCKET_ERROR(EINTR), + + /// Invalid argument. + invalid_argument = ASIO_SOCKET_ERROR(EINVAL), + + /// Message too long. + message_size = ASIO_SOCKET_ERROR(EMSGSIZE), + + /// The name was too long. + name_too_long = ASIO_SOCKET_ERROR(ENAMETOOLONG), + + /// Network is down. + network_down = ASIO_SOCKET_ERROR(ENETDOWN), + + /// Network dropped connection on reset. + network_reset = ASIO_SOCKET_ERROR(ENETRESET), + + /// Network is unreachable. + network_unreachable = ASIO_SOCKET_ERROR(ENETUNREACH), + + /// Too many open files. + no_descriptors = ASIO_SOCKET_ERROR(EMFILE), + + /// No buffer space available. + no_buffer_space = ASIO_SOCKET_ERROR(ENOBUFS), + + /// Cannot allocate memory. + no_memory = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_OUTOFMEMORY), + ASIO_NATIVE_ERROR(ENOMEM)), + + /// Operation not permitted. + no_permission = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_ACCESS_DENIED), + ASIO_NATIVE_ERROR(EPERM)), + + /// Protocol not available. + no_protocol_option = ASIO_SOCKET_ERROR(ENOPROTOOPT), + + /// No such device. + no_such_device = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_BAD_UNIT), + ASIO_NATIVE_ERROR(ENODEV)), + + /// Transport endpoint is not connected. + not_connected = ASIO_SOCKET_ERROR(ENOTCONN), + + /// Socket operation on non-socket. + not_socket = ASIO_SOCKET_ERROR(ENOTSOCK), + + /// Operation cancelled. + operation_aborted = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_OPERATION_ABORTED), + ASIO_NATIVE_ERROR(ECANCELED)), + + /// Operation not supported. + operation_not_supported = ASIO_SOCKET_ERROR(EOPNOTSUPP), + + /// Cannot send after transport endpoint shutdown. + shut_down = ASIO_SOCKET_ERROR(ESHUTDOWN), + + /// Connection timed out. + timed_out = ASIO_SOCKET_ERROR(ETIMEDOUT), + + /// Resource temporarily unavailable. + try_again = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(ERROR_RETRY), + ASIO_NATIVE_ERROR(EAGAIN)), + + /// The socket is marked non-blocking and the requested operation would block. + would_block = ASIO_SOCKET_ERROR(EWOULDBLOCK) +}; + +enum netdb_errors +{ + /// Host not found (authoritative). + host_not_found = ASIO_NETDB_ERROR(HOST_NOT_FOUND), + + /// Host not found (non-authoritative). + host_not_found_try_again = ASIO_NETDB_ERROR(TRY_AGAIN), + + /// The query is valid but does not have associated address data. + no_data = ASIO_NETDB_ERROR(NO_DATA), + + /// A non-recoverable error occurred. + no_recovery = ASIO_NETDB_ERROR(NO_RECOVERY) +}; + +enum addrinfo_errors +{ + /// The service is not supported for the given socket type. + service_not_found = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(WSATYPE_NOT_FOUND), + ASIO_GETADDRINFO_ERROR(EAI_SERVICE)), + + /// The socket type is not supported. + socket_type_not_supported = ASIO_WIN_OR_POSIX( + ASIO_NATIVE_ERROR(WSAESOCKTNOSUPPORT), + ASIO_GETADDRINFO_ERROR(EAI_SOCKTYPE)) +}; + +enum misc_errors +{ + /// Already open. + already_open = 1, + + /// End of file or stream. + eof, + + /// Element not found. + not_found, + + /// The descriptor cannot fit into the select system call's fd_set. + fd_set_failure +}; + +inline const asio::error_category& get_system_category() +{ + return asio::system_category(); +} + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +extern ASIO_DECL +const asio::error_category& get_netdb_category(); + +extern ASIO_DECL +const asio::error_category& get_addrinfo_category(); + +#else // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +inline const asio::error_category& get_netdb_category() +{ + return get_system_category(); +} + +inline const asio::error_category& get_addrinfo_category() +{ + return get_system_category(); +} + +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +extern ASIO_DECL +const asio::error_category& get_misc_category(); + +static const asio::error_category& + system_category ASIO_UNUSED_VARIABLE + = asio::error::get_system_category(); +static const asio::error_category& + netdb_category ASIO_UNUSED_VARIABLE + = asio::error::get_netdb_category(); +static const asio::error_category& + addrinfo_category ASIO_UNUSED_VARIABLE + = asio::error::get_addrinfo_category(); +static const asio::error_category& + misc_category ASIO_UNUSED_VARIABLE + = asio::error::get_misc_category(); + +} // namespace error +} // namespace asio + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) +namespace std { + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +} // namespace std +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +namespace asio { +namespace error { + +inline asio::error_code make_error_code(basic_errors e) +{ + return asio::error_code( + static_cast(e), get_system_category()); +} + +inline asio::error_code make_error_code(netdb_errors e) +{ + return asio::error_code( + static_cast(e), get_netdb_category()); +} + +inline asio::error_code make_error_code(addrinfo_errors e) +{ + return asio::error_code( + static_cast(e), get_addrinfo_category()); +} + +inline asio::error_code make_error_code(misc_errors e) +{ + return asio::error_code( + static_cast(e), get_misc_category()); +} + +} // namespace error +namespace stream_errc { + // Simulates the proposed stream_errc scoped enum. + using error::eof; + using error::not_found; +} // namespace stream_errc +namespace socket_errc { + // Simulates the proposed socket_errc scoped enum. + using error::already_open; + using error::not_found; +} // namespace socket_errc +namespace resolver_errc { + // Simulates the proposed resolver_errc scoped enum. + using error::host_not_found; + const error::netdb_errors try_again = error::host_not_found_try_again; + using error::service_not_found; +} // namespace resolver_errc +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#undef ASIO_NATIVE_ERROR +#undef ASIO_SOCKET_ERROR +#undef ASIO_NETDB_ERROR +#undef ASIO_GETADDRINFO_ERROR +#undef ASIO_WIN_OR_POSIX + +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/error.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error_code.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error_code.hpp new file mode 100644 index 00000000..4b22ecb0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/error_code.hpp @@ -0,0 +1,206 @@ +// +// error_code.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_ERROR_CODE_HPP +#define ASIO_ERROR_CODE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#ifdef ESP_PLATFORM +# include "lwip/sockets.h" +#endif + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) +# include +#else // defined(ASIO_HAS_STD_SYSTEM_ERROR) +# include +# include "asio/detail/noncopyable.hpp" +# if !defined(ASIO_NO_IOSTREAM) +# include +# endif // !defined(ASIO_NO_IOSTREAM) +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) + +typedef std::error_category error_category; + +#else // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +/// Base class for all error categories. +class error_category : private noncopyable +{ +public: + /// Destructor. + virtual ~error_category() + { + } + + /// Returns a string naming the error gategory. + virtual const char* name() const = 0; + + /// Returns a string describing the error denoted by @c value. + virtual std::string message(int value) const = 0; + + /// Equality operator to compare two error categories. + bool operator==(const error_category& rhs) const + { + return this == &rhs; + } + + /// Inequality operator to compare two error categories. + bool operator!=(const error_category& rhs) const + { + return !(*this == rhs); + } +}; + +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +/// Returns the error category used for the system errors produced by asio. +extern ASIO_DECL const error_category& system_category(); + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) + +typedef std::error_code error_code; + +#else // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +/// Class to represent an error code value. +class error_code +{ +public: + /// Default constructor. + error_code() + : value_(0), + category_(&system_category()) + { + } + + /// Construct with specific error code and category. + error_code(int v, const error_category& c) + : value_(v), + category_(&c) + { + } + + /// Construct from an error code enum. + template + error_code(ErrorEnum e) + { + *this = make_error_code(e); + } + + /// Clear the error value to the default. + void clear() + { + value_ = 0; + category_ = &system_category(); + } + + /// Assign a new error value. + void assign(int v, const error_category& c) + { + value_ = v; + category_ = &c; + } + + /// Get the error value. + int value() const + { + return value_; + } + + /// Get the error category. + const error_category& category() const + { + return *category_; + } + + /// Get the message associated with the error. + std::string message() const + { + return category_->message(value_); + } + + struct unspecified_bool_type_t + { + }; + + typedef void (*unspecified_bool_type)(unspecified_bool_type_t); + + static void unspecified_bool_true(unspecified_bool_type_t) {} + + /// Operator returns non-null if there is a non-success error code. + operator unspecified_bool_type() const + { + if (value_ == 0) + return 0; + else + return &error_code::unspecified_bool_true; + } + + /// Operator to test if the error represents success. + bool operator!() const + { + return value_ == 0; + } + + /// Equality operator to compare two error objects. + friend bool operator==(const error_code& e1, const error_code& e2) + { + return e1.value_ == e2.value_ && e1.category_ == e2.category_; + } + + /// Inequality operator to compare two error objects. + friend bool operator!=(const error_code& e1, const error_code& e2) + { + return e1.value_ != e2.value_ || e1.category_ != e2.category_; + } + +private: + // The value associated with the error code. + int value_; + + // The category associated with the error code. + const error_category* category_; +}; + +# if !defined(ASIO_NO_IOSTREAM) + +/// Output an error code. +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const error_code& ec) +{ + os << ec.category().name() << ':' << ec.value(); + return os; +} + +# endif // !defined(ASIO_NO_IOSTREAM) + +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/error_code.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_ERROR_CODE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/execution_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/execution_context.hpp new file mode 100644 index 00000000..7e7f70ac --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/execution_context.hpp @@ -0,0 +1,412 @@ +// +// execution_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXECUTION_CONTEXT_HPP +#define ASIO_EXECUTION_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/variadic_templates.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class execution_context; +class io_context; + +#if !defined(GENERATING_DOCUMENTATION) +template Service& use_service(execution_context&); +template Service& use_service(io_context&); +template void add_service(execution_context&, Service*); +template bool has_service(execution_context&); +#endif // !defined(GENERATING_DOCUMENTATION) + +namespace detail { class service_registry; } + +/// A context for function object execution. +/** + * An execution context represents a place where function objects will be + * executed. An @c io_context is an example of an execution context. + * + * @par The execution_context class and services + * + * Class execution_context implements an extensible, type-safe, polymorphic set + * of services, indexed by service type. + * + * Services exist to manage the resources that are shared across an execution + * context. For example, timers may be implemented in terms of a single timer + * queue, and this queue would be stored in a service. + * + * Access to the services of an execution_context is via three function + * templates, use_service(), add_service() and has_service(). + * + * In a call to @c use_service(), the type argument chooses a service, + * making available all members of the named type. If @c Service is not present + * in an execution_context, an object of type @c Service is created and added + * to the execution_context. A C++ program can check if an execution_context + * implements a particular service with the function template @c + * has_service(). + * + * Service objects may be explicitly added to an execution_context using the + * function template @c add_service(). If the @c Service is already + * present, the service_already_exists exception is thrown. If the owner of the + * service is not the same object as the execution_context parameter, the + * invalid_service_owner exception is thrown. + * + * Once a service reference is obtained from an execution_context object by + * calling use_service(), that reference remains usable as long as the owning + * execution_context object exists. + * + * All service implementations have execution_context::service as a public base + * class. Custom services may be implemented by deriving from this class and + * then added to an execution_context using the facilities described above. + * + * @par The execution_context as a base class + * + * Class execution_context may be used only as a base class for concrete + * execution context types. The @c io_context is an example of such a derived + * type. + * + * On destruction, a class that is derived from execution_context must perform + * execution_context::shutdown() followed by + * execution_context::destroy(). + * + * This destruction sequence permits programs to simplify their resource + * management by using @c shared_ptr<>. Where an object's lifetime is tied to + * the lifetime of a connection (or some other sequence of asynchronous + * operations), a @c shared_ptr to the object would be bound into the handlers + * for all asynchronous operations associated with it. This works as follows: + * + * @li When a single connection ends, all associated asynchronous operations + * complete. The corresponding handler objects are destroyed, and all @c + * shared_ptr references to the objects are destroyed. + * + * @li To shut down the whole program, the io_context function stop() is called + * to terminate any run() calls as soon as possible. The io_context destructor + * calls @c shutdown() and @c destroy() to destroy all pending handlers, + * causing all @c shared_ptr references to all connection objects to be + * destroyed. + */ +class execution_context + : private noncopyable +{ +public: + class id; + class service; + +public: + /// Constructor. + ASIO_DECL execution_context(); + + /// Destructor. + ASIO_DECL ~execution_context(); + +protected: + /// Shuts down all services in the context. + /** + * This function is implemented as follows: + * + * @li For each service object @c svc in the execution_context set, in + * reverse order of the beginning of service object lifetime, performs @c + * svc->shutdown(). + */ + ASIO_DECL void shutdown(); + + /// Destroys all services in the context. + /** + * This function is implemented as follows: + * + * @li For each service object @c svc in the execution_context set, in + * reverse order * of the beginning of service object lifetime, performs + * delete static_cast(svc). + */ + ASIO_DECL void destroy(); + +public: + /// Fork-related event notifications. + enum fork_event + { + /// Notify the context that the process is about to fork. + fork_prepare, + + /// Notify the context that the process has forked and is the parent. + fork_parent, + + /// Notify the context that the process has forked and is the child. + fork_child + }; + + /// Notify the execution_context of a fork-related event. + /** + * This function is used to inform the execution_context that the process is + * about to fork, or has just forked. This allows the execution_context, and + * the services it contains, to perform any necessary housekeeping to ensure + * correct operation following a fork. + * + * This function must not be called while any other execution_context + * function, or any function associated with the execution_context's derived + * class, is being called in another thread. It is, however, safe to call + * this function from within a completion handler, provided no other thread + * is accessing the execution_context or its derived class. + * + * @param event A fork-related event. + * + * @throws asio::system_error Thrown on failure. If the notification + * fails the execution_context object should no longer be used and should be + * destroyed. + * + * @par Example + * The following code illustrates how to incorporate the notify_fork() + * function: + * @code my_execution_context.notify_fork(execution_context::fork_prepare); + * if (fork() == 0) + * { + * // This is the child process. + * my_execution_context.notify_fork(execution_context::fork_child); + * } + * else + * { + * // This is the parent process. + * my_execution_context.notify_fork(execution_context::fork_parent); + * } @endcode + * + * @note For each service object @c svc in the execution_context set, + * performs svc->notify_fork();. When processing the fork_prepare + * event, services are visited in reverse order of the beginning of service + * object lifetime. Otherwise, services are visited in order of the beginning + * of service object lifetime. + */ + ASIO_DECL void notify_fork(fork_event event); + + /// Obtain the service object corresponding to the given type. + /** + * This function is used to locate a service object that corresponds to the + * given service type. If there is no existing implementation of the service, + * then the execution_context will create a new instance of the service. + * + * @param e The execution_context object that owns the service. + * + * @return The service interface implementing the specified service type. + * Ownership of the service interface is not transferred to the caller. + */ + template + friend Service& use_service(execution_context& e); + + /// Obtain the service object corresponding to the given type. + /** + * This function is used to locate a service object that corresponds to the + * given service type. If there is no existing implementation of the service, + * then the io_context will create a new instance of the service. + * + * @param ioc The io_context object that owns the service. + * + * @return The service interface implementing the specified service type. + * Ownership of the service interface is not transferred to the caller. + * + * @note This overload is preserved for backwards compatibility with services + * that inherit from io_context::service. + */ + template + friend Service& use_service(io_context& ioc); + +#if defined(GENERATING_DOCUMENTATION) + + /// Creates a service object and adds it to the execution_context. + /** + * This function is used to add a service to the execution_context. + * + * @param e The execution_context object that owns the service. + * + * @param args Zero or more arguments to be passed to the service + * constructor. + * + * @throws asio::service_already_exists Thrown if a service of the + * given type is already present in the execution_context. + */ + template + friend Service& make_service(execution_context& e, Args&&... args); + +#elif defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + friend Service& make_service(execution_context& e, + ASIO_MOVE_ARG(Args)... args); + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + friend Service& make_service(execution_context& e); + +#define ASIO_PRIVATE_MAKE_SERVICE_DEF(n) \ + template \ + friend Service& make_service(execution_context& e, \ + ASIO_VARIADIC_MOVE_PARAMS(n)); \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_MAKE_SERVICE_DEF) +#undef ASIO_PRIVATE_MAKE_SERVICE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + /// (Deprecated: Use make_service().) Add a service object to the + /// execution_context. + /** + * This function is used to add a service to the execution_context. + * + * @param e The execution_context object that owns the service. + * + * @param svc The service object. On success, ownership of the service object + * is transferred to the execution_context. When the execution_context object + * is destroyed, it will destroy the service object by performing: @code + * delete static_cast(svc) @endcode + * + * @throws asio::service_already_exists Thrown if a service of the + * given type is already present in the execution_context. + * + * @throws asio::invalid_service_owner Thrown if the service's owning + * execution_context is not the execution_context object specified by the + * @c e parameter. + */ + template + friend void add_service(execution_context& e, Service* svc); + + /// Determine if an execution_context contains a specified service type. + /** + * This function is used to determine whether the execution_context contains a + * service object corresponding to the given service type. + * + * @param e The execution_context object that owns the service. + * + * @return A boolean indicating whether the execution_context contains the + * service. + */ + template + friend bool has_service(execution_context& e); + +private: + // The service registry. + asio::detail::service_registry* service_registry_; +}; + +/// Class used to uniquely identify a service. +class execution_context::id + : private noncopyable +{ +public: + /// Constructor. + id() {} +}; + +/// Base class for all io_context services. +class execution_context::service + : private noncopyable +{ +public: + /// Get the context object that owns the service. + execution_context& context(); + +protected: + /// Constructor. + /** + * @param owner The execution_context object that owns the service. + */ + ASIO_DECL service(execution_context& owner); + + /// Destructor. + ASIO_DECL virtual ~service(); + +private: + /// Destroy all user-defined handler objects owned by the service. + virtual void shutdown() = 0; + + /// Handle notification of a fork-related event to perform any necessary + /// housekeeping. + /** + * This function is not a pure virtual so that services only have to + * implement it if necessary. The default implementation does nothing. + */ + ASIO_DECL virtual void notify_fork( + execution_context::fork_event event); + + friend class asio::detail::service_registry; + struct key + { + key() : type_info_(0), id_(0) {} + const std::type_info* type_info_; + const execution_context::id* id_; + } key_; + + execution_context& owner_; + service* next_; +}; + +/// Exception thrown when trying to add a duplicate service to an +/// execution_context. +class service_already_exists + : public std::logic_error +{ +public: + ASIO_DECL service_already_exists(); +}; + +/// Exception thrown when trying to add a service object to an +/// execution_context where the service has a different owner. +class invalid_service_owner + : public std::logic_error +{ +public: + ASIO_DECL invalid_service_owner(); +}; + +namespace detail { + +// Special derived service id type to keep classes header-file only. +template +class service_id + : public execution_context::id +{ +}; + +// Special service base class to keep classes header-file only. +template +class execution_context_service_base + : public execution_context::service +{ +public: + static service_id id; + + // Constructor. + execution_context_service_base(execution_context& e) + : execution_context::service(e) + { + } +}; + +template +service_id execution_context_service_base::id; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/execution_context.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/execution_context.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_EXECUTION_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor.hpp new file mode 100644 index 00000000..d372c067 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor.hpp @@ -0,0 +1,341 @@ +// +// executor.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXECUTOR_HPP +#define ASIO_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/cstddef.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Exception thrown when trying to access an empty polymorphic executor. +class bad_executor + : public std::exception +{ +public: + /// Constructor. + ASIO_DECL bad_executor() ASIO_NOEXCEPT; + + /// Obtain message associated with exception. + ASIO_DECL virtual const char* what() const + ASIO_NOEXCEPT_OR_NOTHROW; +}; + +/// Polymorphic wrapper for executors. +class executor +{ +public: + /// Default constructor. + executor() ASIO_NOEXCEPT + : impl_(0) + { + } + + /// Construct from nullptr. + executor(nullptr_t) ASIO_NOEXCEPT + : impl_(0) + { + } + + /// Copy constructor. + executor(const executor& other) ASIO_NOEXCEPT + : impl_(other.clone()) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + executor(executor&& other) ASIO_NOEXCEPT + : impl_(other.impl_) + { + other.impl_ = 0; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Construct a polymorphic wrapper for the specified executor. + template + executor(Executor e); + + /// Allocator-aware constructor to create a polymorphic wrapper for the + /// specified executor. + template + executor(allocator_arg_t, const Allocator& a, Executor e); + + /// Destructor. + ~executor() + { + destroy(); + } + + /// Assignment operator. + executor& operator=(const executor& other) ASIO_NOEXCEPT + { + destroy(); + impl_ = other.clone(); + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + // Move assignment operator. + executor& operator=(executor&& other) ASIO_NOEXCEPT + { + destroy(); + impl_ = other.impl_; + other.impl_ = 0; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Assignment operator for nullptr_t. + executor& operator=(nullptr_t) ASIO_NOEXCEPT + { + destroy(); + impl_ = 0; + return *this; + } + + /// Assignment operator to create a polymorphic wrapper for the specified + /// executor. + template + executor& operator=(ASIO_MOVE_ARG(Executor) e) ASIO_NOEXCEPT + { + executor tmp(ASIO_MOVE_CAST(Executor)(e)); + destroy(); + impl_ = tmp.impl_; + tmp.impl_ = 0; + return *this; + } + + /// Obtain the underlying execution context. + execution_context& context() const ASIO_NOEXCEPT + { + return get_impl()->context(); + } + + /// Inform the executor that it has some outstanding work to do. + void on_work_started() const ASIO_NOEXCEPT + { + get_impl()->on_work_started(); + } + + /// Inform the executor that some work is no longer outstanding. + void on_work_finished() const ASIO_NOEXCEPT + { + get_impl()->on_work_finished(); + } + + /// Request the executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object is executed according to the rules of the + * target executor object. + * + * @param f The function object to be called. The executor will make a copy + * of the handler object as required. The function signature of the function + * object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object is executed according to the rules of the + * target executor object. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object is executed according to the rules of the + * target executor object. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + struct unspecified_bool_type_t {}; + typedef void (*unspecified_bool_type)(unspecified_bool_type_t); + static void unspecified_bool_true(unspecified_bool_type_t) {} + + /// Operator to test if the executor contains a valid target. + operator unspecified_bool_type() const ASIO_NOEXCEPT + { + return impl_ ? &executor::unspecified_bool_true : 0; + } + + /// Obtain type information for the target executor object. + /** + * @returns If @c *this has a target type of type @c T, typeid(T); + * otherwise, typeid(void). + */ +#if !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) + const std::type_info& target_type() const ASIO_NOEXCEPT + { + return impl_ ? impl_->target_type() : typeid(void); + } +#else // !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) + const void* target_type() const ASIO_NOEXCEPT + { + return impl_ ? impl_->target_type() : 0; + } +#endif // !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) + + /// Obtain a pointer to the target executor object. + /** + * @returns If target_type() == typeid(T), a pointer to the stored + * executor target; otherwise, a null pointer. + */ + template + Executor* target() ASIO_NOEXCEPT; + + /// Obtain a pointer to the target executor object. + /** + * @returns If target_type() == typeid(T), a pointer to the stored + * executor target; otherwise, a null pointer. + */ + template + const Executor* target() const ASIO_NOEXCEPT; + + /// Compare two executors for equality. + friend bool operator==(const executor& a, + const executor& b) ASIO_NOEXCEPT + { + if (a.impl_ == b.impl_) + return true; + if (!a.impl_ || !b.impl_) + return false; + return a.impl_->equals(b.impl_); + } + + /// Compare two executors for inequality. + friend bool operator!=(const executor& a, + const executor& b) ASIO_NOEXCEPT + { + return !(a == b); + } + +private: +#if !defined(GENERATING_DOCUMENTATION) + class function; + template class impl; + +#if !defined(ASIO_NO_TYPEID) + typedef const std::type_info& type_id_result_type; +#else // !defined(ASIO_NO_TYPEID) + typedef const void* type_id_result_type; +#endif // !defined(ASIO_NO_TYPEID) + + template + static type_id_result_type type_id() + { +#if !defined(ASIO_NO_TYPEID) + return typeid(T); +#else // !defined(ASIO_NO_TYPEID) + static int unique_id; + return &unique_id; +#endif // !defined(ASIO_NO_TYPEID) + } + + // Base class for all polymorphic executor implementations. + class impl_base + { + public: + virtual impl_base* clone() const ASIO_NOEXCEPT = 0; + virtual void destroy() ASIO_NOEXCEPT = 0; + virtual execution_context& context() ASIO_NOEXCEPT = 0; + virtual void on_work_started() ASIO_NOEXCEPT = 0; + virtual void on_work_finished() ASIO_NOEXCEPT = 0; + virtual void dispatch(ASIO_MOVE_ARG(function)) = 0; + virtual void post(ASIO_MOVE_ARG(function)) = 0; + virtual void defer(ASIO_MOVE_ARG(function)) = 0; + virtual type_id_result_type target_type() const ASIO_NOEXCEPT = 0; + virtual void* target() ASIO_NOEXCEPT = 0; + virtual const void* target() const ASIO_NOEXCEPT = 0; + virtual bool equals(const impl_base* e) const ASIO_NOEXCEPT = 0; + + protected: + impl_base(bool fast_dispatch) : fast_dispatch_(fast_dispatch) {} + virtual ~impl_base() {} + + private: + friend class executor; + const bool fast_dispatch_; + }; + + // Helper function to check and return the implementation pointer. + impl_base* get_impl() const + { + if (!impl_) + { + bad_executor ex; + asio::detail::throw_exception(ex); + } + return impl_; + } + + // Helper function to clone another implementation. + impl_base* clone() const ASIO_NOEXCEPT + { + return impl_ ? impl_->clone() : 0; + } + + // Helper function to destroy an implementation. + void destroy() ASIO_NOEXCEPT + { + if (impl_) + impl_->destroy(); + } + + impl_base* impl_; +#endif // !defined(GENERATING_DOCUMENTATION) +}; + +} // namespace asio + +ASIO_USES_ALLOCATOR(asio::executor) + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/executor.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/executor.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor_work_guard.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor_work_guard.hpp new file mode 100644 index 00000000..3923d28e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/executor_work_guard.hpp @@ -0,0 +1,170 @@ +// +// executor_work_guard.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_EXECUTOR_WORK_GUARD_HPP +#define ASIO_EXECUTOR_WORK_GUARD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// An object of type @c executor_work_guard controls ownership of executor work +/// within a scope. +template +class executor_work_guard +{ +public: + /// The underlying executor type. + typedef Executor executor_type; + + /// Constructs a @c executor_work_guard object for the specified executor. + /** + * Stores a copy of @c e and calls on_work_started() on it. + */ + explicit executor_work_guard(const executor_type& e) ASIO_NOEXCEPT + : executor_(e), + owns_(true) + { + executor_.on_work_started(); + } + + /// Copy constructor. + executor_work_guard(const executor_work_guard& other) ASIO_NOEXCEPT + : executor_(other.executor_), + owns_(other.owns_) + { + if (owns_) + executor_.on_work_started(); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + executor_work_guard(executor_work_guard&& other) ASIO_NOEXCEPT + : executor_(ASIO_MOVE_CAST(Executor)(other.executor_)), + owns_(other.owns_) + { + other.owns_ = false; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor. + /** + * Unless the object has already been reset, or is in a moved-from state, + * calls on_work_finished() on the stored executor. + */ + ~executor_work_guard() + { + if (owns_) + executor_.on_work_finished(); + } + + /// Obtain the associated executor. + executor_type get_executor() const ASIO_NOEXCEPT + { + return executor_; + } + + /// Whether the executor_work_guard object owns some outstanding work. + bool owns_work() const ASIO_NOEXCEPT + { + return owns_; + } + + /// Indicate that the work is no longer outstanding. + /* + * Unless the object has already been reset, or is in a moved-from state, + * calls on_work_finished() on the stored executor. + */ + void reset() ASIO_NOEXCEPT + { + if (owns_) + { + executor_.on_work_finished(); + owns_ = false; + } + } + +private: + // Disallow assignment. + executor_work_guard& operator=(const executor_work_guard&); + + executor_type executor_; + bool owns_; +}; + +/// Create an @ref executor_work_guard object. +template +inline executor_work_guard make_work_guard(const Executor& ex, + typename enable_if::value>::type* = 0) +{ + return executor_work_guard(ex); +} + +/// Create an @ref executor_work_guard object. +template +inline executor_work_guard +make_work_guard(ExecutionContext& ctx, + typename enable_if< + is_convertible::value>::type* = 0) +{ + return executor_work_guard( + ctx.get_executor()); +} + +/// Create an @ref executor_work_guard object. +template +inline executor_work_guard::type> +make_work_guard(const T& t, + typename enable_if::value && + !is_convertible::value>::type* = 0) +{ + return executor_work_guard::type>( + associated_executor::get(t)); +} + +/// Create an @ref executor_work_guard object. +template +inline executor_work_guard::type> +make_work_guard(const T& t, const Executor& ex, + typename enable_if::value>::type* = 0) +{ + return executor_work_guard::type>( + associated_executor::get(t, ex)); +} + +/// Create an @ref executor_work_guard object. +template +inline executor_work_guard::type> +make_work_guard(const T& t, ExecutionContext& ctx, + typename enable_if::value && + !is_convertible::value && + is_convertible::value>::type* = 0) +{ + return executor_work_guard::type>( + associated_executor::get( + t, ctx.get_executor())); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_EXECUTOR_WORK_GUARD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/basic_endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/basic_endpoint.hpp new file mode 100644 index 00000000..ddedbdee --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/basic_endpoint.hpp @@ -0,0 +1,193 @@ +// +// generic/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_BASIC_ENDPOINT_HPP +#define ASIO_GENERIC_BASIC_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/generic/detail/endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { + +/// Describes an endpoint for any socket type. +/** + * The asio::generic::basic_endpoint class template describes an endpoint + * that may be associated with any socket type. + * + * @note The socket types sockaddr type must be able to fit into a + * @c sockaddr_storage structure. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * Endpoint. + */ +template +class basic_endpoint +{ +public: + /// The protocol type associated with the endpoint. + typedef Protocol protocol_type; + + /// The type of the endpoint structure. This type is dependent on the + /// underlying implementation of the socket layer. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined data_type; +#else + typedef asio::detail::socket_addr_type data_type; +#endif + + /// Default constructor. + basic_endpoint() ASIO_NOEXCEPT + { + } + + /// Construct an endpoint from the specified socket address. + basic_endpoint(const void* socket_address, + std::size_t socket_address_size, int socket_protocol = 0) + : impl_(socket_address, socket_address_size, socket_protocol) + { + } + + /// Construct an endpoint from the specific endpoint type. + template + basic_endpoint(const Endpoint& endpoint) + : impl_(endpoint.data(), endpoint.size(), endpoint.protocol().protocol()) + { + } + + /// Copy constructor. + basic_endpoint(const basic_endpoint& other) + : impl_(other.impl_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_endpoint(basic_endpoint&& other) + : impl_(other.impl_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another endpoint. + basic_endpoint& operator=(const basic_endpoint& other) + { + impl_ = other.impl_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another endpoint. + basic_endpoint& operator=(basic_endpoint&& other) + { + impl_ = other.impl_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// The protocol associated with the endpoint. + protocol_type protocol() const + { + return protocol_type(impl_.family(), impl_.protocol()); + } + + /// Get the underlying endpoint in the native type. + data_type* data() + { + return impl_.data(); + } + + /// Get the underlying endpoint in the native type. + const data_type* data() const + { + return impl_.data(); + } + + /// Get the underlying size of the endpoint in the native type. + std::size_t size() const + { + return impl_.size(); + } + + /// Set the underlying size of the endpoint in the native type. + void resize(std::size_t new_size) + { + impl_.resize(new_size); + } + + /// Get the capacity of the endpoint in the native type. + std::size_t capacity() const + { + return impl_.capacity(); + } + + /// Compare two endpoints for equality. + friend bool operator==(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e1.impl_ == e2.impl_; + } + + /// Compare two endpoints for inequality. + friend bool operator!=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e1.impl_ == e2.impl_); + } + + /// Compare endpoints for ordering. + friend bool operator<(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e1.impl_ < e2.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator>(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e2.impl_ < e1.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator<=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e2 < e1); + } + + /// Compare endpoints for ordering. + friend bool operator>=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e1 < e2); + } + +private: + // The underlying generic endpoint. + asio::generic::detail::endpoint impl_; +}; + +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_GENERIC_BASIC_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/datagram_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/datagram_protocol.hpp new file mode 100644 index 00000000..99cf8472 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/datagram_protocol.hpp @@ -0,0 +1,123 @@ +// +// generic/datagram_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_DATAGRAM_PROTOCOL_HPP +#define ASIO_GENERIC_DATAGRAM_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/basic_datagram_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/generic/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { + +/// Encapsulates the flags needed for a generic datagram-oriented socket. +/** + * The asio::generic::datagram_protocol class contains flags necessary + * for datagram-oriented sockets of any address family and protocol. + * + * @par Examples + * Constructing using a native address family and socket protocol: + * @code datagram_protocol p(AF_INET, IPPROTO_UDP); @endcode + * Constructing from a specific protocol type: + * @code datagram_protocol p(asio::ip::udp::v4()); @endcode + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class datagram_protocol +{ +public: + /// Construct a protocol object for a specific address family and protocol. + datagram_protocol(int address_family, int socket_protocol) + : family_(address_family), + protocol_(socket_protocol) + { + } + + /// Construct a generic protocol object from a specific protocol. + /** + * @throws @c bad_cast Thrown if the source protocol is not datagram-oriented. + */ + template + datagram_protocol(const Protocol& source_protocol) + : family_(source_protocol.family()), + protocol_(source_protocol.protocol()) + { + if (source_protocol.type() != type()) + { + std::bad_cast ex; + asio::detail::throw_exception(ex); + } + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_DGRAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// Compare two protocols for equality. + friend bool operator==(const datagram_protocol& p1, + const datagram_protocol& p2) + { + return p1.family_ == p2.family_ && p1.protocol_ == p2.protocol_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const datagram_protocol& p1, + const datagram_protocol& p2) + { + return !(p1 == p2); + } + + /// The type of an endpoint. + typedef basic_endpoint endpoint; + + /// The generic socket type. + typedef basic_datagram_socket socket; + +private: + int family_; + int protocol_; +}; + +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_GENERIC_DATAGRAM_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/detail/endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/detail/endpoint.hpp new file mode 100644 index 00000000..6556cc37 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/detail/endpoint.hpp @@ -0,0 +1,133 @@ +// +// generic/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_DETAIL_ENDPOINT_HPP +#define ASIO_GENERIC_DETAIL_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { +namespace detail { + +// Helper class for implementing a generic socket endpoint. +class endpoint +{ +public: + // Default constructor. + ASIO_DECL endpoint(); + + // Construct an endpoint from the specified raw bytes. + ASIO_DECL endpoint(const void* sock_addr, + std::size_t sock_addr_size, int sock_protocol); + + // Copy constructor. + endpoint(const endpoint& other) + : data_(other.data_), + size_(other.size_), + protocol_(other.protocol_) + { + } + + // Assign from another endpoint. + endpoint& operator=(const endpoint& other) + { + data_ = other.data_; + size_ = other.size_; + protocol_ = other.protocol_; + return *this; + } + + // Get the address family associated with the endpoint. + int family() const + { + return data_.base.sa_family; + } + + // Get the socket protocol associated with the endpoint. + int protocol() const + { + return protocol_; + } + + // Get the underlying endpoint in the native type. + asio::detail::socket_addr_type* data() + { + return &data_.base; + } + + // Get the underlying endpoint in the native type. + const asio::detail::socket_addr_type* data() const + { + return &data_.base; + } + + // Get the underlying size of the endpoint in the native type. + std::size_t size() const + { + return size_; + } + + // Set the underlying size of the endpoint in the native type. + ASIO_DECL void resize(std::size_t size); + + // Get the capacity of the endpoint in the native type. + std::size_t capacity() const + { + return sizeof(asio::detail::sockaddr_storage_type); + } + + // Compare two endpoints for equality. + ASIO_DECL friend bool operator==( + const endpoint& e1, const endpoint& e2); + + // Compare endpoints for ordering. + ASIO_DECL friend bool operator<( + const endpoint& e1, const endpoint& e2); + +private: + // The underlying socket address. + union data_union + { + asio::detail::socket_addr_type base; + asio::detail::sockaddr_storage_type generic; + } data_; + + // The length of the socket address stored in the endpoint. + std::size_t size_; + + // The socket protocol associated with the endpoint. + int protocol_; + + // Initialise with a specified memory. + ASIO_DECL void init(const void* sock_addr, + std::size_t sock_addr_size, int sock_protocol); +}; + +} // namespace detail +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/generic/detail/impl/endpoint.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_GENERIC_DETAIL_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/raw_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/raw_protocol.hpp new file mode 100644 index 00000000..e94e97a8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/raw_protocol.hpp @@ -0,0 +1,121 @@ +// +// generic/raw_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_RAW_PROTOCOL_HPP +#define ASIO_GENERIC_RAW_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/basic_raw_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/generic/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { + +/// Encapsulates the flags needed for a generic raw socket. +/** + * The asio::generic::raw_protocol class contains flags necessary for + * raw sockets of any address family and protocol. + * + * @par Examples + * Constructing using a native address family and socket protocol: + * @code raw_protocol p(AF_INET, IPPROTO_ICMP); @endcode + * Constructing from a specific protocol type: + * @code raw_protocol p(asio::ip::icmp::v4()); @endcode + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class raw_protocol +{ +public: + /// Construct a protocol object for a specific address family and protocol. + raw_protocol(int address_family, int socket_protocol) + : family_(address_family), + protocol_(socket_protocol) + { + } + + /// Construct a generic protocol object from a specific protocol. + /** + * @throws @c bad_cast Thrown if the source protocol is not raw-oriented. + */ + template + raw_protocol(const Protocol& source_protocol) + : family_(source_protocol.family()), + protocol_(source_protocol.protocol()) + { + if (source_protocol.type() != type()) + { + std::bad_cast ex; + asio::detail::throw_exception(ex); + } + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_RAW); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// Compare two protocols for equality. + friend bool operator==(const raw_protocol& p1, const raw_protocol& p2) + { + return p1.family_ == p2.family_ && p1.protocol_ == p2.protocol_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const raw_protocol& p1, const raw_protocol& p2) + { + return !(p1 == p2); + } + + /// The type of an endpoint. + typedef basic_endpoint endpoint; + + /// The generic socket type. + typedef basic_raw_socket socket; + +private: + int family_; + int protocol_; +}; + +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_GENERIC_RAW_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/seq_packet_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/seq_packet_protocol.hpp new file mode 100644 index 00000000..8ef566b4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/seq_packet_protocol.hpp @@ -0,0 +1,122 @@ +// +// generic/seq_packet_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_SEQ_PACKET_PROTOCOL_HPP +#define ASIO_GENERIC_SEQ_PACKET_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/basic_seq_packet_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/generic/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { + +/// Encapsulates the flags needed for a generic sequenced packet socket. +/** + * The asio::generic::seq_packet_protocol class contains flags necessary + * for seq_packet-oriented sockets of any address family and protocol. + * + * @par Examples + * Constructing using a native address family and socket protocol: + * @code seq_packet_protocol p(AF_INET, IPPROTO_SCTP); @endcode + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class seq_packet_protocol +{ +public: + /// Construct a protocol object for a specific address family and protocol. + seq_packet_protocol(int address_family, int socket_protocol) + : family_(address_family), + protocol_(socket_protocol) + { + } + + /// Construct a generic protocol object from a specific protocol. + /** + * @throws @c bad_cast Thrown if the source protocol is not based around + * sequenced packets. + */ + template + seq_packet_protocol(const Protocol& source_protocol) + : family_(source_protocol.family()), + protocol_(source_protocol.protocol()) + { + if (source_protocol.type() != type()) + { + std::bad_cast ex; + asio::detail::throw_exception(ex); + } + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_SEQPACKET); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// Compare two protocols for equality. + friend bool operator==(const seq_packet_protocol& p1, + const seq_packet_protocol& p2) + { + return p1.family_ == p2.family_ && p1.protocol_ == p2.protocol_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const seq_packet_protocol& p1, + const seq_packet_protocol& p2) + { + return !(p1 == p2); + } + + /// The type of an endpoint. + typedef basic_endpoint endpoint; + + /// The generic socket type. + typedef basic_seq_packet_socket socket; + +private: + int family_; + int protocol_; +}; + +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_GENERIC_SEQ_PACKET_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/stream_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/stream_protocol.hpp new file mode 100644 index 00000000..a44afc05 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/generic/stream_protocol.hpp @@ -0,0 +1,127 @@ +// +// generic/stream_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_GENERIC_STREAM_PROTOCOL_HPP +#define ASIO_GENERIC_STREAM_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/basic_socket_iostream.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/generic/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace generic { + +/// Encapsulates the flags needed for a generic stream-oriented socket. +/** + * The asio::generic::stream_protocol class contains flags necessary for + * stream-oriented sockets of any address family and protocol. + * + * @par Examples + * Constructing using a native address family and socket protocol: + * @code stream_protocol p(AF_INET, IPPROTO_TCP); @endcode + * Constructing from a specific protocol type: + * @code stream_protocol p(asio::ip::tcp::v4()); @endcode + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class stream_protocol +{ +public: + /// Construct a protocol object for a specific address family and protocol. + stream_protocol(int address_family, int socket_protocol) + : family_(address_family), + protocol_(socket_protocol) + { + } + + /// Construct a generic protocol object from a specific protocol. + /** + * @throws @c bad_cast Thrown if the source protocol is not stream-oriented. + */ + template + stream_protocol(const Protocol& source_protocol) + : family_(source_protocol.family()), + protocol_(source_protocol.protocol()) + { + if (source_protocol.type() != type()) + { + std::bad_cast ex; + asio::detail::throw_exception(ex); + } + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_STREAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// Compare two protocols for equality. + friend bool operator==(const stream_protocol& p1, const stream_protocol& p2) + { + return p1.family_ == p2.family_ && p1.protocol_ == p2.protocol_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const stream_protocol& p1, const stream_protocol& p2) + { + return !(p1 == p2); + } + + /// The type of an endpoint. + typedef basic_endpoint endpoint; + + /// The generic socket type. + typedef basic_stream_socket socket; + +#if !defined(ASIO_NO_IOSTREAM) + /// The generic socket iostream type. + typedef basic_socket_iostream iostream; +#endif // !defined(ASIO_NO_IOSTREAM) + +private: + int family_; + int protocol_; +}; + +} // namespace generic +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_GENERIC_STREAM_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_alloc_hook.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_alloc_hook.hpp new file mode 100644 index 00000000..68ab9091 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_alloc_hook.hpp @@ -0,0 +1,81 @@ +// +// handler_alloc_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_HANDLER_ALLOC_HOOK_HPP +#define ASIO_HANDLER_ALLOC_HOOK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default allocation function for handlers. +/** + * Asynchronous operations may need to allocate temporary objects. Since + * asynchronous operations have a handler function object, these temporary + * objects can be said to be associated with the handler. + * + * Implement asio_handler_allocate and asio_handler_deallocate for your own + * handlers to provide custom allocation for these temporary objects. + * + * The default implementation of these allocation hooks uses ::operator + * new and ::operator delete. + * + * @note All temporary objects associated with a handler will be deallocated + * before the upcall to the handler is performed. This allows the same memory to + * be reused for a subsequent asynchronous operation initiated by the handler. + * + * @par Example + * @code + * class my_handler; + * + * void* asio_handler_allocate(std::size_t size, my_handler* context) + * { + * return ::operator new(size); + * } + * + * void asio_handler_deallocate(void* pointer, std::size_t size, + * my_handler* context) + * { + * ::operator delete(pointer); + * } + * @endcode + */ +ASIO_DECL void* asio_handler_allocate( + std::size_t size, ...); + +/// Default deallocation function for handlers. +/** + * Implement asio_handler_allocate and asio_handler_deallocate for your own + * handlers to provide custom allocation for the associated temporary objects. + * + * The default implementation of these allocation hooks uses ::operator + * new and ::operator delete. + * + * @sa asio_handler_allocate. + */ +ASIO_DECL void asio_handler_deallocate( + void* pointer, std::size_t size, ...); + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/handler_alloc_hook.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_HANDLER_ALLOC_HOOK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_continuation_hook.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_continuation_hook.hpp new file mode 100644 index 00000000..46eccda6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_continuation_hook.hpp @@ -0,0 +1,54 @@ +// +// handler_continuation_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_HANDLER_CONTINUATION_HOOK_HPP +#define ASIO_HANDLER_CONTINUATION_HOOK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Default continuation function for handlers. +/** + * Asynchronous operations may represent a continuation of the asynchronous + * control flow associated with the current handler. The implementation can use + * this knowledge to optimise scheduling of the handler. + * + * Implement asio_handler_is_continuation for your own handlers to indicate + * when a handler represents a continuation. + * + * The default implementation of the continuation hook returns false. + * + * @par Example + * @code + * class my_handler; + * + * bool asio_handler_is_continuation(my_handler* context) + * { + * return true; + * } + * @endcode + */ +inline bool asio_handler_is_continuation(...) +{ + return false; +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_HANDLER_CONTINUATION_HOOK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_invoke_hook.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_invoke_hook.hpp new file mode 100644 index 00000000..013a94f6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/handler_invoke_hook.hpp @@ -0,0 +1,85 @@ +// +// handler_invoke_hook.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_HANDLER_INVOKE_HOOK_HPP +#define ASIO_HANDLER_INVOKE_HOOK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/** @defgroup asio_handler_invoke asio::asio_handler_invoke + * + * @brief Default invoke function for handlers. + * + * Completion handlers for asynchronous operations are invoked by the + * io_context associated with the corresponding object (e.g. a socket or + * deadline_timer). Certain guarantees are made on when the handler may be + * invoked, in particular that a handler can only be invoked from a thread that + * is currently calling @c run() on the corresponding io_context object. + * Handlers may subsequently be invoked through other objects (such as + * io_context::strand objects) that provide additional guarantees. + * + * When asynchronous operations are composed from other asynchronous + * operations, all intermediate handlers should be invoked using the same + * method as the final handler. This is required to ensure that user-defined + * objects are not accessed in a way that may violate the guarantees. This + * hooking function ensures that the invoked method used for the final handler + * is accessible at each intermediate step. + * + * Implement asio_handler_invoke for your own handlers to specify a custom + * invocation strategy. + * + * This default implementation invokes the function object like so: + * @code function(); @endcode + * If necessary, the default implementation makes a copy of the function object + * so that the non-const operator() can be used. + * + * @par Example + * @code + * class my_handler; + * + * template + * void asio_handler_invoke(Function function, my_handler* context) + * { + * context->strand_.dispatch(function); + * } + * @endcode + */ +/*@{*/ + +/// Default handler invocation hook used for non-const function objects. +template +inline void asio_handler_invoke(Function& function, ...) +{ + function(); +} + +/// Default handler invocation hook used for const function objects. +template +inline void asio_handler_invoke(const Function& function, ...) +{ + Function tmp(function); + tmp(); +} + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_HANDLER_INVOKE_HOOK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/high_resolution_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/high_resolution_timer.hpp new file mode 100644 index 00000000..bde0ba10 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/high_resolution_timer.hpp @@ -0,0 +1,44 @@ +// +// high_resolution_timer.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_HIGH_RESOLUTION_TIMER_HPP +#define ASIO_HIGH_RESOLUTION_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_waitable_timer.hpp" +#include "asio/detail/chrono.hpp" + +namespace asio { + +/// Typedef for a timer based on the high resolution clock. +/** + * This typedef uses the C++11 @c <chrono> standard library facility, if + * available. Otherwise, it may use the Boost.Chrono library. To explicitly + * utilise Boost.Chrono, use the basic_waitable_timer template directly: + * @code + * typedef basic_waitable_timer timer; + * @endcode + */ +typedef basic_waitable_timer< + chrono::high_resolution_clock> + high_resolution_timer; + +} // namespace asio + +#endif // defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_HIGH_RESOLUTION_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/awaitable.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/awaitable.hpp new file mode 100644 index 00000000..9bd139d1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/awaitable.hpp @@ -0,0 +1,422 @@ +// +// impl/awaitable.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_AWAITABLE_HPP +#define ASIO_IMPL_AWAITABLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include +#include "asio/detail/thread_context.hpp" +#include "asio/detail/thread_info_base.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/post.hpp" +#include "asio/system_error.hpp" +#include "asio/this_coro.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// An awaitable_thread represents a thread-of-execution that is composed of one +// or more "stack frames", with each frame represented by an awaitable_frame. +// All execution occurs in the context of the awaitable_thread's executor. An +// awaitable_thread continues to "pump" the stack frames by repeatedly resuming +// the top stack frame until the stack is empty, or until ownership of the +// stack is transferred to another awaitable_thread object. +// +// +------------------------------------+ +// | top_of_stack_ | +// | V +// +--------------+---+ +-----------------+ +// | | | | +// | awaitable_thread |<---------------------------+ awaitable_frame | +// | | attached_thread_ | | +// +--------------+---+ (Set only when +---+-------------+ +// | frames are being | +// | actively pumped | caller_ +// | by a thread, and | +// | then only for V +// | the top frame.) +-----------------+ +// | | | +// | | awaitable_frame | +// | | | +// | +---+-------------+ +// | | +// | | caller_ +// | : +// | : +// | | +// | V +// | +-----------------+ +// | bottom_of_stack_ | | +// +------------------------------->| awaitable_frame | +// | | +// +-----------------+ + +template +class awaitable_frame_base +{ +public: +#if !defined(ASIO_DISABLE_AWAITABLE_FRAME_RECYCLING) + void* operator new(std::size_t size) + { + return asio::detail::thread_info_base::allocate( + asio::detail::thread_info_base::awaitable_frame_tag(), + asio::detail::thread_context::thread_call_stack::top(), + size); + } + + void operator delete(void* pointer, std::size_t size) + { + asio::detail::thread_info_base::deallocate( + asio::detail::thread_info_base::awaitable_frame_tag(), + asio::detail::thread_context::thread_call_stack::top(), + pointer, size); + } +#endif // !defined(ASIO_DISABLE_AWAITABLE_FRAME_RECYCLING) + + // The frame starts in a suspended state until the awaitable_thread object + // pumps the stack. + auto initial_suspend() noexcept + { + return suspend_always(); + } + + // On final suspension the frame is popped from the top of the stack. + auto final_suspend() noexcept + { + struct result + { + awaitable_frame_base* this_; + + bool await_ready() const noexcept + { + return false; + } + + void await_suspend(coroutine_handle) noexcept + { + this_->pop_frame(); + } + + void await_resume() const noexcept + { + } + }; + + return result{this}; + } + + void set_except(std::exception_ptr e) noexcept + { + pending_exception_ = e; + } + + void set_error(const asio::error_code& ec) + { + this->set_except(std::make_exception_ptr(asio::system_error(ec))); + } + + void unhandled_exception() + { + set_except(std::current_exception()); + } + + void rethrow_exception() + { + if (pending_exception_) + { + std::exception_ptr ex = std::exchange(pending_exception_, nullptr); + std::rethrow_exception(ex); + } + } + + template + auto await_transform(awaitable a) const + { + return a; + } + + // This await transformation obtains the associated executor of the thread of + // execution. + auto await_transform(this_coro::executor_t) noexcept + { + struct result + { + awaitable_frame_base* this_; + + bool await_ready() const noexcept + { + return true; + } + + void await_suspend(coroutine_handle) noexcept + { + } + + auto await_resume() const noexcept + { + return this_->attached_thread_->get_executor(); + } + }; + + return result{this}; + } + + // This await transformation is used to run an async operation's initiation + // function object after the coroutine has been suspended. This ensures that + // immediate resumption of the coroutine in another thread does not cause a + // race condition. + template + auto await_transform(Function f, + typename enable_if< + is_convertible< + typename result_of::type, + awaitable_thread* + >::value + >::type* = 0) + { + struct result + { + Function function_; + awaitable_frame_base* this_; + + bool await_ready() const noexcept + { + return false; + } + + void await_suspend(coroutine_handle) noexcept + { + function_(this_); + } + + void await_resume() const noexcept + { + } + }; + + return result{std::move(f), this}; + } + + void attach_thread(awaitable_thread* handler) noexcept + { + attached_thread_ = handler; + } + + awaitable_thread* detach_thread() noexcept + { + return std::exchange(attached_thread_, nullptr); + } + + void push_frame(awaitable_frame_base* caller) noexcept + { + caller_ = caller; + attached_thread_ = caller_->attached_thread_; + attached_thread_->top_of_stack_ = this; + caller_->attached_thread_ = nullptr; + } + + void pop_frame() noexcept + { + if (caller_) + caller_->attached_thread_ = attached_thread_; + attached_thread_->top_of_stack_ = caller_; + attached_thread_ = nullptr; + caller_ = nullptr; + } + + void resume() + { + coro_.resume(); + } + + void destroy() + { + coro_.destroy(); + } + +protected: + coroutine_handle coro_ = nullptr; + awaitable_thread* attached_thread_ = nullptr; + awaitable_frame_base* caller_ = nullptr; + std::exception_ptr pending_exception_ = nullptr; +}; + +template +class awaitable_frame + : public awaitable_frame_base +{ +public: + awaitable_frame() noexcept + { + } + + awaitable_frame(awaitable_frame&& other) noexcept + : awaitable_frame_base(std::move(other)) + { + } + + ~awaitable_frame() + { + if (has_result_) + static_cast(static_cast(result_))->~T(); + } + + awaitable get_return_object() noexcept + { + this->coro_ = coroutine_handle::from_promise(*this); + return awaitable(this); + }; + + template + void return_value(U&& u) + { + new (&result_) T(std::forward(u)); + has_result_ = true; + } + + template + void return_values(Us&&... us) + { + this->return_value(std::forward_as_tuple(std::forward(us)...)); + } + + T get() + { + this->caller_ = nullptr; + this->rethrow_exception(); + return std::move(*static_cast(static_cast(result_))); + } + +private: + alignas(T) unsigned char result_[sizeof(T)]; + bool has_result_ = false; +}; + +template +class awaitable_frame + : public awaitable_frame_base +{ +public: + awaitable get_return_object() + { + this->coro_ = coroutine_handle::from_promise(*this); + return awaitable(this); + }; + + void return_void() + { + } + + void get() + { + this->caller_ = nullptr; + this->rethrow_exception(); + } +}; + +template +class awaitable_thread +{ +public: + typedef Executor executor_type; + + // Construct from the entry point of a new thread of execution. + awaitable_thread(awaitable p, const Executor& ex) + : bottom_of_stack_(std::move(p)), + top_of_stack_(bottom_of_stack_.frame_), + executor_(ex) + { + } + + // Transfer ownership from another awaitable_thread. + awaitable_thread(awaitable_thread&& other) noexcept + : bottom_of_stack_(std::move(other.bottom_of_stack_)), + top_of_stack_(std::exchange(other.top_of_stack_, nullptr)), + executor_(std::move(other.executor_)) + { + } + + // Clean up with a last ditch effort to ensure the thread is unwound within + // the context of the executor. + ~awaitable_thread() + { + if (bottom_of_stack_.valid()) + { + // Coroutine "stack unwinding" must be performed through the executor. + (post)(executor_, + [a = std::move(bottom_of_stack_)]() mutable + { + awaitable(std::move(a)); + }); + } + } + + executor_type get_executor() const noexcept + { + return executor_; + } + + // Launch a new thread of execution. + void launch() + { + top_of_stack_->attach_thread(this); + pump(); + } + +protected: + template friend class awaitable_frame_base; + + // Repeatedly resume the top stack frame until the stack is empty or until it + // has been transferred to another resumable_thread object. + void pump() + { + do top_of_stack_->resume(); while (top_of_stack_); + if (bottom_of_stack_.valid()) + { + awaitable a(std::move(bottom_of_stack_)); + a.frame_->rethrow_exception(); + } + } + + awaitable bottom_of_stack_; + awaitable_frame_base* top_of_stack_; + executor_type executor_; +}; + +} // namespace detail +} // namespace asio + +#if !defined(GENERATING_DOCUMENTATION) + +namespace std { namespace experimental { + +template +struct coroutine_traits, Args...> +{ + typedef asio::detail::awaitable_frame promise_type; +}; + +}} // namespace std::experimental + +#endif // !defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_AWAITABLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_read_stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_read_stream.hpp new file mode 100644 index 00000000..d4e0cacf --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_read_stream.hpp @@ -0,0 +1,489 @@ +// +// impl/buffered_read_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_BUFFERED_READ_STREAM_HPP +#define ASIO_IMPL_BUFFERED_READ_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +template +std::size_t buffered_read_stream::fill() +{ + detail::buffer_resize_guard + resize_guard(storage_); + std::size_t previous_size = storage_.size(); + storage_.resize(storage_.capacity()); + storage_.resize(previous_size + next_layer_.read_some(buffer( + storage_.data() + previous_size, + storage_.size() - previous_size))); + resize_guard.commit(); + return storage_.size() - previous_size; +} + +template +std::size_t buffered_read_stream::fill(asio::error_code& ec) +{ + detail::buffer_resize_guard + resize_guard(storage_); + std::size_t previous_size = storage_.size(); + storage_.resize(storage_.capacity()); + storage_.resize(previous_size + next_layer_.read_some(buffer( + storage_.data() + previous_size, + storage_.size() - previous_size), + ec)); + resize_guard.commit(); + return storage_.size() - previous_size; +} + +namespace detail +{ + template + class buffered_fill_handler + { + public: + buffered_fill_handler(detail::buffered_stream_storage& storage, + std::size_t previous_size, ReadHandler& handler) + : storage_(storage), + previous_size_(previous_size), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + buffered_fill_handler(const buffered_fill_handler& other) + : storage_(other.storage_), + previous_size_(other.previous_size_), + handler_(other.handler_) + { + } + + buffered_fill_handler(buffered_fill_handler&& other) + : storage_(other.storage_), + previous_size_(other.previous_size_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + const std::size_t bytes_transferred) + { + storage_.resize(previous_size_ + bytes_transferred); + handler_(ec, bytes_transferred); + } + + //private: + detail::buffered_stream_storage& storage_; + std::size_t previous_size_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + buffered_fill_handler* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + buffered_fill_handler* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + buffered_fill_handler* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + buffered_fill_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + buffered_fill_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_buffered_fill + { + public: + typedef typename remove_reference< + Stream>::type::lowest_layer_type::executor_type executor_type; + + explicit initiate_async_buffered_fill(Stream& next_layer) + : next_layer_(next_layer) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + buffered_stream_storage* storage) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + std::size_t previous_size = storage->size(); + storage->resize(storage->capacity()); + next_layer_.async_read_some( + buffer( + storage->data() + previous_size, + storage->size() - previous_size), + buffered_fill_handler::type>( + *storage, previous_size, handler2.value)); + } + + private: + Stream& next_layer_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::buffered_fill_handler, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::buffered_fill_handler& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::buffered_fill_handler, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::buffered_fill_handler& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) ReadHandler> +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +buffered_read_stream::async_fill( + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_buffered_fill(next_layer_), + handler, &storage_); +} + +template +template +std::size_t buffered_read_stream::read_some( + const MutableBufferSequence& buffers) +{ + using asio::buffer_size; + if (buffer_size(buffers) == 0) + return 0; + + if (storage_.empty()) + this->fill(); + + return this->copy(buffers); +} + +template +template +std::size_t buffered_read_stream::read_some( + const MutableBufferSequence& buffers, asio::error_code& ec) +{ + ec = asio::error_code(); + + using asio::buffer_size; + if (buffer_size(buffers) == 0) + return 0; + + if (storage_.empty() && !this->fill(ec)) + return 0; + + return this->copy(buffers); +} + +namespace detail +{ + template + class buffered_read_some_handler + { + public: + buffered_read_some_handler(detail::buffered_stream_storage& storage, + const MutableBufferSequence& buffers, ReadHandler& handler) + : storage_(storage), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + buffered_read_some_handler(const buffered_read_some_handler& other) + : storage_(other.storage_), + buffers_(other.buffers_), + handler_(other.handler_) + { + } + + buffered_read_some_handler(buffered_read_some_handler&& other) + : storage_(other.storage_), + buffers_(other.buffers_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, std::size_t) + { + if (ec || storage_.empty()) + { + const std::size_t length = 0; + handler_(ec, length); + } + else + { + const std::size_t bytes_copied = asio::buffer_copy( + buffers_, storage_.data(), storage_.size()); + storage_.consume(bytes_copied); + handler_(ec, bytes_copied); + } + } + + //private: + detail::buffered_stream_storage& storage_; + MutableBufferSequence buffers_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + buffered_read_some_handler< + MutableBufferSequence, ReadHandler>* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + buffered_read_some_handler< + MutableBufferSequence, ReadHandler>* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + buffered_read_some_handler< + MutableBufferSequence, ReadHandler>* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + buffered_read_some_handler< + MutableBufferSequence, ReadHandler>* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + buffered_read_some_handler< + MutableBufferSequence, ReadHandler>* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_buffered_read_some + { + public: + typedef typename remove_reference< + Stream>::type::lowest_layer_type::executor_type executor_type; + + explicit initiate_async_buffered_read_some(Stream& next_layer) + : next_layer_(next_layer) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + buffered_stream_storage* storage, + const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + using asio::buffer_size; + non_const_lvalue handler2(handler); + if (buffer_size(buffers) == 0 || !storage->empty()) + { + next_layer_.async_read_some(ASIO_MUTABLE_BUFFER(0, 0), + buffered_read_some_handler::type>( + *storage, buffers, handler2.value)); + } + else + { + initiate_async_buffered_fill(this->next_layer_)( + buffered_read_some_handler::type>( + *storage, buffers, handler2.value), + storage); + } + } + + private: + Stream& next_layer_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::buffered_read_some_handler, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::buffered_read_some_handler< + MutableBufferSequence, ReadHandler>& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::buffered_read_some_handler, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::buffered_read_some_handler< + MutableBufferSequence, ReadHandler>& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +buffered_read_stream::async_read_some( + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_buffered_read_some(next_layer_), + handler, &storage_, buffers); +} + +template +template +std::size_t buffered_read_stream::peek( + const MutableBufferSequence& buffers) +{ + if (storage_.empty()) + this->fill(); + return this->peek_copy(buffers); +} + +template +template +std::size_t buffered_read_stream::peek( + const MutableBufferSequence& buffers, asio::error_code& ec) +{ + ec = asio::error_code(); + if (storage_.empty() && !this->fill(ec)) + return 0; + return this->peek_copy(buffers); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_BUFFERED_READ_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_write_stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_write_stream.hpp new file mode 100644 index 00000000..c2c9755a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/buffered_write_stream.hpp @@ -0,0 +1,469 @@ +// +// impl/buffered_write_stream.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP +#define ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +template +std::size_t buffered_write_stream::flush() +{ + std::size_t bytes_written = write(next_layer_, + buffer(storage_.data(), storage_.size())); + storage_.consume(bytes_written); + return bytes_written; +} + +template +std::size_t buffered_write_stream::flush(asio::error_code& ec) +{ + std::size_t bytes_written = write(next_layer_, + buffer(storage_.data(), storage_.size()), + transfer_all(), ec); + storage_.consume(bytes_written); + return bytes_written; +} + +namespace detail +{ + template + class buffered_flush_handler + { + public: + buffered_flush_handler(detail::buffered_stream_storage& storage, + WriteHandler& handler) + : storage_(storage), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + buffered_flush_handler(const buffered_flush_handler& other) + : storage_(other.storage_), + handler_(other.handler_) + { + } + + buffered_flush_handler(buffered_flush_handler&& other) + : storage_(other.storage_), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + const std::size_t bytes_written) + { + storage_.consume(bytes_written); + handler_(ec, bytes_written); + } + + //private: + detail::buffered_stream_storage& storage_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + buffered_flush_handler* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + buffered_flush_handler* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + buffered_flush_handler* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + buffered_flush_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + buffered_flush_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_buffered_flush + { + public: + typedef typename remove_reference< + Stream>::type::lowest_layer_type::executor_type executor_type; + + explicit initiate_async_buffered_flush(Stream& next_layer) + : next_layer_(next_layer) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + buffered_stream_storage* storage) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + async_write(next_layer_, buffer(storage->data(), storage->size()), + buffered_flush_handler::type>( + *storage, handler2.value)); + } + + private: + Stream& next_layer_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::buffered_flush_handler, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::buffered_flush_handler& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::buffered_flush_handler, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::buffered_flush_handler& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + std::size_t)) WriteHandler> +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +buffered_write_stream::async_flush( + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_buffered_flush(next_layer_), + handler, &storage_); +} + +template +template +std::size_t buffered_write_stream::write_some( + const ConstBufferSequence& buffers) +{ + using asio::buffer_size; + if (buffer_size(buffers) == 0) + return 0; + + if (storage_.size() == storage_.capacity()) + this->flush(); + + return this->copy(buffers); +} + +template +template +std::size_t buffered_write_stream::write_some( + const ConstBufferSequence& buffers, asio::error_code& ec) +{ + ec = asio::error_code(); + + using asio::buffer_size; + if (buffer_size(buffers) == 0) + return 0; + + if (storage_.size() == storage_.capacity() && !flush(ec)) + return 0; + + return this->copy(buffers); +} + +namespace detail +{ + template + class buffered_write_some_handler + { + public: + buffered_write_some_handler(detail::buffered_stream_storage& storage, + const ConstBufferSequence& buffers, WriteHandler& handler) + : storage_(storage), + buffers_(buffers), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + buffered_write_some_handler(const buffered_write_some_handler& other) + : storage_(other.storage_), + buffers_(other.buffers_), + handler_(other.handler_) + { + } + + buffered_write_some_handler(buffered_write_some_handler&& other) + : storage_(other.storage_), + buffers_(other.buffers_), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, std::size_t) + { + if (ec) + { + const std::size_t length = 0; + handler_(ec, length); + } + else + { + using asio::buffer_size; + std::size_t orig_size = storage_.size(); + std::size_t space_avail = storage_.capacity() - orig_size; + std::size_t bytes_avail = buffer_size(buffers_); + std::size_t length = bytes_avail < space_avail + ? bytes_avail : space_avail; + storage_.resize(orig_size + length); + const std::size_t bytes_copied = asio::buffer_copy( + storage_.data() + orig_size, buffers_, length); + handler_(ec, bytes_copied); + } + } + + //private: + detail::buffered_stream_storage& storage_; + ConstBufferSequence buffers_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + buffered_write_some_handler< + ConstBufferSequence, WriteHandler>* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + buffered_write_some_handler< + ConstBufferSequence, WriteHandler>* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + buffered_write_some_handler< + ConstBufferSequence, WriteHandler>* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + buffered_write_some_handler< + ConstBufferSequence, WriteHandler>* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + buffered_write_some_handler< + ConstBufferSequence, WriteHandler>* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_buffered_write_some + { + public: + typedef typename remove_reference< + Stream>::type::lowest_layer_type::executor_type executor_type; + + explicit initiate_async_buffered_write_some(Stream& next_layer) + : next_layer_(next_layer) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + buffered_stream_storage* storage, + const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + using asio::buffer_size; + non_const_lvalue handler2(handler); + if (buffer_size(buffers) == 0 || storage->size() < storage->capacity()) + { + next_layer_.async_write_some(ASIO_CONST_BUFFER(0, 0), + buffered_write_some_handler::type>( + *storage, buffers, handler2.value)); + } + else + { + initiate_async_buffered_flush(this->next_layer_)( + buffered_write_some_handler::type>( + *storage, buffers, handler2.value), + storage); + } + } + + private: + Stream& next_layer_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::buffered_write_some_handler, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::buffered_write_some_handler< + ConstBufferSequence, WriteHandler>& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::buffered_write_some_handler, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::buffered_write_some_handler< + ConstBufferSequence, WriteHandler>& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +buffered_write_stream::async_write_some( + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_buffered_write_some(next_layer_), + handler, &storage_, buffers); +} + +template +template +std::size_t buffered_write_stream::copy( + const ConstBufferSequence& buffers) +{ + using asio::buffer_size; + std::size_t orig_size = storage_.size(); + std::size_t space_avail = storage_.capacity() - orig_size; + std::size_t bytes_avail = buffer_size(buffers); + std::size_t length = bytes_avail < space_avail ? bytes_avail : space_avail; + storage_.resize(orig_size + length); + return asio::buffer_copy( + storage_.data() + orig_size, buffers, length); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_BUFFERED_WRITE_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/co_spawn.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/co_spawn.hpp new file mode 100644 index 00000000..7360ab0c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/co_spawn.hpp @@ -0,0 +1,160 @@ +// +// impl/co_spawn.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_CO_SPAWN_HPP +#define ASIO_IMPL_CO_SPAWN_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/awaitable.hpp" +#include "asio/dispatch.hpp" +#include "asio/post.hpp" +#include "asio/use_awaitable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +awaitable co_spawn_entry_point( + awaitable*, Executor ex, F f, Handler handler) +{ + auto spawn_work = make_work_guard(ex); + auto handler_work = make_work_guard(handler, ex); + + (void) co_await (post)(spawn_work.get_executor(), + use_awaitable_t{}); + + bool done = false; + try + { + T t = co_await f(); + + done = true; + + (dispatch)(handler_work.get_executor(), + [handler = std::move(handler), t = std::move(t)]() mutable + { + handler(std::exception_ptr(), std::move(t)); + }); + } + catch (...) + { + if (done) + throw; + + (dispatch)(handler_work.get_executor(), + [handler = std::move(handler), e = std::current_exception()]() mutable + { + handler(e, T()); + }); + } +} + +template +awaitable co_spawn_entry_point( + awaitable*, Executor ex, F f, Handler handler) +{ + auto spawn_work = make_work_guard(ex); + auto handler_work = make_work_guard(handler, ex); + + (void) co_await (post)(spawn_work.get_executor(), + use_awaitable_t{}); + + std::exception_ptr e = nullptr; + try + { + co_await f(); + } + catch (...) + { + e = std::current_exception(); + } + + (dispatch)(handler_work.get_executor(), + [handler = std::move(handler), e]() mutable + { + handler(e); + }); +} + +template +class initiate_co_spawn +{ +public: + typedef Executor executor_type; + + template + explicit initiate_co_spawn(const OtherExecutor& ex) + : ex_(ex) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return ex_; + } + + template + void operator()(Handler&& handler, F&& f) const + { + typedef typename result_of::type awaitable_type; + + auto a = (co_spawn_entry_point)(static_cast(nullptr), + ex_, std::forward(f), std::forward(handler)); + awaitable_handler(std::move(a), ex_).launch(); + } + +private: + Executor ex_; +}; + +} // namespace detail + +template ::type>::type) CompletionToken> +inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, + typename detail::awaitable_signature::type>::type) +co_spawn(const Executor& ex, F&& f, CompletionToken&& token, + typename enable_if< + is_executor::value + >::type*) +{ + return async_initiate::type>>( + detail::initiate_co_spawn< + typename result_of::type::executor_type>(ex), + token, std::forward(f)); +} + +template ::type>::type) CompletionToken> +inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, + typename detail::awaitable_signature::type>::type) +co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token, + typename enable_if< + is_convertible::value + >::type*) +{ + return (co_spawn)(ctx.get_executor(), std::forward(f), + std::forward(token)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_CO_SPAWN_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/compose.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/compose.hpp new file mode 100644 index 00000000..0896e9c5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/compose.hpp @@ -0,0 +1,532 @@ +// +// impl/compose.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_COMPOSE_HPP +#define ASIO_IMPL_COMPOSE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/variadic_templates.hpp" +#include "asio/executor_work_guard.hpp" +#include "asio/is_executor.hpp" +#include "asio/system_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + struct composed_io_executors; + + template <> + struct composed_io_executors + { + composed_io_executors() ASIO_NOEXCEPT + : head_(system_executor()) + { + } + + typedef system_executor head_type; + system_executor head_; + }; + + inline composed_io_executors make_composed_io_executors() + { + return composed_io_executors(); + } + + template + struct composed_io_executors + { + explicit composed_io_executors(const Head& ex) ASIO_NOEXCEPT + : head_(ex) + { + } + + typedef Head head_type; + Head head_; + }; + + template + inline composed_io_executors + make_composed_io_executors(const Head& head) + { + return composed_io_executors(head); + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + struct composed_io_executors + { + explicit composed_io_executors(const Head& head, + const Tail&... tail) ASIO_NOEXCEPT + : head_(head), + tail_(tail...) + { + } + + void reset() + { + head_.reset(); + tail_.reset(); + } + + typedef Head head_type; + Head head_; + composed_io_executors tail_; + }; + + template + inline composed_io_executors + make_composed_io_executors(const Head& head, const Tail&... tail) + { + return composed_io_executors(head, tail...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF(n) \ + template \ + struct composed_io_executors \ + { \ + explicit composed_io_executors(const Head& head, \ + ASIO_VARIADIC_CONSTREF_PARAMS(n)) ASIO_NOEXCEPT \ + : head_(head), \ + tail_(ASIO_VARIADIC_BYVAL_ARGS(n)) \ + { \ + } \ + \ + void reset() \ + { \ + head_.reset(); \ + tail_.reset(); \ + } \ + \ + typedef Head head_type; \ + Head head_; \ + composed_io_executors tail_; \ + }; \ + \ + template \ + inline composed_io_executors \ + make_composed_io_executors(const Head& head, \ + ASIO_VARIADIC_CONSTREF_PARAMS(n)) \ + { \ + return composed_io_executors< \ + void(Head, ASIO_VARIADIC_TARGS(n))>( \ + head, ASIO_VARIADIC_BYVAL_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF) +#undef ASIO_PRIVATE_COMPOSED_IO_EXECUTORS_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + struct composed_work; + + template <> + struct composed_work + { + typedef composed_io_executors executors_type; + + composed_work(const executors_type&) ASIO_NOEXCEPT + : head_(system_executor()) + { + } + + void reset() + { + head_.reset(); + } + + typedef system_executor head_type; + executor_work_guard head_; + }; + + template + struct composed_work + { + typedef composed_io_executors executors_type; + + explicit composed_work(const executors_type& ex) ASIO_NOEXCEPT + : head_(ex.head_) + { + } + + void reset() + { + head_.reset(); + } + + typedef Head head_type; + executor_work_guard head_; + }; + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + struct composed_work + { + typedef composed_io_executors executors_type; + + explicit composed_work(const executors_type& ex) ASIO_NOEXCEPT + : head_(ex.head_), + tail_(ex.tail_) + { + } + + void reset() + { + head_.reset(); + tail_.reset(); + } + + typedef Head head_type; + executor_work_guard head_; + composed_work tail_; + }; + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_COMPOSED_WORK_DEF(n) \ + template \ + struct composed_work \ + { \ + typedef composed_io_executors executors_type; \ + \ + explicit composed_work(const executors_type& ex) ASIO_NOEXCEPT \ + : head_(ex.head_), \ + tail_(ex.tail_) \ + { \ + } \ + \ + void reset() \ + { \ + head_.reset(); \ + tail_.reset(); \ + } \ + \ + typedef Head head_type; \ + executor_work_guard head_; \ + composed_work tail_; \ + }; \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_COMPOSED_WORK_DEF) +#undef ASIO_PRIVATE_COMPOSED_WORK_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + template + class composed_op; + + template + class composed_op +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + template + class composed_op +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + { + public: + composed_op(ASIO_MOVE_ARG(Impl) impl, + ASIO_MOVE_ARG(Work) work, + ASIO_MOVE_ARG(Handler) handler) + : impl_(ASIO_MOVE_CAST(Impl)(impl)), + work_(ASIO_MOVE_CAST(Work)(work)), + handler_(ASIO_MOVE_CAST(Handler)(handler)), + invocations_(0) + { + } + +#if defined(ASIO_HAS_MOVE) + composed_op(composed_op&& other) + : impl_(ASIO_MOVE_CAST(Impl)(other.impl_)), + work_(ASIO_MOVE_CAST(Work)(other.work_)), + handler_(ASIO_MOVE_CAST(Handler)(other.handler_)), + invocations_(other.invocations_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + typedef typename associated_executor::type executor_type; + + executor_type get_executor() const ASIO_NOEXCEPT + { + return (get_associated_executor)(handler_, work_.head_.get_executor()); + } + + typedef typename associated_allocator >::type allocator_type; + + allocator_type get_allocator() const ASIO_NOEXCEPT + { + return (get_associated_allocator)(handler_, std::allocator()); + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(ASIO_MOVE_ARG(T)... t) + { + if (invocations_ < ~unsigned(0)) + ++invocations_; + impl_(*this, ASIO_MOVE_CAST(T)(t)...); + } + + void complete(Args... args) + { + this->work_.reset(); + this->handler_(ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + void operator()() + { + if (invocations_ < ~unsigned(0)) + ++invocations_; + impl_(*this); + } + + void complete() + { + this->work_.reset(); + this->handler_(); + } + +#define ASIO_PRIVATE_COMPOSED_OP_DEF(n) \ + template \ + void operator()(ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + if (invocations_ < ~unsigned(0)) \ + ++invocations_; \ + impl_(*this, ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + \ + template \ + void complete(ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + this->work_.reset(); \ + this->handler_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_COMPOSED_OP_DEF) +#undef ASIO_PRIVATE_COMPOSED_OP_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + //private: + Impl impl_; + Work work_; + Handler handler_; + unsigned invocations_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + composed_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + composed_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + composed_op* this_handler) + { + return this_handler->invocations_ > 1 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + composed_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + composed_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_composed_op + { + public: + typedef typename composed_io_executors::head_type executor_type; + + template + explicit initiate_composed_op(ASIO_MOVE_ARG(T) executors) + : executors_(ASIO_MOVE_CAST(T)(executors)) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return executors_.head_; + } + + template + void operator()(ASIO_MOVE_ARG(Handler) handler, + ASIO_MOVE_ARG(Impl) impl) const + { + composed_op::type, composed_work, + typename decay::type, Signature>( + ASIO_MOVE_CAST(Impl)(impl), + composed_work(executors_), + ASIO_MOVE_CAST(Handler)(handler))(); + } + + private: + composed_io_executors executors_; + }; + + template + inline initiate_composed_op make_initiate_composed_op( + ASIO_MOVE_ARG(composed_io_executors) executors) + { + return initiate_composed_op( + ASIO_MOVE_CAST(composed_io_executors)(executors)); + } + + template + inline typename IoObject::executor_type + get_composed_io_executor(IoObject& io_object) + { + return io_object.get_executor(); + } + + template + inline const Executor& get_composed_io_executor(const Executor& ex, + typename enable_if::value>::type* = 0) + { + return ex; + } +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) +async_compose(ASIO_MOVE_ARG(Implementation) implementation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, + ASIO_MOVE_ARG(IoObjectsOrExecutors)... io_objects_or_executors) +{ + return async_initiate( + detail::make_initiate_composed_op( + detail::make_composed_io_executors( + detail::get_composed_io_executor( + ASIO_MOVE_CAST(IoObjectsOrExecutors)( + io_objects_or_executors))...)), + token, ASIO_MOVE_CAST(Implementation)(implementation)); +} + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) +async_compose(ASIO_MOVE_ARG(Implementation) implementation, + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token) +{ + return async_initiate( + detail::make_initiate_composed_op( + detail::make_composed_io_executors()), + token, ASIO_MOVE_CAST(Implementation)(implementation)); +} + +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR(n) \ + ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_##n + +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_1 \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T1)(x1)) +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_2 \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T1)(x1)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T2)(x2)) +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_3 \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T1)(x1)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T2)(x2)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T3)(x3)) +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_4 \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T1)(x1)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T2)(x2)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T3)(x3)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T4)(x4)) +# define ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_5 \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T1)(x1)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T2)(x2)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T3)(x3)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T4)(x4)), \ + detail::get_composed_io_executor(ASIO_MOVE_CAST(T5)(x5)) + +#define ASIO_PRIVATE_ASYNC_COMPOSE_DEF(n) \ + template \ + ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, Signature) \ + async_compose(ASIO_MOVE_ARG(Implementation) implementation, \ + ASIO_NONDEDUCED_MOVE_ARG(CompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + return async_initiate( \ + detail::make_initiate_composed_op( \ + detail::make_composed_io_executors( \ + ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR(n))), \ + token, ASIO_MOVE_CAST(Implementation)(implementation)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_ASYNC_COMPOSE_DEF) +#undef ASIO_PRIVATE_ASYNC_COMPOSE_DEF + +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_1 +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_2 +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_3 +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_4 +#undef ASIO_PRIVATE_GET_COMPOSED_IO_EXECUTOR_5 + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_COMPOSE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/connect.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/connect.hpp new file mode 100644 index 00000000..34c5e798 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/connect.hpp @@ -0,0 +1,872 @@ +// +// impl/connect.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_CONNECT_HPP +#define ASIO_IMPL_CONNECT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/post.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + struct default_connect_condition + { + template + bool operator()(const asio::error_code&, const Endpoint&) + { + return true; + } + }; + + template + inline typename Protocol::endpoint deref_connect_result( + Iterator iter, asio::error_code& ec) + { + return ec ? typename Protocol::endpoint() : *iter; + } + + template + struct legacy_connect_condition_helper : T + { + typedef char (*fallback_func_type)(...); + operator fallback_func_type() const; + }; + + template + struct legacy_connect_condition_helper + { + R operator()(Arg1, Arg2) const; + char operator()(...) const; + }; + + template + struct is_legacy_connect_condition + { + static char asio_connect_condition_check(char); + static char (&asio_connect_condition_check(Iterator))[2]; + + static const bool value = + sizeof(asio_connect_condition_check( + (*static_cast*>(0))( + *static_cast(0), + *static_cast(0)))) != 1; + }; + + template + inline Iterator call_connect_condition(ConnectCondition& connect_condition, + const asio::error_code& ec, Iterator next, Iterator end, + typename enable_if::value>::type* = 0) + { + if (next != end) + return connect_condition(ec, next); + return end; + } + + template + inline Iterator call_connect_condition(ConnectCondition& connect_condition, + const asio::error_code& ec, Iterator next, Iterator end, + typename enable_if::value>::type* = 0) + { + for (;next != end; ++next) + if (connect_condition(ec, *next)) + return next; + return end; + } +} + +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, + typename enable_if::value>::type*) +{ + asio::error_code ec; + typename Protocol::endpoint result = connect(s, endpoints, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, asio::error_code& ec, + typename enable_if::value>::type*) +{ + return detail::deref_connect_result( + connect(s, endpoints.begin(), endpoints.end(), + detail::default_connect_condition(), ec), ec); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +Iterator connect(basic_socket& s, Iterator begin, + typename enable_if::value>::type*) +{ + asio::error_code ec; + Iterator result = connect(s, begin, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +inline Iterator connect(basic_socket& s, + Iterator begin, asio::error_code& ec, + typename enable_if::value>::type*) +{ + return connect(s, begin, Iterator(), detail::default_connect_condition(), ec); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +Iterator connect(basic_socket& s, + Iterator begin, Iterator end) +{ + asio::error_code ec; + Iterator result = connect(s, begin, end, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +inline Iterator connect(basic_socket& s, + Iterator begin, Iterator end, asio::error_code& ec) +{ + return connect(s, begin, end, detail::default_connect_condition(), ec); +} + +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + typename enable_if::value>::type*) +{ + asio::error_code ec; + typename Protocol::endpoint result = connect( + s, endpoints, connect_condition, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +typename Protocol::endpoint connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + asio::error_code& ec, + typename enable_if::value>::type*) +{ + return detail::deref_connect_result( + connect(s, endpoints.begin(), endpoints.end(), + connect_condition, ec), ec); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +Iterator connect(basic_socket& s, + Iterator begin, ConnectCondition connect_condition, + typename enable_if::value>::type*) +{ + asio::error_code ec; + Iterator result = connect(s, begin, connect_condition, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +inline Iterator connect(basic_socket& s, + Iterator begin, ConnectCondition connect_condition, + asio::error_code& ec, + typename enable_if::value>::type*) +{ + return connect(s, begin, Iterator(), connect_condition, ec); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +Iterator connect(basic_socket& s, Iterator begin, + Iterator end, ConnectCondition connect_condition) +{ + asio::error_code ec; + Iterator result = connect(s, begin, end, connect_condition, ec); + asio::detail::throw_error(ec, "connect"); + return result; +} + +template +Iterator connect(basic_socket& s, Iterator begin, + Iterator end, ConnectCondition connect_condition, + asio::error_code& ec) +{ + ec = asio::error_code(); + + for (Iterator iter = begin; iter != end; ++iter) + { + iter = (detail::call_connect_condition(connect_condition, ec, iter, end)); + if (iter != end) + { + s.close(ec); + s.connect(*iter, ec); + if (!ec) + return iter; + } + else + break; + } + + if (!ec) + ec = asio::error::not_found; + + return end; +} + +namespace detail +{ + // Enable the empty base class optimisation for the connect condition. + template + class base_from_connect_condition + { + protected: + explicit base_from_connect_condition( + const ConnectCondition& connect_condition) + : connect_condition_(connect_condition) + { + } + + template + void check_condition(const asio::error_code& ec, + Iterator& iter, Iterator& end) + { + iter = detail::call_connect_condition(connect_condition_, ec, iter, end); + } + + private: + ConnectCondition connect_condition_; + }; + + // The default_connect_condition implementation is essentially a no-op. This + // template specialisation lets us eliminate all costs associated with it. + template <> + class base_from_connect_condition + { + protected: + explicit base_from_connect_condition(const default_connect_condition&) + { + } + + template + void check_condition(const asio::error_code&, Iterator&, Iterator&) + { + } + }; + + template + class range_connect_op : base_from_connect_condition + { + public: + range_connect_op(basic_socket& sock, + const EndpointSequence& endpoints, + const ConnectCondition& connect_condition, + RangeConnectHandler& handler) + : base_from_connect_condition(connect_condition), + socket_(sock), + endpoints_(endpoints), + index_(0), + start_(0), + handler_(ASIO_MOVE_CAST(RangeConnectHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + range_connect_op(const range_connect_op& other) + : base_from_connect_condition(other), + socket_(other.socket_), + endpoints_(other.endpoints_), + index_(other.index_), + start_(other.start_), + handler_(other.handler_) + { + } + + range_connect_op(range_connect_op&& other) + : base_from_connect_condition(other), + socket_(other.socket_), + endpoints_(other.endpoints_), + index_(other.index_), + start_(other.start_), + handler_(ASIO_MOVE_CAST(RangeConnectHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(asio::error_code ec, int start = 0) + { + this->process(ec, start, + const_cast(endpoints_).begin(), + const_cast(endpoints_).end()); + } + + //private: + template + void process(asio::error_code ec, + int start, Iterator begin, Iterator end) + { + Iterator iter = begin; + std::advance(iter, index_); + + switch (start_ = start) + { + case 1: + for (;;) + { + this->check_condition(ec, iter, end); + index_ = std::distance(begin, iter); + + if (iter != end) + { + socket_.close(ec); + socket_.async_connect(*iter, + ASIO_MOVE_CAST(range_connect_op)(*this)); + return; + } + + if (start) + { + ec = asio::error::not_found; + asio::post(socket_.get_executor(), + detail::bind_handler( + ASIO_MOVE_CAST(range_connect_op)(*this), ec)); + return; + } + + /* fall-through */ default: + + if (iter == end) + break; + + if (!socket_.is_open()) + { + ec = asio::error::operation_aborted; + break; + } + + if (!ec) + break; + + ++iter; + ++index_; + } + + handler_(static_cast(ec), + static_cast( + ec || iter == end ? typename Protocol::endpoint() : *iter)); + } + } + + basic_socket& socket_; + EndpointSequence endpoints_; + std::size_t index_; + int start_; + RangeConnectHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + range_connect_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + range_connect_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + range_connect_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + range_connect_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + range_connect_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_range_connect + { + public: + typedef Executor executor_type; + + explicit initiate_async_range_connect(basic_socket& s) + : socket_(s) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return socket_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(RangeConnectHandler) handler, + const EndpointSequence& endpoints, + const ConnectCondition& connect_condition) const + { + // If you get an error on the following line it means that your + // handler does not meet the documented type requirements for an + // RangeConnectHandler. + ASIO_RANGE_CONNECT_HANDLER_CHECK(RangeConnectHandler, + handler, typename Protocol::endpoint) type_check; + + non_const_lvalue handler2(handler); + range_connect_op::type>(socket_, endpoints, + connect_condition, handler2.value)(asio::error_code(), 1); + } + + private: + basic_socket& socket_; + }; + + template + class iterator_connect_op : base_from_connect_condition + { + public: + iterator_connect_op(basic_socket& sock, + const Iterator& begin, const Iterator& end, + const ConnectCondition& connect_condition, + IteratorConnectHandler& handler) + : base_from_connect_condition(connect_condition), + socket_(sock), + iter_(begin), + end_(end), + start_(0), + handler_(ASIO_MOVE_CAST(IteratorConnectHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + iterator_connect_op(const iterator_connect_op& other) + : base_from_connect_condition(other), + socket_(other.socket_), + iter_(other.iter_), + end_(other.end_), + start_(other.start_), + handler_(other.handler_) + { + } + + iterator_connect_op(iterator_connect_op&& other) + : base_from_connect_condition(other), + socket_(other.socket_), + iter_(other.iter_), + end_(other.end_), + start_(other.start_), + handler_(ASIO_MOVE_CAST(IteratorConnectHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(asio::error_code ec, int start = 0) + { + switch (start_ = start) + { + case 1: + for (;;) + { + this->check_condition(ec, iter_, end_); + + if (iter_ != end_) + { + socket_.close(ec); + socket_.async_connect(*iter_, + ASIO_MOVE_CAST(iterator_connect_op)(*this)); + return; + } + + if (start) + { + ec = asio::error::not_found; + asio::post(socket_.get_executor(), + detail::bind_handler( + ASIO_MOVE_CAST(iterator_connect_op)(*this), ec)); + return; + } + + /* fall-through */ default: + + if (iter_ == end_) + break; + + if (!socket_.is_open()) + { + ec = asio::error::operation_aborted; + break; + } + + if (!ec) + break; + + ++iter_; + } + + handler_(static_cast(ec), + static_cast(iter_)); + } + } + + //private: + basic_socket& socket_; + Iterator iter_; + Iterator end_; + int start_; + IteratorConnectHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + iterator_connect_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + iterator_connect_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + iterator_connect_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + iterator_connect_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + iterator_connect_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_iterator_connect + { + public: + typedef Executor executor_type; + + explicit initiate_async_iterator_connect( + basic_socket& s) + : socket_(s) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return socket_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(IteratorConnectHandler) handler, + Iterator begin, Iterator end, + const ConnectCondition& connect_condition) const + { + // If you get an error on the following line it means that your + // handler does not meet the documented type requirements for an + // IteratorConnectHandler. + ASIO_ITERATOR_CONNECT_HANDLER_CHECK( + IteratorConnectHandler, handler, Iterator) type_check; + + non_const_lvalue handler2(handler); + iterator_connect_op::type>(socket_, begin, end, + connect_condition, handler2.value)(asio::error_code(), 1); + } + + private: + basic_socket& socket_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::range_connect_op, Allocator> +{ + typedef typename associated_allocator< + RangeConnectHandler, Allocator>::type type; + + static type get( + const detail::range_connect_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::range_connect_op, Executor1> +{ + typedef typename associated_executor< + RangeConnectHandler, Executor1>::type type; + + static type get( + const detail::range_connect_op& h, + const Executor1& ex = Executor1()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +template +struct associated_allocator< + detail::iterator_connect_op, + Allocator> +{ + typedef typename associated_allocator< + IteratorConnectHandler, Allocator>::type type; + + static type get( + const detail::iterator_connect_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::iterator_connect_op, + Executor1> +{ + typedef typename associated_executor< + IteratorConnectHandler, Executor1>::type type; + + static type get( + const detail::iterator_connect_op& h, + const Executor1& ex = Executor1()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(RangeConnectHandler, + void (asio::error_code, typename Protocol::endpoint)) +async_connect(basic_socket& s, + const EndpointSequence& endpoints, + ASIO_MOVE_ARG(RangeConnectHandler) handler, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_async_range_connect(s), + handler, endpoints, detail::default_connect_condition()); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + ASIO_MOVE_ARG(IteratorConnectHandler) handler, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_async_iterator_connect(s), + handler, begin, Iterator(), detail::default_connect_condition()); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, Iterator end, + ASIO_MOVE_ARG(IteratorConnectHandler) handler) +{ + return async_initiate( + detail::initiate_async_iterator_connect(s), + handler, begin, end, detail::default_connect_condition()); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(RangeConnectHandler, + void (asio::error_code, typename Protocol::endpoint)) +async_connect(basic_socket& s, + const EndpointSequence& endpoints, ConnectCondition connect_condition, + ASIO_MOVE_ARG(RangeConnectHandler) handler, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_async_range_connect(s), + handler, endpoints, connect_condition); +} + +#if !defined(ASIO_NO_DEPRECATED) +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + ConnectCondition connect_condition, + ASIO_MOVE_ARG(IteratorConnectHandler) handler, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_async_iterator_connect(s), + handler, begin, Iterator(), connect_condition); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(IteratorConnectHandler, + void (asio::error_code, Iterator)) +async_connect(basic_socket& s, Iterator begin, + Iterator end, ConnectCondition connect_condition, + ASIO_MOVE_ARG(IteratorConnectHandler) handler) +{ + return async_initiate( + detail::initiate_async_iterator_connect(s), + handler, begin, end, connect_condition); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_CONNECT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/defer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/defer.hpp new file mode 100644 index 00000000..5676aa72 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/defer.hpp @@ -0,0 +1,113 @@ +// +// impl/defer.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_DEFER_HPP +#define ASIO_IMPL_DEFER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/work_dispatcher.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class initiate_defer +{ +public: + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_executor::type ex( + (get_associated_executor)(handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex.defer(ASIO_MOVE_CAST(CompletionHandler)(handler), alloc); + } +}; + +template +class initiate_defer_with_executor +{ +public: + typedef Executor executor_type; + + explicit initiate_defer_with_executor(const Executor& ex) + : ex_(ex) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return ex_; + } + + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex_.defer(detail::work_dispatcher( + ASIO_MOVE_CAST(CompletionHandler)(handler)), alloc); + } + +private: + Executor ex_; +}; + +} // namespace detail + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + ASIO_MOVE_ARG(CompletionToken) token) +{ + return async_initiate( + detail::initiate_defer(), token); +} + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_defer_with_executor(ex), token); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) defer( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return (defer)(ctx.get_executor(), + ASIO_MOVE_CAST(CompletionToken)(token)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_DEFER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/detached.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/detached.hpp new file mode 100644 index 00000000..8817ba95 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/detached.hpp @@ -0,0 +1,130 @@ +// +// impl/detached.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_DETACHED_HPP +#define ASIO_IMPL_DETACHED_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/variadic_templates.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + + // Class to adapt a detached_t as a completion handler. + class detached_handler + { + public: + typedef void result_type; + + detached_handler(detached_t) + { + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(Args...) + { + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + void operator()() + { + } + +#define ASIO_PRIVATE_DETACHED_DEF(n) \ + template \ + void operator()(ASIO_VARIADIC_TARGS(n)) \ + { \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_DETACHED_DEF) +#undef ASIO_PRIVATE_DETACHED_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + }; + +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct async_result +{ + typedef asio::detail::detached_handler completion_handler_type; + + typedef void return_type; + + explicit async_result(completion_handler_type&) + { + } + + void get() + { + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken), + ASIO_MOVE_ARG(Args)... args) + { + ASIO_MOVE_CAST(Initiation)(initiation)( + detail::detached_handler(detached_t()), + ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken)) + { + ASIO_MOVE_CAST(Initiation)(initiation)( + detail::detached_handler(detached_t())); + } + +#define ASIO_PRIVATE_INITIATE_DEF(n) \ + template \ + static return_type initiate( \ + ASIO_MOVE_ARG(Initiation) initiation, \ + ASIO_MOVE_ARG(RawCompletionToken), \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + ASIO_MOVE_CAST(Initiation)(initiation)( \ + detail::detached_handler(detached_t()), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INITIATE_DEF) +#undef ASIO_PRIVATE_INITIATE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_DETACHED_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/dispatch.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/dispatch.hpp new file mode 100644 index 00000000..2242ad71 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/dispatch.hpp @@ -0,0 +1,113 @@ +// +// impl/dispatch.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_DISPATCH_HPP +#define ASIO_IMPL_DISPATCH_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/work_dispatcher.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class initiate_dispatch +{ +public: + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_executor::type ex( + (get_associated_executor)(handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex.dispatch(ASIO_MOVE_CAST(CompletionHandler)(handler), alloc); + } +}; + +template +class initiate_dispatch_with_executor +{ +public: + typedef Executor executor_type; + + explicit initiate_dispatch_with_executor(const Executor& ex) + : ex_(ex) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return ex_; + } + + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex_.dispatch(detail::work_dispatcher( + ASIO_MOVE_CAST(CompletionHandler)(handler)), alloc); + } + +private: + Executor ex_; +}; + +} // namespace detail + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + ASIO_MOVE_ARG(CompletionToken) token) +{ + return async_initiate( + detail::initiate_dispatch(), token); +} + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_dispatch_with_executor(ex), token); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) dispatch( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return (dispatch)(ctx.get_executor(), + ASIO_MOVE_CAST(CompletionToken)(token)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_DISPATCH_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/execution_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/execution_context.hpp new file mode 100644 index 00000000..d31e41da --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/execution_context.hpp @@ -0,0 +1,109 @@ +// +// impl/execution_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_EXECUTION_CONTEXT_HPP +#define ASIO_IMPL_EXECUTION_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/scoped_ptr.hpp" +#include "asio/detail/service_registry.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(GENERATING_DOCUMENTATION) + +template +inline Service& use_service(execution_context& e) +{ + // Check that Service meets the necessary type requirements. + (void)static_cast(static_cast(0)); + + return e.service_registry_->template use_service(); +} + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +Service& make_service(execution_context& e, ASIO_MOVE_ARG(Args)... args) +{ + detail::scoped_ptr svc( + new Service(e, ASIO_MOVE_CAST(Args)(args)...)); + e.service_registry_->template add_service(svc.get()); + Service& result = *svc; + svc.release(); + return result; +} + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +Service& make_service(execution_context& e) +{ + detail::scoped_ptr svc(new Service(e)); + e.service_registry_->template add_service(svc.get()); + Service& result = *svc; + svc.release(); + return result; +} + +#define ASIO_PRIVATE_MAKE_SERVICE_DEF(n) \ + template \ + Service& make_service(execution_context& e, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + detail::scoped_ptr svc( \ + new Service(e, ASIO_VARIADIC_MOVE_ARGS(n))); \ + e.service_registry_->template add_service(svc.get()); \ + Service& result = *svc; \ + svc.release(); \ + return result; \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_MAKE_SERVICE_DEF) +#undef ASIO_PRIVATE_MAKE_SERVICE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +inline void add_service(execution_context& e, Service* svc) +{ + // Check that Service meets the necessary type requirements. + (void)static_cast(static_cast(0)); + + e.service_registry_->template add_service(svc); +} + +template +inline bool has_service(execution_context& e) +{ + // Check that Service meets the necessary type requirements. + (void)static_cast(static_cast(0)); + + return e.service_registry_->template has_service(); +} + +#endif // !defined(GENERATING_DOCUMENTATION) + +inline execution_context& execution_context::service::context() +{ + return owner_; +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_EXECUTION_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/executor.hpp new file mode 100644 index 00000000..43ba5f6d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/executor.hpp @@ -0,0 +1,387 @@ +// +// impl/executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_EXECUTOR_HPP +#define ASIO_IMPL_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/executor_function.hpp" +#include "asio/detail/global.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/executor.hpp" +#include "asio/system_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_HAS_MOVE) + +// Lightweight, move-only function object wrapper. +class executor::function +{ +public: + template + explicit function(F f, const Alloc& a) + { + // Allocate and construct an operation to wrap the function. + typedef detail::executor_function func_type; + typename func_type::ptr p = { + detail::addressof(a), func_type::ptr::allocate(a), 0 }; + func_ = new (p.v) func_type(ASIO_MOVE_CAST(F)(f), a); + p.v = 0; + } + + function(function&& other) ASIO_NOEXCEPT + : func_(other.func_) + { + other.func_ = 0; + } + + ~function() + { + if (func_) + func_->destroy(); + } + + void operator()() + { + if (func_) + { + detail::executor_function_base* func = func_; + func_ = 0; + func->complete(); + } + } + +private: + detail::executor_function_base* func_; +}; + +#else // defined(ASIO_HAS_MOVE) + +// Not so lightweight, copyable function object wrapper. +class executor::function +{ +public: + template + explicit function(const F& f, const Alloc&) + : impl_(new impl(f)) + { + } + + void operator()() + { + impl_->invoke_(impl_.get()); + } + +private: + // Base class for polymorphic function implementations. + struct impl_base + { + void (*invoke_)(impl_base*); + }; + + // Polymorphic function implementation. + template + struct impl : impl_base + { + impl(const F& f) + : function_(f) + { + invoke_ = &function::invoke; + } + + F function_; + }; + + // Helper to invoke a function. + template + static void invoke(impl_base* i) + { + static_cast*>(i)->function_(); + } + + detail::shared_ptr impl_; +}; + +#endif // defined(ASIO_HAS_MOVE) + +// Default polymorphic allocator implementation. +template +class executor::impl + : public executor::impl_base +{ +public: + typedef ASIO_REBIND_ALLOC(Allocator, impl) allocator_type; + + static impl_base* create(const Executor& e, Allocator a = Allocator()) + { + raw_mem mem(a); + impl* p = new (mem.ptr_) impl(e, a); + mem.ptr_ = 0; + return p; + } + + impl(const Executor& e, const Allocator& a) ASIO_NOEXCEPT + : impl_base(false), + ref_count_(1), + executor_(e), + allocator_(a) + { + } + + impl_base* clone() const ASIO_NOEXCEPT + { + ++ref_count_; + return const_cast(static_cast(this)); + } + + void destroy() ASIO_NOEXCEPT + { + if (--ref_count_ == 0) + { + allocator_type alloc(allocator_); + impl* p = this; + p->~impl(); + alloc.deallocate(p, 1); + } + } + + void on_work_started() ASIO_NOEXCEPT + { + executor_.on_work_started(); + } + + void on_work_finished() ASIO_NOEXCEPT + { + executor_.on_work_finished(); + } + + execution_context& context() ASIO_NOEXCEPT + { + return executor_.context(); + } + + void dispatch(ASIO_MOVE_ARG(function) f) + { + executor_.dispatch(ASIO_MOVE_CAST(function)(f), allocator_); + } + + void post(ASIO_MOVE_ARG(function) f) + { + executor_.post(ASIO_MOVE_CAST(function)(f), allocator_); + } + + void defer(ASIO_MOVE_ARG(function) f) + { + executor_.defer(ASIO_MOVE_CAST(function)(f), allocator_); + } + + type_id_result_type target_type() const ASIO_NOEXCEPT + { + return type_id(); + } + + void* target() ASIO_NOEXCEPT + { + return &executor_; + } + + const void* target() const ASIO_NOEXCEPT + { + return &executor_; + } + + bool equals(const impl_base* e) const ASIO_NOEXCEPT + { + if (this == e) + return true; + if (target_type() != e->target_type()) + return false; + return executor_ == *static_cast(e->target()); + } + +private: + mutable detail::atomic_count ref_count_; + Executor executor_; + Allocator allocator_; + + struct raw_mem + { + allocator_type allocator_; + impl* ptr_; + + explicit raw_mem(const Allocator& a) + : allocator_(a), + ptr_(allocator_.allocate(1)) + { + } + + ~raw_mem() + { + if (ptr_) + allocator_.deallocate(ptr_, 1); + } + + private: + // Disallow copying and assignment. + raw_mem(const raw_mem&); + raw_mem operator=(const raw_mem&); + }; +}; + +// Polymorphic allocator specialisation for system_executor. +template +class executor::impl + : public executor::impl_base +{ +public: + static impl_base* create(const system_executor&, + const Allocator& = Allocator()) + { + return &detail::global > >(); + } + + impl() + : impl_base(true) + { + } + + impl_base* clone() const ASIO_NOEXCEPT + { + return const_cast(static_cast(this)); + } + + void destroy() ASIO_NOEXCEPT + { + } + + void on_work_started() ASIO_NOEXCEPT + { + executor_.on_work_started(); + } + + void on_work_finished() ASIO_NOEXCEPT + { + executor_.on_work_finished(); + } + + execution_context& context() ASIO_NOEXCEPT + { + return executor_.context(); + } + + void dispatch(ASIO_MOVE_ARG(function) f) + { + executor_.dispatch(ASIO_MOVE_CAST(function)(f), allocator_); + } + + void post(ASIO_MOVE_ARG(function) f) + { + executor_.post(ASIO_MOVE_CAST(function)(f), allocator_); + } + + void defer(ASIO_MOVE_ARG(function) f) + { + executor_.defer(ASIO_MOVE_CAST(function)(f), allocator_); + } + + type_id_result_type target_type() const ASIO_NOEXCEPT + { + return type_id(); + } + + void* target() ASIO_NOEXCEPT + { + return &executor_; + } + + const void* target() const ASIO_NOEXCEPT + { + return &executor_; + } + + bool equals(const impl_base* e) const ASIO_NOEXCEPT + { + return this == e; + } + +private: + system_executor executor_; + Allocator allocator_; +}; + +template +executor::executor(Executor e) + : impl_(impl >::create(e)) +{ +} + +template +executor::executor(allocator_arg_t, const Allocator& a, Executor e) + : impl_(impl::create(e, a)) +{ +} + +template +void executor::dispatch(ASIO_MOVE_ARG(Function) f, + const Allocator& a) const +{ + impl_base* i = get_impl(); + if (i->fast_dispatch_) + system_executor().dispatch(ASIO_MOVE_CAST(Function)(f), a); + else + i->dispatch(function(ASIO_MOVE_CAST(Function)(f), a)); +} + +template +void executor::post(ASIO_MOVE_ARG(Function) f, + const Allocator& a) const +{ + get_impl()->post(function(ASIO_MOVE_CAST(Function)(f), a)); +} + +template +void executor::defer(ASIO_MOVE_ARG(Function) f, + const Allocator& a) const +{ + get_impl()->defer(function(ASIO_MOVE_CAST(Function)(f), a)); +} + +template +Executor* executor::target() ASIO_NOEXCEPT +{ + return impl_ && impl_->target_type() == type_id() + ? static_cast(impl_->target()) : 0; +} + +template +const Executor* executor::target() const ASIO_NOEXCEPT +{ + return impl_ && impl_->target_type() == type_id() + ? static_cast(impl_->target()) : 0; +} + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/io_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/io_context.hpp new file mode 100644 index 00000000..2db6f15a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/io_context.hpp @@ -0,0 +1,353 @@ +// +// impl/io_context.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_IO_CONTEXT_HPP +#define ASIO_IMPL_IO_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/completion_handler.hpp" +#include "asio/detail/executor_op.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/detail/service_registry.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +#if !defined(GENERATING_DOCUMENTATION) + +namespace asio { + +template +inline Service& use_service(io_context& ioc) +{ + // Check that Service meets the necessary type requirements. + (void)static_cast(static_cast(0)); + (void)static_cast(&Service::id); + + return ioc.service_registry_->template use_service(ioc); +} + +template <> +inline detail::io_context_impl& use_service( + io_context& ioc) +{ + return ioc.impl_; +} + +} // namespace asio + +#endif // !defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HAS_IOCP) +# include "asio/detail/win_iocp_io_context.hpp" +#else +# include "asio/detail/scheduler.hpp" +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { + +inline io_context::executor_type +io_context::get_executor() ASIO_NOEXCEPT +{ + return executor_type(*this); +} + +#if defined(ASIO_HAS_CHRONO) + +template +std::size_t io_context::run_for( + const chrono::duration& rel_time) +{ + return this->run_until(chrono::steady_clock::now() + rel_time); +} + +template +std::size_t io_context::run_until( + const chrono::time_point& abs_time) +{ + std::size_t n = 0; + while (this->run_one_until(abs_time)) + if (n != (std::numeric_limits::max)()) + ++n; + return n; +} + +template +std::size_t io_context::run_one_for( + const chrono::duration& rel_time) +{ + return this->run_one_until(chrono::steady_clock::now() + rel_time); +} + +template +std::size_t io_context::run_one_until( + const chrono::time_point& abs_time) +{ + typename Clock::time_point now = Clock::now(); + while (now < abs_time) + { + typename Clock::duration rel_time = abs_time - now; + if (rel_time > chrono::seconds(1)) + rel_time = chrono::seconds(1); + + asio::error_code ec; + std::size_t s = impl_.wait_one( + static_cast(chrono::duration_cast< + chrono::microseconds>(rel_time).count()), ec); + asio::detail::throw_error(ec); + + if (s || impl_.stopped()) + return s; + + now = Clock::now(); + } + + return 0; +} + +#endif // defined(ASIO_HAS_CHRONO) + +#if !defined(ASIO_NO_DEPRECATED) + +inline void io_context::reset() +{ + restart(); +} + +struct io_context::initiate_dispatch +{ + template + void operator()(ASIO_MOVE_ARG(LegacyCompletionHandler) handler, + io_context* self) const + { + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a LegacyCompletionHandler. + ASIO_LEGACY_COMPLETION_HANDLER_CHECK( + LegacyCompletionHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + if (self->impl_.can_dispatch()) + { + detail::fenced_block b(detail::fenced_block::full); + asio_handler_invoke_helpers::invoke( + handler2.value, handler2.value); + } + else + { + // Allocate and construct an operation to wrap the handler. + typedef detail::completion_handler< + typename decay::type> op; + typename op::ptr p = { detail::addressof(handler2.value), + op::ptr::allocate(handler2.value), 0 }; + p.p = new (p.v) op(handler2.value); + + ASIO_HANDLER_CREATION((*self, *p.p, + "io_context", self, 0, "dispatch")); + + self->impl_.do_dispatch(p.p); + p.v = p.p = 0; + } + } +}; + +template +ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) +io_context::dispatch(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) +{ + return async_initiate( + initiate_dispatch(), handler, this); +} + +struct io_context::initiate_post +{ + template + void operator()(ASIO_MOVE_ARG(LegacyCompletionHandler) handler, + io_context* self) const + { + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a LegacyCompletionHandler. + ASIO_LEGACY_COMPLETION_HANDLER_CHECK( + LegacyCompletionHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + + bool is_continuation = + asio_handler_cont_helpers::is_continuation(handler2.value); + + // Allocate and construct an operation to wrap the handler. + typedef detail::completion_handler< + typename decay::type> op; + typename op::ptr p = { detail::addressof(handler2.value), + op::ptr::allocate(handler2.value), 0 }; + p.p = new (p.v) op(handler2.value); + + ASIO_HANDLER_CREATION((*self, *p.p, + "io_context", self, 0, "post")); + + self->impl_.post_immediate_completion(p.p, is_continuation); + p.v = p.p = 0; + } +}; + +template +ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) +io_context::post(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) +{ + return async_initiate( + initiate_post(), handler, this); +} + +template +#if defined(GENERATING_DOCUMENTATION) +unspecified +#else +inline detail::wrapped_handler +#endif +io_context::wrap(Handler handler) +{ + return detail::wrapped_handler(*this, handler); +} + +#endif // !defined(ASIO_NO_DEPRECATED) + +inline io_context& +io_context::executor_type::context() const ASIO_NOEXCEPT +{ + return io_context_; +} + +inline void +io_context::executor_type::on_work_started() const ASIO_NOEXCEPT +{ + io_context_.impl_.work_started(); +} + +inline void +io_context::executor_type::on_work_finished() const ASIO_NOEXCEPT +{ + io_context_.impl_.work_finished(); +} + +template +void io_context::executor_type::dispatch( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Invoke immediately if we are already inside the thread pool. + if (io_context_.impl_.can_dispatch()) + { + // Make a local, non-const copy of the function. + function_type tmp(ASIO_MOVE_CAST(Function)(f)); + + detail::fenced_block b(detail::fenced_block::full); + asio_handler_invoke_helpers::invoke(tmp, tmp); + return; + } + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((this->context(), *p.p, + "io_context", &this->context(), 0, "dispatch")); + + io_context_.impl_.post_immediate_completion(p.p, false); + p.v = p.p = 0; +} + +template +void io_context::executor_type::post( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((this->context(), *p.p, + "io_context", &this->context(), 0, "post")); + + io_context_.impl_.post_immediate_completion(p.p, false); + p.v = p.p = 0; +} + +template +void io_context::executor_type::defer( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((this->context(), *p.p, + "io_context", &this->context(), 0, "defer")); + + io_context_.impl_.post_immediate_completion(p.p, true); + p.v = p.p = 0; +} + +inline bool +io_context::executor_type::running_in_this_thread() const ASIO_NOEXCEPT +{ + return io_context_.impl_.can_dispatch(); +} + +#if !defined(ASIO_NO_DEPRECATED) +inline io_context::work::work(asio::io_context& io_context) + : io_context_impl_(io_context.impl_) +{ + io_context_impl_.work_started(); +} + +inline io_context::work::work(const work& other) + : io_context_impl_(other.io_context_impl_) +{ + io_context_impl_.work_started(); +} + +inline io_context::work::~work() +{ + io_context_impl_.work_finished(); +} + +inline asio::io_context& io_context::work::get_io_context() +{ + return static_cast(io_context_impl_.context()); +} +#endif // !defined(ASIO_NO_DEPRECATED) + +inline asio::io_context& io_context::service::get_io_context() +{ + return static_cast(context()); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_IO_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/post.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/post.hpp new file mode 100644 index 00000000..1e7d589a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/post.hpp @@ -0,0 +1,113 @@ +// +// impl/post.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_POST_HPP +#define ASIO_IMPL_POST_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/detail/work_dispatcher.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +class initiate_post +{ +public: + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_executor::type ex( + (get_associated_executor)(handler)); + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex.post(ASIO_MOVE_CAST(CompletionHandler)(handler), alloc); + } +}; + +template +class initiate_post_with_executor +{ +public: + typedef Executor executor_type; + + explicit initiate_post_with_executor(const Executor& ex) + : ex_(ex) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return ex_; + } + + template + void operator()(ASIO_MOVE_ARG(CompletionHandler) handler) const + { + typedef typename decay::type DecayedHandler; + + typename associated_allocator::type alloc( + (get_associated_allocator)(handler)); + + ex_.post(detail::work_dispatcher( + ASIO_MOVE_CAST(CompletionHandler)(handler)), alloc); + } + +private: + Executor ex_; +}; + +} // namespace detail + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + ASIO_MOVE_ARG(CompletionToken) token) +{ + return async_initiate( + detail::initiate_post(), token); +} + +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + const Executor& ex, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return async_initiate( + detail::initiate_post_with_executor(ex), token); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + ExecutionContext& ctx, ASIO_MOVE_ARG(CompletionToken) token, + typename enable_if::value>::type*) +{ + return (post)(ctx.get_executor(), + ASIO_MOVE_CAST(CompletionToken)(token)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_POST_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read.hpp new file mode 100644 index 00000000..d349b39b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read.hpp @@ -0,0 +1,1143 @@ +// +// impl/read.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_READ_HPP +#define ASIO_IMPL_READ_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/base_from_completion_cond.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/consuming_buffers.hpp" +#include "asio/detail/dependent_type.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + std::size_t read_buffer_sequence(SyncReadStream& s, + const MutableBufferSequence& buffers, const MutableBufferIterator&, + CompletionCondition completion_condition, asio::error_code& ec) + { + ec = asio::error_code(); + asio::detail::consuming_buffers tmp(buffers); + while (!tmp.empty()) + { + if (std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, tmp.total_consumed()))) + tmp.consume(s.read_some(tmp.prepare(max_size), ec)); + else + break; + } + return tmp.total_consumed();; + } +} // namespace detail + +template +std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + return detail::read_buffer_sequence(s, buffers, + asio::buffer_sequence_begin(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, buffers, transfer_all(), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +template +inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + asio::error_code& ec, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + return read(s, buffers, transfer_all(), ec); +} + +template +inline std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + ec = asio::error_code(); + std::size_t total_transferred = 0; + std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + std::size_t bytes_available = std::min( + std::max(512, b.capacity() - b.size()), + std::min(max_size, b.max_size() - b.size())); + while (bytes_available > 0) + { + std::size_t bytes_transferred = s.read_some(b.prepare(bytes_available), ec); + b.commit(bytes_transferred); + total_transferred += bytes_transferred; + max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + bytes_available = std::min( + std::max(512, b.capacity() - b.size()), + std::min(max_size, b.max_size() - b.size())); + } + return total_transferred; +} + +template +inline std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), transfer_all(), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +template +inline std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return read(s, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline std::size_t read(SyncReadStream& s, + asio::basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec) +{ + return read(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t read(SyncReadStream& s, + asio::basic_streambuf& b) +{ + return read(s, basic_streambuf_ref(b)); +} + +template +inline std::size_t read(SyncReadStream& s, + asio::basic_streambuf& b, + asio::error_code& ec) +{ + return read(s, basic_streambuf_ref(b), ec); +} + +template +inline std::size_t read(SyncReadStream& s, + asio::basic_streambuf& b, + CompletionCondition completion_condition) +{ + return read(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + DynamicBuffer_v2& b = buffers; + + ec = asio::error_code(); + std::size_t total_transferred = 0; + std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + std::size_t bytes_available = std::min( + std::max(512, b.capacity() - b.size()), + std::min(max_size, b.max_size() - b.size())); + while (bytes_available > 0) + { + std::size_t pos = b.size(); + b.grow(bytes_available); + std::size_t bytes_transferred = s.read_some( + b.data(pos, bytes_available), ec); + b.shrink(bytes_available - bytes_transferred); + total_transferred += bytes_transferred; + max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + bytes_available = std::min( + std::max(512, b.capacity() - b.size()), + std::min(max_size, b.max_size() - b.size())); + } + return total_transferred; +} + +template +inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), transfer_all(), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +template +inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return read(s, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "read"); + return bytes_transferred; +} + +namespace detail +{ + template + class read_op + : detail::base_from_completion_cond + { + public: + read_op(AsyncReadStream& stream, const MutableBufferSequence& buffers, + CompletionCondition& completion_condition, ReadHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + stream_(stream), + buffers_(buffers), + start_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_op(const read_op& other) + : detail::base_from_completion_cond(other), + stream_(other.stream_), + buffers_(other.buffers_), + start_(other.start_), + handler_(other.handler_) + { + } + + read_op(read_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(buffers_type)(other.buffers_)), + start_(other.start_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + do + { + stream_.async_read_some(buffers_.prepare(max_size), + ASIO_MOVE_CAST(read_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + if ((!ec && bytes_transferred == 0) || buffers_.empty()) + break; + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + } while (max_size > 0); + + handler_(ec, buffers_.total_consumed()); + } + } + + //private: + typedef asio::detail::consuming_buffers buffers_type; + + AsyncReadStream& stream_; + buffers_type buffers_; + int start_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void start_read_buffer_sequence_op(AsyncReadStream& stream, + const MutableBufferSequence& buffers, const MutableBufferIterator&, + CompletionCondition& completion_condition, ReadHandler& handler) + { + detail::read_op( + stream, buffers, completion_condition, handler)( + asio::error_code(), 0, 1); + } + + template + class initiate_async_read_buffer_sequence + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_buffer_sequence(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + start_read_buffer_sequence_op(stream_, buffers, + asio::buffer_sequence_begin(buffers), + completion_cond2.value, handler2.value); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_buffer_sequence(s), handler, + buffers, ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_mutable_buffer_sequence::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_buffer_sequence(s), + handler, buffers, transfer_all()); +} + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class read_dynbuf_v1_op + : detail::base_from_completion_cond + { + public: + template + read_dynbuf_v1_op(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + CompletionCondition& completion_condition, ReadHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + start_(0), + total_transferred_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_dynbuf_v1_op(const read_dynbuf_v1_op& other) + : detail::base_from_completion_cond(other), + stream_(other.stream_), + buffers_(other.buffers_), + start_(other.start_), + total_transferred_(other.total_transferred_), + handler_(other.handler_) + { + } + + read_dynbuf_v1_op(read_dynbuf_v1_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + start_(other.start_), + total_transferred_(other.total_transferred_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size, bytes_available; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(max_size, + buffers_.max_size() - buffers_.size())); + for (;;) + { + stream_.async_read_some(buffers_.prepare(bytes_available), + ASIO_MOVE_CAST(read_dynbuf_v1_op)(*this)); + return; default: + total_transferred_ += bytes_transferred; + buffers_.commit(bytes_transferred); + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(max_size, + buffers_.max_size() - buffers_.size())); + if ((!ec && bytes_transferred == 0) || bytes_available == 0) + break; + } + + handler_(ec, static_cast(total_transferred_)); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v1 buffers_; + int start_; + std::size_t total_transferred_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_dynbuf_v1_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_dynbuf_v1_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_dynbuf_v1_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_dynbuf_v1_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_dynbuf_v1_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_dynbuf_v1 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_dynbuf_v1(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + read_dynbuf_v1_op::type, + CompletionCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + completion_cond2.value, handler2.value)( + asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_dynbuf_v1_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_dynbuf_v1_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_dynbuf_v1_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_dynbuf_v1_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_read(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + transfer_all(), ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + return async_initiate( + detail::initiate_async_read_dynbuf_v1(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, basic_streambuf& b, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_read(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_read(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), + ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class read_dynbuf_v2_op + : detail::base_from_completion_cond + { + public: + template + read_dynbuf_v2_op(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + CompletionCondition& completion_condition, ReadHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + start_(0), + total_transferred_(0), + bytes_available_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_dynbuf_v2_op(const read_dynbuf_v2_op& other) + : detail::base_from_completion_cond(other), + stream_(other.stream_), + buffers_(other.buffers_), + start_(other.start_), + total_transferred_(other.total_transferred_), + bytes_available_(other.bytes_available_), + handler_(other.handler_) + { + } + + read_dynbuf_v2_op(read_dynbuf_v2_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + start_(other.start_), + total_transferred_(other.total_transferred_), + bytes_available_(other.bytes_available_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size, pos; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(max_size, + buffers_.max_size() - buffers_.size())); + for (;;) + { + pos = buffers_.size(); + buffers_.grow(bytes_available_); + stream_.async_read_some(buffers_.data(pos, bytes_available_), + ASIO_MOVE_CAST(read_dynbuf_v2_op)(*this)); + return; default: + total_transferred_ += bytes_transferred; + buffers_.shrink(bytes_available_ - bytes_transferred); + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(max_size, + buffers_.max_size() - buffers_.size())); + if ((!ec && bytes_transferred == 0) || bytes_available_ == 0) + break; + } + + handler_(ec, static_cast(total_transferred_)); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v2 buffers_; + int start_; + std::size_t total_transferred_; + std::size_t bytes_available_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_dynbuf_v2_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_dynbuf_v2_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_dynbuf_v2_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_dynbuf_v2_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_dynbuf_v2_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_dynbuf_v2 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_dynbuf_v2(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + read_dynbuf_v2_op::type, + CompletionCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + completion_cond2.value, handler2.value)( + asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_dynbuf_v2_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_dynbuf_v2_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_dynbuf_v2_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_dynbuf_v2_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_read(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + transfer_all(), ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + // If you get an error on the following line it means that your handler does + // not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + return async_initiate( + detail::initiate_async_read_dynbuf_v2(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_READ_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_at.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_at.hpp new file mode 100644 index 00000000..bee6be75 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_at.hpp @@ -0,0 +1,699 @@ +// +// impl/read_at.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_READ_AT_HPP +#define ASIO_IMPL_READ_AT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/base_from_completion_cond.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/consuming_buffers.hpp" +#include "asio/detail/dependent_type.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + std::size_t read_at_buffer_sequence(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + const MutableBufferIterator&, CompletionCondition completion_condition, + asio::error_code& ec) + { + ec = asio::error_code(); + asio::detail::consuming_buffers tmp(buffers); + while (!tmp.empty()) + { + if (std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, tmp.total_consumed()))) + { + tmp.consume(d.read_some_at(offset + tmp.total_consumed(), + tmp.prepare(max_size), ec)); + } + else + break; + } + return tmp.total_consumed();; + } +} // namespace detail + +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec) +{ + return detail::read_at_buffer_sequence(d, offset, buffers, + asio::buffer_sequence_begin(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_at( + d, offset, buffers, transfer_all(), ec); + asio::detail::throw_error(ec, "read_at"); + return bytes_transferred; +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + asio::error_code& ec) +{ + return read_at(d, offset, buffers, transfer_all(), ec); +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_at(d, offset, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "read_at"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec) +{ + ec = asio::error_code(); + std::size_t total_transferred = 0; + std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + std::size_t bytes_available = read_size_helper(b, max_size); + while (bytes_available > 0) + { + std::size_t bytes_transferred = d.read_some_at( + offset + total_transferred, b.prepare(bytes_available), ec); + b.commit(bytes_transferred); + total_transferred += bytes_transferred; + max_size = detail::adapt_completion_condition_result( + completion_condition(ec, total_transferred)); + bytes_available = read_size_helper(b, max_size); + } + return total_transferred; +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_at( + d, offset, b, transfer_all(), ec); + asio::detail::throw_error(ec, "read_at"); + return bytes_transferred; +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b, + asio::error_code& ec) +{ + return read_at(d, offset, b, transfer_all(), ec); +} + +template +inline std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_at(d, offset, b, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "read_at"); + return bytes_transferred; +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +namespace detail +{ + template + class read_at_op + : detail::base_from_completion_cond + { + public: + read_at_op(AsyncRandomAccessReadDevice& device, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition& completion_condition, ReadHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + device_(device), + offset_(offset), + buffers_(buffers), + start_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_at_op(const read_at_op& other) + : detail::base_from_completion_cond(other), + device_(other.device_), + offset_(other.offset_), + buffers_(other.buffers_), + start_(other.start_), + handler_(other.handler_) + { + } + + read_at_op(read_at_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + device_(other.device_), + offset_(other.offset_), + buffers_(ASIO_MOVE_CAST(buffers_type)(other.buffers_)), + start_(other.start_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + do + { + device_.async_read_some_at( + offset_ + buffers_.total_consumed(), buffers_.prepare(max_size), + ASIO_MOVE_CAST(read_at_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + if ((!ec && bytes_transferred == 0) || buffers_.empty()) + break; + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + } while (max_size > 0); + + handler_(ec, buffers_.total_consumed()); + } + } + + //private: + typedef asio::detail::consuming_buffers buffers_type; + + AsyncRandomAccessReadDevice& device_; + uint64_t offset_; + buffers_type buffers_; + int start_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_at_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_at_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_at_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_at_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_at_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void start_read_at_buffer_sequence_op(AsyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + const MutableBufferIterator&, CompletionCondition& completion_condition, + ReadHandler& handler) + { + detail::read_at_op( + d, offset, buffers, completion_condition, handler)( + asio::error_code(), 0, 1); + } + + template + class initiate_async_read_at_buffer_sequence + { + public: + typedef typename AsyncRandomAccessReadDevice::executor_type executor_type; + + explicit initiate_async_read_at_buffer_sequence( + AsyncRandomAccessReadDevice& device) + : device_(device) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return device_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + uint64_t offset, const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + start_read_at_buffer_sequence_op(device_, offset, buffers, + asio::buffer_sequence_begin(buffers), + completion_cond2.value, handler2.value); + } + + private: + AsyncRandomAccessReadDevice& device_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_at_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_at_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_at_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_at_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_read_at_buffer_sequence< + AsyncRandomAccessReadDevice>(d), + handler, offset, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_read_at_buffer_sequence< + AsyncRandomAccessReadDevice>(d), + handler, offset, buffers, transfer_all()); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +namespace detail +{ + template + class read_at_streambuf_op + : detail::base_from_completion_cond + { + public: + read_at_streambuf_op(AsyncRandomAccessReadDevice& device, + uint64_t offset, basic_streambuf& streambuf, + CompletionCondition& completion_condition, ReadHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + device_(device), + offset_(offset), + streambuf_(streambuf), + start_(0), + total_transferred_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_at_streambuf_op(const read_at_streambuf_op& other) + : detail::base_from_completion_cond(other), + device_(other.device_), + offset_(other.offset_), + streambuf_(other.streambuf_), + start_(other.start_), + total_transferred_(other.total_transferred_), + handler_(other.handler_) + { + } + + read_at_streambuf_op(read_at_streambuf_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + device_(other.device_), + offset_(other.offset_), + streambuf_(other.streambuf_), + start_(other.start_), + total_transferred_(other.total_transferred_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size, bytes_available; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available = read_size_helper(streambuf_, max_size); + for (;;) + { + device_.async_read_some_at(offset_ + total_transferred_, + streambuf_.prepare(bytes_available), + ASIO_MOVE_CAST(read_at_streambuf_op)(*this)); + return; default: + total_transferred_ += bytes_transferred; + streambuf_.commit(bytes_transferred); + max_size = this->check_for_completion(ec, total_transferred_); + bytes_available = read_size_helper(streambuf_, max_size); + if ((!ec && bytes_transferred == 0) || bytes_available == 0) + break; + } + + handler_(ec, static_cast(total_transferred_)); + } + } + + //private: + AsyncRandomAccessReadDevice& device_; + uint64_t offset_; + asio::basic_streambuf& streambuf_; + int start_; + std::size_t total_transferred_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_at_streambuf_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_at_streambuf_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_at_streambuf_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_at_streambuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_at_streambuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_at_streambuf + { + public: + typedef typename AsyncRandomAccessReadDevice::executor_type executor_type; + + explicit initiate_async_read_at_streambuf( + AsyncRandomAccessReadDevice& device) + : device_(device) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return device_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + uint64_t offset, basic_streambuf* b, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + read_at_streambuf_op::type>( + device_, offset, *b, completion_cond2.value, handler2.value)( + asio::error_code(), 0, 1); + } + + private: + AsyncRandomAccessReadDevice& device_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_at_streambuf_op, + Allocator1> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_at_streambuf_op& h, + const Allocator1& a = Allocator1()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_at_streambuf_op, + Executor1> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_at_streambuf_op& h, + const Executor1& ex = Executor1()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_read_at_streambuf(d), + handler, offset, &b, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, asio::basic_streambuf& b, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_initiate( + detail::initiate_async_read_at_streambuf(d), + handler, offset, &b, transfer_all()); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_READ_AT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_until.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_until.hpp new file mode 100644 index 00000000..08b8677c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/read_until.hpp @@ -0,0 +1,3150 @@ +// +// impl/read_until.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_READ_UNTIL_HPP +#define ASIO_IMPL_READ_UNTIL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include +#include +#include +#include +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/buffers_iterator.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/limits.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + // Algorithm that finds a subsequence of equal values in a sequence. Returns + // (iterator,true) if a full match was found, in which case the iterator + // points to the beginning of the match. Returns (iterator,false) if a + // partial match was found at the end of the first sequence, in which case + // the iterator points to the beginning of the partial match. Returns + // (last1,false) if no full or partial match was found. + template + std::pair partial_search( + Iterator1 first1, Iterator1 last1, Iterator2 first2, Iterator2 last2) + { + for (Iterator1 iter1 = first1; iter1 != last1; ++iter1) + { + Iterator1 test_iter1 = iter1; + Iterator2 test_iter2 = first2; + for (;; ++test_iter1, ++test_iter2) + { + if (test_iter2 == last2) + return std::make_pair(iter1, true); + if (test_iter1 == last1) + { + if (test_iter2 != first2) + return std::make_pair(iter1, false); + else + break; + } + if (*test_iter1 != *test_iter2) + break; + } + } + return std::make_pair(last1, false); + } +} // namespace detail + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +inline std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, char delim, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), delim, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + char delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = b.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + iterator iter = std::find(start_pos, end, delim); + if (iter != end) + { + // Found a match. We're done. + ec = asio::error_code(); + return iter - begin + 1; + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + b.commit(s.read_some(b.prepare(bytes_to_read), ec)); + if (ec) + return 0; + } +} + +template +inline std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), delim, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = b.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = detail::partial_search( + start_pos, end, delim.begin(), delim.end()); + if (result.first != end) + { + if (result.second) + { + // Full match. We're done. + ec = asio::error_code(); + return result.first - begin + delim.length(); + } + else + { + // Partial match. Next search needs to start from beginning of match. + search_position = result.first - begin; + } + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + b.commit(s.read_some(b.prepare(bytes_to_read), ec)); + if (ec) + return 0; + } +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), expr, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = b.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + boost::match_results >::allocator_type> + match_results; + if (regex_search(start_pos, end, match_results, expr, + boost::match_default | boost::match_partial)) + { + if (match_results[0].matched) + { + // Full match. We're done. + ec = asio::error_code(); + return match_results[0].second - begin; + } + else + { + // Partial match. Next search needs to start from beginning of match. + search_position = match_results[0].first - begin; + } + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + b.commit(s.read_some(b.prepare(bytes_to_read), ec)); + if (ec) + return 0; + } +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + match_condition, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = b.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = match_condition(start_pos, end); + if (result.second) + { + // Full match. We're done. + ec = asio::error_code(); + return result.first - begin; + } + else if (result.first != end) + { + // Partial match. Next search needs to start from beginning of match. + search_position = result.first - begin; + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + b.commit(s.read_some(b.prepare(bytes_to_read), ec)); + if (ec) + return 0; + } +} + +#if !defined(ASIO_NO_IOSTREAM) + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, char delim) +{ + return read_until(s, basic_streambuf_ref(b), delim); +} + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, char delim, + asio::error_code& ec) +{ + return read_until(s, basic_streambuf_ref(b), delim, ec); +} + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim) +{ + return read_until(s, basic_streambuf_ref(b), delim); +} + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec) +{ + return read_until(s, basic_streambuf_ref(b), delim, ec); +} + +#if defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr) +{ + return read_until(s, basic_streambuf_ref(b), expr); +} + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr, + asio::error_code& ec) +{ + return read_until(s, basic_streambuf_ref(b), expr, ec); +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, MatchCondition match_condition, + typename enable_if::value>::type*) +{ + return read_until(s, basic_streambuf_ref(b), match_condition); +} + +template +inline std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if::value>::type*) +{ + return read_until(s, basic_streambuf_ref(b), match_condition, ec); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +inline std::size_t read_until(SyncReadStream& s, + DynamicBuffer_v2 buffers, char delim, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), delim, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + char delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + DynamicBuffer_v2& b = buffers; + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(b).data(0, b.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + iterator iter = std::find(start_pos, end, delim); + if (iter != end) + { + // Found a match. We're done. + ec = asio::error_code(); + return iter - begin + 1; + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + std::size_t pos = b.size(); + b.grow(bytes_to_read); + std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec); + b.shrink(bytes_to_read - bytes_transferred); + if (ec) + return 0; + } +} + +template +inline std::size_t read_until(SyncReadStream& s, + DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), delim, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + DynamicBuffer_v2& b = buffers; + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(b).data(0, b.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = detail::partial_search( + start_pos, end, delim.begin(), delim.end()); + if (result.first != end) + { + if (result.second) + { + // Full match. We're done. + ec = asio::error_code(); + return result.first - begin + delim.length(); + } + else + { + // Partial match. Next search needs to start from beginning of match. + search_position = result.first - begin; + } + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + std::size_t pos = b.size(); + b.grow(bytes_to_read); + std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec); + b.shrink(bytes_to_read - bytes_transferred); + if (ec) + return 0; + } +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + DynamicBuffer_v2 buffers, const boost::regex& expr, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), expr, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + const boost::regex& expr, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + DynamicBuffer_v2& b = buffers; + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(b).data(0, b.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + boost::match_results >::allocator_type> + match_results; + if (regex_search(start_pos, end, match_results, expr, + boost::match_default | boost::match_partial)) + { + if (match_results[0].matched) + { + // Full match. We're done. + ec = asio::error_code(); + return match_results[0].second - begin; + } + else + { + // Partial match. Next search needs to start from beginning of match. + search_position = match_results[0].first - begin; + } + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + std::size_t pos = b.size(); + b.grow(bytes_to_read); + std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec); + b.shrink(bytes_to_read - bytes_transferred); + if (ec) + return 0; + } +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +template +inline std::size_t read_until(SyncReadStream& s, + DynamicBuffer_v2 buffers, MatchCondition match_condition, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = read_until(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + match_condition, ec); + asio::detail::throw_error(ec, "read_until"); + return bytes_transferred; +} + +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type*) +{ + DynamicBuffer_v2& b = buffers; + + std::size_t search_position = 0; + for (;;) + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(b).data(0, b.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = match_condition(start_pos, end); + if (result.second) + { + // Full match. We're done. + ec = asio::error_code(); + return result.first - begin; + } + else if (result.first != end) + { + // Partial match. Next search needs to start from beginning of match. + search_position = result.first - begin; + } + else + { + // No match. Next search can start with the new data. + search_position = end - begin; + } + + // Check if buffer is full. + if (b.size() == b.max_size()) + { + ec = error::not_found; + return 0; + } + + // Need more data. + std::size_t bytes_to_read = std::min( + std::max(512, b.capacity() - b.size()), + std::min(65536, b.max_size() - b.size())); + std::size_t pos = b.size(); + b.grow(bytes_to_read); + std::size_t bytes_transferred = s.read_some(b.data(pos, bytes_to_read), ec); + b.shrink(bytes_to_read - bytes_transferred); + if (ec) + return 0; + } +} + +#endif // !defined(ASIO_NO_EXTENSIONS) + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class read_until_delim_op_v1 + { + public: + template + read_until_delim_op_v1(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + char delim, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + delim_(delim), + start_(0), + search_position_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_delim_op_v1(const read_until_delim_op_v1& other) + : stream_(other.stream_), + buffers_(other.buffers_), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + handler_(other.handler_) + { + } + + read_until_delim_op_v1(read_until_delim_op_v1&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t bytes_to_read; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = buffers_.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + iterator iter = std::find(start_pos, end, delim_); + if (iter != end) + { + // Found a match. We're done. + search_position_ = iter - begin + 1; + bytes_to_read = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read = 0; + } + + // Need to read some more data. + else + { + // Next search can start with the new data. + search_position_ = end - begin; + bytes_to_read = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read == 0) + break; + + // Start a new asynchronous read op_v1eration to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_delim_op_v1)(*this)); + return; default: + buffers_.commit(bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v1 buffers_; + char delim_; + int start_; + std::size_t search_position_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_delim_op_v1* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_delim_op_v1* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_op_v1* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_delim_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_delim_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_delim_v1 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_delim_v1(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + char delim) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_delim_op_v1::type, + typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + delim, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_op_v1, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_op_v1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_op_v1, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_op_v1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + char delim, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_delim_v1(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), delim); +} + +namespace detail +{ + template + class read_until_delim_string_op_v1 + { + public: + template + read_until_delim_string_op_v1(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + const std::string& delim, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + delim_(delim), + start_(0), + search_position_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_delim_string_op_v1(const read_until_delim_string_op_v1& other) + : stream_(other.stream_), + buffers_(other.buffers_), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + handler_(other.handler_) + { + } + + read_until_delim_string_op_v1(read_until_delim_string_op_v1&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + delim_(ASIO_MOVE_CAST(std::string)(other.delim_)), + start_(other.start_), + search_position_(other.search_position_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t bytes_to_read; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = buffers_.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = detail::partial_search( + start_pos, end, delim_.begin(), delim_.end()); + if (result.first != end && result.second) + { + // Full match. We're done. + search_position_ = result.first - begin + delim_.length(); + bytes_to_read = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read = 0; + } + + // Need to read some more data. + else + { + if (result.first != end) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = result.first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read == 0) + break; + + // Start a new asynchronous read op_v1eration to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_delim_string_op_v1)(*this)); + return; default: + buffers_.commit(bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v1 buffers_; + std::string delim_; + int start_; + std::size_t search_position_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_delim_string_op_v1* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_delim_string_op_v1* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_string_op_v1* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_delim_string_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_delim_string_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_delim_string_v1 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_delim_string_v1(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const std::string& delim) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_delim_string_op_v1::type, + typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + delim, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_string_op_v1, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_string_op_v1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_string_op_v1, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_string_op_v1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_delim_string_v1(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + static_cast(delim)); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_expr_op_v1 + { + public: + template + read_until_expr_op_v1(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + const boost::regex& expr, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + expr_(expr), + start_(0), + search_position_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_expr_op_v1(const read_until_expr_op_v1& other) + : stream_(other.stream_), + buffers_(other.buffers_), + expr_(other.expr_), + start_(other.start_), + search_position_(other.search_position_), + handler_(other.handler_) + { + } + + read_until_expr_op_v1(read_until_expr_op_v1&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + expr_(other.expr_), + start_(other.start_), + search_position_(other.search_position_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t bytes_to_read; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = buffers_.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + boost::match_results >::allocator_type> + match_results; + bool match = regex_search(start_pos, end, match_results, expr_, + boost::match_default | boost::match_partial); + if (match && match_results[0].matched) + { + // Full match. We're done. + search_position_ = match_results[0].second - begin; + bytes_to_read = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read = 0; + } + + // Need to read some more data. + else + { + if (match) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = match_results[0].first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read == 0) + break; + + // Start a new asynchronous read op_v1eration to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_expr_op_v1)(*this)); + return; default: + buffers_.commit(bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v1 buffers_; + RegEx expr_; + int start_; + std::size_t search_position_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_expr_op_v1* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_expr_op_v1* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_expr_op_v1* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_expr_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_expr_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_expr_v1 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_expr_v1(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, const RegEx& expr) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_expr_op_v1::type, + RegEx, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + expr, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_expr_op_v1, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_expr_op_v1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_expr_op_v1, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_expr_op_v1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_expr_v1(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), expr); +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_match_op_v1 + { + public: + template + read_until_match_op_v1(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + MatchCondition match_condition, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + match_condition_(match_condition), + start_(0), + search_position_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_match_op_v1(const read_until_match_op_v1& other) + : stream_(other.stream_), + buffers_(other.buffers_), + match_condition_(other.match_condition_), + start_(other.start_), + search_position_(other.search_position_), + handler_(other.handler_) + { + } + + read_until_match_op_v1(read_until_match_op_v1&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + match_condition_(other.match_condition_), + start_(other.start_), + search_position_(other.search_position_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t bytes_to_read; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v1::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = buffers_.data(); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = match_condition_(start_pos, end); + if (result.second) + { + // Full match. We're done. + search_position_ = result.first - begin; + bytes_to_read = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read = 0; + } + + // Need to read some more data. + else + { + if (result.first != end) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = result.first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read == 0) + break; + + // Start a new asynchronous read op_v1eration to obtain more data. + stream_.async_read_some(buffers_.prepare(bytes_to_read), + ASIO_MOVE_CAST(read_until_match_op_v1)(*this)); + return; default: + buffers_.commit(bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v1 buffers_; + MatchCondition match_condition_; + int start_; + std::size_t search_position_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_match_op_v1* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_match_op_v1* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_match_op_v1* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_match_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_match_op_v1* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_match_v1 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_match_v1(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_match_op_v1::type, + MatchCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + match_condition, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_match_op_v1, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_match_op_v1& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_match_op_v1, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_match_op_v1& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_match_v1(s), handler, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), match_condition); +} + +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, + char delim, ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_read_until(s, basic_streambuf_ref(b), + delim, ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_read_until(s, basic_streambuf_ref(b), + delim, ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +#if defined(ASIO_HAS_BOOST_REGEX) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler) +{ + return async_read_until(s, basic_streambuf_ref(b), + expr, ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, + MatchCondition match_condition, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if::value>::type*) +{ + return async_read_until(s, basic_streambuf_ref(b), + match_condition, ASIO_MOVE_CAST(ReadHandler)(handler)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class read_until_delim_op_v2 + { + public: + template + read_until_delim_op_v2(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + char delim, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + delim_(delim), + start_(0), + search_position_(0), + bytes_to_read_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_delim_op_v2(const read_until_delim_op_v2& other) + : stream_(other.stream_), + buffers_(other.buffers_), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(other.handler_) + { + } + + read_until_delim_op_v2(read_until_delim_op_v2&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t pos; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(buffers_).data( + 0, buffers_.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + iterator iter = std::find(start_pos, end, delim_); + if (iter != end) + { + // Found a match. We're done. + search_position_ = iter - begin + 1; + bytes_to_read_ = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read_ = 0; + } + + // Need to read some more data. + else + { + // Next search can start with the new data. + search_position_ = end - begin; + bytes_to_read_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read_ == 0) + break; + + // Start a new asynchronous read op_v2eration to obtain more data. + pos = buffers_.size(); + buffers_.grow(bytes_to_read_); + stream_.async_read_some(buffers_.data(pos, bytes_to_read_), + ASIO_MOVE_CAST(read_until_delim_op_v2)(*this)); + return; default: + buffers_.shrink(bytes_to_read_ - bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v2 buffers_; + char delim_; + int start_; + std::size_t search_position_; + std::size_t bytes_to_read_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_delim_op_v2* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_delim_op_v2* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_op_v2* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_delim_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_delim_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_delim_v2 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_delim_v2(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, char delim) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_delim_op_v2::type, + typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + delim, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_op_v2, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_op_v2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_op_v2, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_op_v2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + char delim, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_delim_v2(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), delim); +} + +namespace detail +{ + template + class read_until_delim_string_op_v2 + { + public: + template + read_until_delim_string_op_v2(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + const std::string& delim, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + delim_(delim), + start_(0), + search_position_(0), + bytes_to_read_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_delim_string_op_v2(const read_until_delim_string_op_v2& other) + : stream_(other.stream_), + buffers_(other.buffers_), + delim_(other.delim_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(other.handler_) + { + } + + read_until_delim_string_op_v2(read_until_delim_string_op_v2&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + delim_(ASIO_MOVE_CAST(std::string)(other.delim_)), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t pos; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(buffers_).data( + 0, buffers_.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = detail::partial_search( + start_pos, end, delim_.begin(), delim_.end()); + if (result.first != end && result.second) + { + // Full match. We're done. + search_position_ = result.first - begin + delim_.length(); + bytes_to_read_ = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read_ = 0; + } + + // Need to read some more data. + else + { + if (result.first != end) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = result.first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read_ == 0) + break; + + // Start a new asynchronous read op_v2eration to obtain more data. + pos = buffers_.size(); + buffers_.grow(bytes_to_read_); + stream_.async_read_some(buffers_.data(pos, bytes_to_read_), + ASIO_MOVE_CAST(read_until_delim_string_op_v2)(*this)); + return; default: + buffers_.shrink(bytes_to_read_ - bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v2 buffers_; + std::string delim_; + int start_; + std::size_t search_position_; + std::size_t bytes_to_read_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_delim_string_op_v2* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_delim_string_op_v2* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_delim_string_op_v2* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_delim_string_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_delim_string_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_delim_string_v2 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_delim_string_v2(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, + const std::string& delim) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_delim_string_op_v2::type, + typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + delim, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_delim_string_op_v2, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_delim_string_op_v2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_delim_string_op_v2, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_delim_string_op_v2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + DynamicBuffer_v2 buffers, ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_delim_string_v2(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + static_cast(delim)); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_expr_op_v2 + { + public: + template + read_until_expr_op_v2(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + const boost::regex& expr, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + expr_(expr), + start_(0), + search_position_(0), + bytes_to_read_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_expr_op_v2(const read_until_expr_op_v2& other) + : stream_(other.stream_), + buffers_(other.buffers_), + expr_(other.expr_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(other.handler_) + { + } + + read_until_expr_op_v2(read_until_expr_op_v2&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + expr_(other.expr_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t pos; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(buffers_).data( + 0, buffers_.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + boost::match_results >::allocator_type> + match_results; + bool match = regex_search(start_pos, end, match_results, expr_, + boost::match_default | boost::match_partial); + if (match && match_results[0].matched) + { + // Full match. We're done. + search_position_ = match_results[0].second - begin; + bytes_to_read_ = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read_ = 0; + } + + // Need to read some more data. + else + { + if (match) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = match_results[0].first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read_ == 0) + break; + + // Start a new asynchronous read op_v2eration to obtain more data. + pos = buffers_.size(); + buffers_.grow(bytes_to_read_); + stream_.async_read_some(buffers_.data(pos, bytes_to_read_), + ASIO_MOVE_CAST(read_until_expr_op_v2)(*this)); + return; default: + buffers_.shrink(bytes_to_read_ - bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v2 buffers_; + RegEx expr_; + int start_; + std::size_t search_position_; + std::size_t bytes_to_read_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_expr_op_v2* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_expr_op_v2* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_expr_op_v2* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_expr_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_expr_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_expr_v2 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_expr_v2(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, + const RegEx& expr) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_expr_op_v2::type, + RegEx, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + expr, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_expr_op_v2, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_expr_op_v2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_expr_op_v2, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_expr_op_v2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + const boost::regex& expr, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_expr_v2(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), expr); +} + +#endif // defined(ASIO_HAS_BOOST_REGEX) + +namespace detail +{ + template + class read_until_match_op_v2 + { + public: + template + read_until_match_op_v2(AsyncReadStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + MatchCondition match_condition, ReadHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + match_condition_(match_condition), + start_(0), + search_position_(0), + bytes_to_read_(0), + handler_(ASIO_MOVE_CAST(ReadHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + read_until_match_op_v2(const read_until_match_op_v2& other) + : stream_(other.stream_), + buffers_(other.buffers_), + match_condition_(other.match_condition_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(other.handler_) + { + } + + read_until_match_op_v2(read_until_match_op_v2&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + match_condition_(other.match_condition_), + start_(other.start_), + search_position_(other.search_position_), + bytes_to_read_(other.bytes_to_read_), + handler_(ASIO_MOVE_CAST(ReadHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + const std::size_t not_found = (std::numeric_limits::max)(); + std::size_t pos; + switch (start_ = start) + { + case 1: + for (;;) + { + { + // Determine the range of the data to be searched. + typedef typename DynamicBuffer_v2::const_buffers_type + buffers_type; + typedef buffers_iterator iterator; + buffers_type data_buffers = + const_cast(buffers_).data( + 0, buffers_.size()); + iterator begin = iterator::begin(data_buffers); + iterator start_pos = begin + search_position_; + iterator end = iterator::end(data_buffers); + + // Look for a match. + std::pair result = match_condition_(start_pos, end); + if (result.second) + { + // Full match. We're done. + search_position_ = result.first - begin; + bytes_to_read_ = 0; + } + + // No match yet. Check if buffer is full. + else if (buffers_.size() == buffers_.max_size()) + { + search_position_ = not_found; + bytes_to_read_ = 0; + } + + // Need to read some more data. + else + { + if (result.first != end) + { + // Partial match. Next search needs to start from beginning of + // match. + search_position_ = result.first - begin; + } + else + { + // Next search can start with the new data. + search_position_ = end - begin; + } + + bytes_to_read_ = std::min( + std::max(512, + buffers_.capacity() - buffers_.size()), + std::min(65536, + buffers_.max_size() - buffers_.size())); + } + } + + // Check if we're done. + if (!start && bytes_to_read_ == 0) + break; + + // Start a new asynchronous read op_v2eration to obtain more data. + pos = buffers_.size(); + buffers_.grow(bytes_to_read_); + stream_.async_read_some(buffers_.data(pos, bytes_to_read_), + ASIO_MOVE_CAST(read_until_match_op_v2)(*this)); + return; default: + buffers_.shrink(bytes_to_read_ - bytes_transferred); + if (ec || bytes_transferred == 0) + break; + } + + const asio::error_code result_ec = + (search_position_ == not_found) + ? error::not_found : ec; + + const std::size_t result_n = + (ec || search_position_ == not_found) + ? 0 : search_position_; + + handler_(result_ec, result_n); + } + } + + //private: + AsyncReadStream& stream_; + DynamicBuffer_v2 buffers_; + MatchCondition match_condition_; + int start_; + std::size_t search_position_; + std::size_t bytes_to_read_; + ReadHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + read_until_match_op_v2* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + read_until_match_op_v2* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + read_until_match_op_v2* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + read_until_match_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + read_until_match_op_v2* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_read_until_match_v2 + { + public: + typedef typename AsyncReadStream::executor_type executor_type; + + explicit initiate_async_read_until_match_v2(AsyncReadStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, + MatchCondition match_condition) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + non_const_lvalue handler2(handler); + read_until_match_op_v2::type, + MatchCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + match_condition, handler2.value)(asio::error_code(), 0, 1); + } + + private: + AsyncReadStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::read_until_match_op_v2, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::read_until_match_op_v2& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::read_until_match_op_v2, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::read_until_match_op_v2& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + MatchCondition match_condition, ASIO_MOVE_ARG(ReadHandler) handler, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type*) +{ + return async_initiate( + detail::initiate_async_read_until_match_v2(s), handler, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), match_condition); +} + +#endif // !defined(ASIO_NO_EXTENSIONS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_READ_UNTIL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/redirect_error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/redirect_error.hpp new file mode 100644 index 00000000..ca1e5e52 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/redirect_error.hpp @@ -0,0 +1,372 @@ + +// impl/redirect_error.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_REDIRECT_ERROR_HPP +#define ASIO_IMPL_REDIRECT_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_executor.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/variadic_templates.hpp" +#include "asio/system_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +// Class to adapt a redirect_error_t as a completion handler. +template +class redirect_error_handler +{ +public: + typedef void result_type; + + template + redirect_error_handler(redirect_error_t e) + : ec_(e.ec_), + handler_(ASIO_MOVE_CAST(CompletionToken)(e.token_)) + { + } + + template + redirect_error_handler(asio::error_code& ec, + ASIO_MOVE_ARG(RedirectedHandler) h) + : ec_(ec), + handler_(ASIO_MOVE_CAST(RedirectedHandler)(h)) + { + } + + void operator()() + { + handler_(); + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + typename enable_if< + !is_same::type, asio::error_code>::value + >::type + operator()(ASIO_MOVE_ARG(Arg) arg, ASIO_MOVE_ARG(Args)... args) + { + handler_(ASIO_MOVE_CAST(Arg)(arg), + ASIO_MOVE_CAST(Args)(args)...); + } + + template + void operator()(const asio::error_code& ec, + ASIO_MOVE_ARG(Args)... args) + { + ec_ = ec; + handler_(ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + typename enable_if< + !is_same::type, asio::error_code>::value + >::type + operator()(ASIO_MOVE_ARG(Arg) arg) + { + handler_(ASIO_MOVE_CAST(Arg)(arg)); + } + + void operator()(const asio::error_code& ec) + { + ec_ = ec; + handler_(); + } + +#define ASIO_PRIVATE_REDIRECT_ERROR_DEF(n) \ + template \ + typename enable_if< \ + !is_same::type, asio::error_code>::value \ + >::type \ + operator()(ASIO_MOVE_ARG(Arg) arg, ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + handler_(ASIO_MOVE_CAST(Arg)(arg), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + \ + template \ + void operator()(const asio::error_code& ec, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + ec_ = ec; \ + handler_(ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_REDIRECT_ERROR_DEF) +#undef ASIO_PRIVATE_REDIRECT_ERROR_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +//private: + asio::error_code& ec_; + Handler handler_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + redirect_error_handler* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + redirect_error_handler* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + redirect_error_handler* this_handler) +{ + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + redirect_error_handler* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + redirect_error_handler* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +struct redirect_error_signature +{ + typedef Signature type; +}; + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +struct redirect_error_signature +{ + typedef R type(Args...); +}; + +template +struct redirect_error_signature +{ + typedef R type(Args...); +}; + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +struct redirect_error_signature +{ + typedef R type(); +}; + +template +struct redirect_error_signature +{ + typedef R type(); +}; + +#define ASIO_PRIVATE_REDIRECT_ERROR_DEF(n) \ + template \ + struct redirect_error_signature< \ + R(asio::error_code, ASIO_VARIADIC_TARGS(n))> \ + { \ + typedef R type(ASIO_VARIADIC_TARGS(n)); \ + }; \ + \ + template \ + struct redirect_error_signature< \ + R(const asio::error_code&, ASIO_VARIADIC_TARGS(n))> \ + { \ + typedef R type(ASIO_VARIADIC_TARGS(n)); \ + }; \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_REDIRECT_ERROR_DEF) +#undef ASIO_PRIVATE_REDIRECT_ERROR_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct async_result, Signature> +{ + typedef typename async_result::type> + ::return_type return_type; + + template + struct init_wrapper + { + template + init_wrapper(asio::error_code& ec, ASIO_MOVE_ARG(Init) init) + : ec_(ec), + initiation_(ASIO_MOVE_CAST(Init)(init)) + { + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()( + ASIO_MOVE_ARG(Handler) handler, + ASIO_MOVE_ARG(Args)... args) + { + ASIO_MOVE_CAST(Initiation)(initiation_)( + detail::redirect_error_handler< + typename decay::type>( + ec_, ASIO_MOVE_CAST(Handler)(handler)), + ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()( + ASIO_MOVE_ARG(Handler) handler) + { + ASIO_MOVE_CAST(Initiation)(initiation_)( + detail::redirect_error_handler< + typename decay::type>( + ec_, ASIO_MOVE_CAST(Handler)(handler))); + } + +#define ASIO_PRIVATE_INIT_WRAPPER_DEF(n) \ + template \ + void operator()( \ + ASIO_MOVE_ARG(Handler) handler, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + ASIO_MOVE_CAST(Initiation)(initiation_)( \ + detail::redirect_error_handler< \ + typename decay::type>( \ + ec_, ASIO_MOVE_CAST(Handler)(handler)), \ + ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INIT_WRAPPER_DEF) +#undef ASIO_PRIVATE_INIT_WRAPPER_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + asio::error_code& ec_; + Initiation initiation_; + }; + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken) token, + ASIO_MOVE_ARG(Args)... args) + { + return async_initiate::type>( + init_wrapper::type>( + token.ec_, ASIO_MOVE_CAST(Initiation)(initiation)), + token.token_, ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + static return_type initiate( + ASIO_MOVE_ARG(Initiation) initiation, + ASIO_MOVE_ARG(RawCompletionToken) token) + { + return async_initiate::type>( + init_wrapper::type>( + token.ec_, ASIO_MOVE_CAST(Initiation)(initiation)), + token.token_); + } + +#define ASIO_PRIVATE_INITIATE_DEF(n) \ + template \ + static return_type initiate( \ + ASIO_MOVE_ARG(Initiation) initiation, \ + ASIO_MOVE_ARG(RawCompletionToken) token, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + return async_initiate::type>( \ + init_wrapper::type>( \ + token.ec_, ASIO_MOVE_CAST(Initiation)(initiation)), \ + token.token_, ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_INITIATE_DEF) +#undef ASIO_PRIVATE_INITIATE_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::redirect_error_handler& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::redirect_error_handler& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_REDIRECT_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/serial_port_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/serial_port_base.hpp new file mode 100644 index 00000000..d34dd5b1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/serial_port_base.hpp @@ -0,0 +1,59 @@ +// +// impl/serial_port_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_SERIAL_PORT_BASE_HPP +#define ASIO_IMPL_SERIAL_PORT_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +inline serial_port_base::baud_rate::baud_rate(unsigned int rate) + : value_(rate) +{ +} + +inline unsigned int serial_port_base::baud_rate::value() const +{ + return value_; +} + +inline serial_port_base::flow_control::type +serial_port_base::flow_control::value() const +{ + return value_; +} + +inline serial_port_base::parity::type serial_port_base::parity::value() const +{ + return value_; +} + +inline serial_port_base::stop_bits::type +serial_port_base::stop_bits::value() const +{ + return value_; +} + +inline unsigned int serial_port_base::character_size::value() const +{ + return value_; +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_SERIAL_PORT_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/spawn.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/spawn.hpp new file mode 100644 index 00000000..5235d3ff --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/spawn.hpp @@ -0,0 +1,490 @@ +// +// impl/spawn.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_SPAWN_HPP +#define ASIO_IMPL_SPAWN_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/async_result.hpp" +#include "asio/bind_executor.hpp" +#include "asio/detail/atomic_count.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/system_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + + template + class coro_handler + { + public: + coro_handler(basic_yield_context ctx) + : coro_(ctx.coro_.lock()), + ca_(ctx.ca_), + handler_(ctx.handler_), + ready_(0), + ec_(ctx.ec_), + value_(0) + { + } + + void operator()(T value) + { + *ec_ = asio::error_code(); + *value_ = ASIO_MOVE_CAST(T)(value); + if (--*ready_ == 0) + (*coro_)(); + } + + void operator()(asio::error_code ec, T value) + { + *ec_ = ec; + *value_ = ASIO_MOVE_CAST(T)(value); + if (--*ready_ == 0) + (*coro_)(); + } + + //private: + shared_ptr::callee_type> coro_; + typename basic_yield_context::caller_type& ca_; + Handler handler_; + atomic_count* ready_; + asio::error_code* ec_; + T* value_; + }; + + template + class coro_handler + { + public: + coro_handler(basic_yield_context ctx) + : coro_(ctx.coro_.lock()), + ca_(ctx.ca_), + handler_(ctx.handler_), + ready_(0), + ec_(ctx.ec_) + { + } + + void operator()() + { + *ec_ = asio::error_code(); + if (--*ready_ == 0) + (*coro_)(); + } + + void operator()(asio::error_code ec) + { + *ec_ = ec; + if (--*ready_ == 0) + (*coro_)(); + } + + //private: + shared_ptr::callee_type> coro_; + typename basic_yield_context::caller_type& ca_; + Handler handler_; + atomic_count* ready_; + asio::error_code* ec_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + coro_handler* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + coro_handler* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation(coro_handler*) + { + return true; + } + + template + inline void asio_handler_invoke(Function& function, + coro_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + coro_handler* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class coro_async_result + { + public: + typedef coro_handler completion_handler_type; + typedef T return_type; + + explicit coro_async_result(completion_handler_type& h) + : handler_(h), + ca_(h.ca_), + ready_(2) + { + h.ready_ = &ready_; + out_ec_ = h.ec_; + if (!out_ec_) h.ec_ = &ec_; + h.value_ = &value_; + } + + return_type get() + { + // Must not hold shared_ptr to coro while suspended. + handler_.coro_.reset(); + + if (--ready_ != 0) + ca_(); + if (!out_ec_ && ec_) throw asio::system_error(ec_); + return ASIO_MOVE_CAST(return_type)(value_); + } + + private: + completion_handler_type& handler_; + typename basic_yield_context::caller_type& ca_; + atomic_count ready_; + asio::error_code* out_ec_; + asio::error_code ec_; + return_type value_; + }; + + template + class coro_async_result + { + public: + typedef coro_handler completion_handler_type; + typedef void return_type; + + explicit coro_async_result(completion_handler_type& h) + : handler_(h), + ca_(h.ca_), + ready_(2) + { + h.ready_ = &ready_; + out_ec_ = h.ec_; + if (!out_ec_) h.ec_ = &ec_; + } + + void get() + { + // Must not hold shared_ptr to coro while suspended. + handler_.coro_.reset(); + + if (--ready_ != 0) + ca_(); + if (!out_ec_ && ec_) throw asio::system_error(ec_); + } + + private: + completion_handler_type& handler_; + typename basic_yield_context::caller_type& ca_; + atomic_count ready_; + asio::error_code* out_ec_; + asio::error_code ec_; + }; + +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +class async_result, ReturnType()> + : public detail::coro_async_result +{ +public: + explicit async_result( + typename detail::coro_async_result::completion_handler_type& h) + : detail::coro_async_result(h) + { + } +}; + +template +class async_result, ReturnType(Arg1)> + : public detail::coro_async_result::type> +{ +public: + explicit async_result( + typename detail::coro_async_result::type>::completion_handler_type& h) + : detail::coro_async_result::type>(h) + { + } +}; + +template +class async_result, + ReturnType(asio::error_code)> + : public detail::coro_async_result +{ +public: + explicit async_result( + typename detail::coro_async_result::completion_handler_type& h) + : detail::coro_async_result(h) + { + } +}; + +template +class async_result, + ReturnType(asio::error_code, Arg2)> + : public detail::coro_async_result::type> +{ +public: + explicit async_result( + typename detail::coro_async_result::type>::completion_handler_type& h) + : detail::coro_async_result::type>(h) + { + } +}; + +template +struct associated_allocator, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const detail::coro_handler& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const detail::coro_handler& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +namespace detail { + + template + struct spawn_data : private noncopyable + { + template + spawn_data(ASIO_MOVE_ARG(Hand) handler, + bool call_handler, ASIO_MOVE_ARG(Func) function) + : handler_(ASIO_MOVE_CAST(Hand)(handler)), + call_handler_(call_handler), + function_(ASIO_MOVE_CAST(Func)(function)) + { + } + + weak_ptr::callee_type> coro_; + Handler handler_; + bool call_handler_; + Function function_; + }; + + template + struct coro_entry_point + { + void operator()(typename basic_yield_context::caller_type& ca) + { + shared_ptr > data(data_); +#if !defined(BOOST_COROUTINES_UNIDIRECT) && !defined(BOOST_COROUTINES_V2) + ca(); // Yield until coroutine pointer has been initialised. +#endif // !defined(BOOST_COROUTINES_UNIDIRECT) && !defined(BOOST_COROUTINES_V2) + const basic_yield_context yield( + data->coro_, ca, data->handler_); + + (data->function_)(yield); + if (data->call_handler_) + (data->handler_)(); + } + + shared_ptr > data_; + }; + + template + struct spawn_helper + { + void operator()() + { + typedef typename basic_yield_context::callee_type callee_type; + coro_entry_point entry_point = { data_ }; + shared_ptr coro(new callee_type(entry_point, attributes_)); + data_->coro_ = coro; + (*coro)(); + } + + shared_ptr > data_; + boost::coroutines::attributes attributes_; + }; + + template + inline void asio_handler_invoke(Function& function, + spawn_helper* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->data_->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + spawn_helper* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->data_->handler_); + } + + inline void default_spawn_handler() {} + +} // namespace detail + +template +inline void spawn(ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes) +{ + typedef typename decay::type function_type; + + typename associated_executor::type ex( + (get_associated_executor)(function)); + + asio::spawn(ex, ASIO_MOVE_CAST(Function)(function), attributes); +} + +template +void spawn(ASIO_MOVE_ARG(Handler) handler, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes, + typename enable_if::type>::value && + !is_convertible::value>::type*) +{ + typedef typename decay::type handler_type; + typedef typename decay::type function_type; + + typename associated_executor::type ex( + (get_associated_executor)(handler)); + + typename associated_allocator::type a( + (get_associated_allocator)(handler)); + + detail::spawn_helper helper; + helper.data_.reset( + new detail::spawn_data( + ASIO_MOVE_CAST(Handler)(handler), true, + ASIO_MOVE_CAST(Function)(function))); + helper.attributes_ = attributes; + + ex.dispatch(helper, a); +} + +template +void spawn(basic_yield_context ctx, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes) +{ + typedef typename decay::type function_type; + + Handler handler(ctx.handler_); // Explicit copy that might be moved from. + + typename associated_executor::type ex( + (get_associated_executor)(handler)); + + typename associated_allocator::type a( + (get_associated_allocator)(handler)); + + detail::spawn_helper helper; + helper.data_.reset( + new detail::spawn_data( + ASIO_MOVE_CAST(Handler)(handler), false, + ASIO_MOVE_CAST(Function)(function))); + helper.attributes_ = attributes; + + ex.dispatch(helper, a); +} + +template +inline void spawn(const Executor& ex, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes, + typename enable_if::value>::type*) +{ + asio::spawn(asio::strand(ex), + ASIO_MOVE_CAST(Function)(function), attributes); +} + +template +inline void spawn(const strand& ex, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes) +{ + asio::spawn(asio::bind_executor( + ex, &detail::default_spawn_handler), + ASIO_MOVE_CAST(Function)(function), attributes); +} + +template +inline void spawn(const asio::io_context::strand& s, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes) +{ + asio::spawn(asio::bind_executor( + s, &detail::default_spawn_handler), + ASIO_MOVE_CAST(Function)(function), attributes); +} + +template +inline void spawn(ExecutionContext& ctx, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes, + typename enable_if::value>::type*) +{ + asio::spawn(ctx.get_executor(), + ASIO_MOVE_CAST(Function)(function), attributes); +} + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_SPAWN_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/src.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/src.hpp new file mode 100644 index 00000000..a1ee55d6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/src.hpp @@ -0,0 +1,82 @@ +// +// impl/src.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_SRC_HPP +#define ASIO_IMPL_SRC_HPP + +#define ASIO_SOURCE + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HEADER_ONLY) +# error Do not compile Asio library source with ASIO_HEADER_ONLY defined +#endif + +#include "asio/impl/error.ipp" +#include "asio/impl/error_code.ipp" +#include "asio/impl/execution_context.ipp" +#include "asio/impl/executor.ipp" +#include "asio/impl/handler_alloc_hook.ipp" +#include "asio/impl/io_context.ipp" +#include "asio/impl/serial_port_base.ipp" +#include "asio/impl/system_context.ipp" +#include "asio/impl/thread_pool.ipp" +#include "asio/detail/impl/buffer_sequence_adapter.ipp" +#include "asio/detail/impl/descriptor_ops.ipp" +#include "asio/detail/impl/dev_poll_reactor.ipp" +#include "asio/detail/impl/epoll_reactor.ipp" +#include "asio/detail/impl/eventfd_select_interrupter.ipp" +#include "asio/detail/impl/handler_tracking.ipp" +#include "asio/detail/impl/kqueue_reactor.ipp" +#include "asio/detail/impl/null_event.ipp" +#include "asio/detail/impl/pipe_select_interrupter.ipp" +#include "asio/detail/impl/posix_event.ipp" +#include "asio/detail/impl/posix_mutex.ipp" +#include "asio/detail/impl/posix_thread.ipp" +#include "asio/detail/impl/posix_tss_ptr.ipp" +#include "asio/detail/impl/reactive_descriptor_service.ipp" +#include "asio/detail/impl/reactive_serial_port_service.ipp" +#include "asio/detail/impl/reactive_socket_service_base.ipp" +#include "asio/detail/impl/resolver_service_base.ipp" +#include "asio/detail/impl/scheduler.ipp" +#include "asio/detail/impl/select_reactor.ipp" +#include "asio/detail/impl/service_registry.ipp" +#include "asio/detail/impl/signal_set_service.ipp" +#include "asio/detail/impl/socket_ops.ipp" +#include "asio/detail/impl/socket_select_interrupter.ipp" +#include "asio/detail/impl/strand_executor_service.ipp" +#include "asio/detail/impl/strand_service.ipp" +#include "asio/detail/impl/throw_error.ipp" +#include "asio/detail/impl/timer_queue_ptime.ipp" +#include "asio/detail/impl/timer_queue_set.ipp" +#include "asio/detail/impl/win_iocp_handle_service.ipp" +#include "asio/detail/impl/win_iocp_io_context.ipp" +#include "asio/detail/impl/win_iocp_serial_port_service.ipp" +#include "asio/detail/impl/win_iocp_socket_service_base.ipp" +#include "asio/detail/impl/win_event.ipp" +#include "asio/detail/impl/win_mutex.ipp" +#include "asio/detail/impl/win_object_handle_service.ipp" +#include "asio/detail/impl/win_static_mutex.ipp" +#include "asio/detail/impl/win_thread.ipp" +#include "asio/detail/impl/win_tss_ptr.ipp" +#include "asio/detail/impl/winrt_ssocket_service_base.ipp" +#include "asio/detail/impl/winrt_timer_scheduler.ipp" +#include "asio/detail/impl/winsock_init.ipp" +#include "asio/generic/detail/impl/endpoint.ipp" +#include "asio/ip/impl/address.ipp" +#include "asio/ip/impl/address_v4.ipp" +#include "asio/ip/impl/address_v6.ipp" +#include "asio/ip/impl/host_name.ipp" +#include "asio/ip/impl/network_v4.ipp" +#include "asio/ip/impl/network_v6.ipp" +#include "asio/ip/detail/impl/endpoint.ipp" +#include "asio/local/detail/impl/endpoint.ipp" + +#endif // ASIO_IMPL_SRC_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_context.hpp new file mode 100644 index 00000000..daffd555 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_context.hpp @@ -0,0 +1,34 @@ +// +// impl/system_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_SYSTEM_CONTEXT_HPP +#define ASIO_IMPL_SYSTEM_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/system_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +inline system_context::executor_type +system_context::get_executor() ASIO_NOEXCEPT +{ + return system_executor(); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_SYSTEM_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_executor.hpp new file mode 100644 index 00000000..d7dc2c80 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/system_executor.hpp @@ -0,0 +1,85 @@ +// +// impl/system_executor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_SYSTEM_EXECUTOR_HPP +#define ASIO_IMPL_SYSTEM_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/executor_op.hpp" +#include "asio/detail/global.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/system_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +inline system_context& system_executor::context() const ASIO_NOEXCEPT +{ + return detail::global(); +} + +template +void system_executor::dispatch( + ASIO_MOVE_ARG(Function) f, const Allocator&) const +{ + typename decay::type tmp(ASIO_MOVE_CAST(Function)(f)); + asio_handler_invoke_helpers::invoke(tmp, tmp); +} + +template +void system_executor::post( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + system_context& ctx = detail::global(); + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((ctx, *p.p, + "system_executor", &this->context(), 0, "post")); + + ctx.scheduler_.post_immediate_completion(p.p, false); + p.v = p.p = 0; +} + +template +void system_executor::defer( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + system_context& ctx = detail::global(); + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((ctx, *p.p, + "system_executor", &this->context(), 0, "defer")); + + ctx.scheduler_.post_immediate_completion(p.p, true); + p.v = p.p = 0; +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_SYSTEM_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/thread_pool.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/thread_pool.hpp new file mode 100644 index 00000000..033cb76c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/thread_pool.hpp @@ -0,0 +1,127 @@ +// +// impl/thread_pool.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_THREAD_POOL_HPP +#define ASIO_IMPL_THREAD_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/executor_op.hpp" +#include "asio/detail/fenced_block.hpp" +#include "asio/detail/recycling_allocator.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +inline thread_pool::executor_type +thread_pool::get_executor() ASIO_NOEXCEPT +{ + return executor_type(*this); +} + +inline thread_pool& +thread_pool::executor_type::context() const ASIO_NOEXCEPT +{ + return pool_; +} + +inline void +thread_pool::executor_type::on_work_started() const ASIO_NOEXCEPT +{ + pool_.scheduler_.work_started(); +} + +inline void thread_pool::executor_type::on_work_finished() +const ASIO_NOEXCEPT +{ + pool_.scheduler_.work_finished(); +} + +template +void thread_pool::executor_type::dispatch( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Invoke immediately if we are already inside the thread pool. + if (pool_.scheduler_.can_dispatch()) + { + // Make a local, non-const copy of the function. + function_type tmp(ASIO_MOVE_CAST(Function)(f)); + + detail::fenced_block b(detail::fenced_block::full); + asio_handler_invoke_helpers::invoke(tmp, tmp); + return; + } + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((pool_, *p.p, + "thread_pool", &this->context(), 0, "dispatch")); + + pool_.scheduler_.post_immediate_completion(p.p, false); + p.v = p.p = 0; +} + +template +void thread_pool::executor_type::post( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((pool_, *p.p, + "thread_pool", &this->context(), 0, "post")); + + pool_.scheduler_.post_immediate_completion(p.p, false); + p.v = p.p = 0; +} + +template +void thread_pool::executor_type::defer( + ASIO_MOVE_ARG(Function) f, const Allocator& a) const +{ + typedef typename decay::type function_type; + + // Allocate and construct an operation to wrap the function. + typedef detail::executor_op op; + typename op::ptr p = { detail::addressof(a), op::ptr::allocate(a), 0 }; + p.p = new (p.v) op(ASIO_MOVE_CAST(Function)(f), a); + + ASIO_HANDLER_CREATION((pool_, *p.p, + "thread_pool", &this->context(), 0, "defer")); + + pool_.scheduler_.post_immediate_completion(p.p, true); + p.v = p.p = 0; +} + +inline bool +thread_pool::executor_type::running_in_this_thread() const ASIO_NOEXCEPT +{ + return pool_.scheduler_.can_dispatch(); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_THREAD_POOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_awaitable.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_awaitable.hpp new file mode 100644 index 00000000..c607d10c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_awaitable.hpp @@ -0,0 +1,276 @@ +// +// impl/use_awaitable.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_USE_AWAITABLE_HPP +#define ASIO_IMPL_USE_AWAITABLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class awaitable_handler_base + : public awaitable_thread +{ +public: + typedef void result_type; + typedef awaitable awaitable_type; + + // Construct from the entry point of a new thread of execution. + awaitable_handler_base(awaitable a, const Executor& ex) + : awaitable_thread(std::move(a), ex) + { + } + + // Transfer ownership from another awaitable_thread. + explicit awaitable_handler_base(awaitable_thread* h) + : awaitable_thread(std::move(*h)) + { + } + +protected: + awaitable_frame* frame() noexcept + { + return static_cast*>(this->top_of_stack_); + } +}; + +template +class awaitable_handler; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + void operator()() + { + this->frame()->attach_thread(this); + this->frame()->return_void(); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + void operator()(const asio::error_code& ec) + { + this->frame()->attach_thread(this); + if (ec) + this->frame()->set_error(ec); + else + this->frame()->return_void(); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + void operator()(std::exception_ptr ex) + { + this->frame()->attach_thread(this); + if (ex) + this->frame()->set_except(ex); + else + this->frame()->return_void(); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + template + void operator()(Arg&& arg) + { + this->frame()->attach_thread(this); + this->frame()->return_value(std::forward(arg)); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + template + void operator()(const asio::error_code& ec, Arg&& arg) + { + this->frame()->attach_thread(this); + if (ec) + this->frame()->set_error(ec); + else + this->frame()->return_value(std::forward(arg)); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base +{ +public: + using awaitable_handler_base::awaitable_handler_base; + + template + void operator()(std::exception_ptr ex, Arg&& arg) + { + this->frame()->attach_thread(this); + if (ex) + this->frame()->set_except(ex); + else + this->frame()->return_value(std::forward(arg)); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base> +{ +public: + using awaitable_handler_base>::awaitable_handler_base; + + template + void operator()(Args&&... args) + { + this->frame()->attach_thread(this); + this->frame()->return_values(std::forward(args)...); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base> +{ +public: + using awaitable_handler_base>::awaitable_handler_base; + + template + void operator()(const asio::error_code& ec, Args&&... args) + { + this->frame()->attach_thread(this); + if (ec) + this->frame()->set_error(ec); + else + this->frame()->return_values(std::forward(args)...); + this->frame()->pop_frame(); + this->pump(); + } +}; + +template +class awaitable_handler + : public awaitable_handler_base> +{ +public: + using awaitable_handler_base>::awaitable_handler_base; + + template + void operator()(std::exception_ptr ex, Args&&... args) + { + this->frame()->attach_thread(this); + if (ex) + this->frame()->set_except(ex); + else + this->frame()->return_values(std::forward(args)...); + this->frame()->pop_frame(); + this->pump(); + } +}; + +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +class async_result, R(Args...)> +{ +public: + typedef typename detail::awaitable_handler< + Executor, typename decay::type...> handler_type; + typedef typename handler_type::awaitable_type return_type; + +#if defined(_MSC_VER) + template + static T dummy_return() + { + return std::move(*static_cast(nullptr)); + } + + template <> + static void dummy_return() + { + } +#endif // defined(_MSC_VER) + + template + static return_type initiate(Initiation initiation, + use_awaitable_t, InitArgs... args) + { + co_await [&](auto* frame) + { + handler_type handler(frame->detach_thread()); + std::move(initiation)(std::move(handler), std::move(args)...); + return static_cast(nullptr); + }; + + for (;;) {} // Never reached. +#if defined(_MSC_VER) + co_return dummy_return(); +#endif // defined(_MSC_VER) + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_USE_AWAITABLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_future.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_future.hpp new file mode 100644 index 00000000..64ed4a51 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/use_future.hpp @@ -0,0 +1,887 @@ +// +// impl/use_future.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_USE_FUTURE_HPP +#define ASIO_IMPL_USE_FUTURE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/detail/memory.hpp" +#include "asio/error_code.hpp" +#include "asio/packaged_task.hpp" +#include "asio/system_error.hpp" +#include "asio/system_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +inline void promise_invoke_and_set(std::promise& p, + F& f, ASIO_MOVE_ARG(Args)... args) +{ +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + p.set_value(f(ASIO_MOVE_CAST(Args)(args)...)); + } +#if !defined(ASIO_NO_EXCEPTIONS) + catch (...) + { + p.set_exception(std::current_exception()); + } +#endif // !defined(ASIO_NO_EXCEPTIONS) +} + +template +inline void promise_invoke_and_set(std::promise& p, + F& f, ASIO_MOVE_ARG(Args)... args) +{ +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + f(ASIO_MOVE_CAST(Args)(args)...); + p.set_value(); + } +#if !defined(ASIO_NO_EXCEPTIONS) + catch (...) + { + p.set_exception(std::current_exception()); + } +#endif // !defined(ASIO_NO_EXCEPTIONS) +} + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +inline void promise_invoke_and_set(std::promise& p, F& f) +{ +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + p.set_value(f()); + } +#if !defined(ASIO_NO_EXCEPTIONS) + catch (...) + { + p.set_exception(std::current_exception()); + } +#endif // !defined(ASIO_NO_EXCEPTIONS) +} + +template +inline void promise_invoke_and_set(std::promise& p, F& f) +{ +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + f(); + p.set_value(); +#if !defined(ASIO_NO_EXCEPTIONS) + } + catch (...) + { + p.set_exception(std::current_exception()); + } +#endif // !defined(ASIO_NO_EXCEPTIONS) +} + +#if defined(ASIO_NO_EXCEPTIONS) + +#define ASIO_PRIVATE_PROMISE_INVOKE_DEF(n) \ + template \ + inline void promise_invoke_and_set(std::promise& p, \ + F& f, ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + p.set_value(f(ASIO_VARIADIC_MOVE_ARGS(n))); \ + } \ + \ + template \ + inline void promise_invoke_and_set(std::promise& p, \ + F& f, ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + f(ASIO_VARIADIC_MOVE_ARGS(n)); \ + p.set_value(); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_PROMISE_INVOKE_DEF) +#undef ASIO_PRIVATE_PROMISE_INVOKE_DEF + +#else // defined(ASIO_NO_EXCEPTIONS) + +#define ASIO_PRIVATE_PROMISE_INVOKE_DEF(n) \ + template \ + inline void promise_invoke_and_set(std::promise& p, \ + F& f, ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + try \ + { \ + p.set_value(f(ASIO_VARIADIC_MOVE_ARGS(n))); \ + } \ + catch (...) \ + { \ + p.set_exception(std::current_exception()); \ + } \ + } \ + \ + template \ + inline void promise_invoke_and_set(std::promise& p, \ + F& f, ASIO_VARIADIC_MOVE_PARAMS(n)) \ + { \ + try \ + { \ + f(ASIO_VARIADIC_MOVE_ARGS(n)); \ + p.set_value(); \ + } \ + catch (...) \ + { \ + p.set_exception(std::current_exception()); \ + } \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_PROMISE_INVOKE_DEF) +#undef ASIO_PRIVATE_PROMISE_INVOKE_DEF + +#endif // defined(ASIO_NO_EXCEPTIONS) + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +// A function object adapter to invoke a nullary function object and capture +// any exception thrown into a promise. +template +class promise_invoker +{ +public: + promise_invoker(const shared_ptr >& p, + ASIO_MOVE_ARG(F) f) + : p_(p), f_(ASIO_MOVE_CAST(F)(f)) + { + } + + void operator()() + { +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + f_(); + } +#if !defined(ASIO_NO_EXCEPTIONS) + catch (...) + { + p_->set_exception(std::current_exception()); + } +#endif // !defined(ASIO_NO_EXCEPTIONS) + } + +private: + shared_ptr > p_; + typename decay::type f_; +}; + +// An executor that adapts the system_executor to capture any exeption thrown +// by a submitted function object and save it into a promise. +template +class promise_executor +{ +public: + explicit promise_executor(const shared_ptr >& p) + : p_(p) + { + } + + execution_context& context() const ASIO_NOEXCEPT + { + return system_executor().context(); + } + + void on_work_started() const ASIO_NOEXCEPT {} + void on_work_finished() const ASIO_NOEXCEPT {} + + template + void dispatch(ASIO_MOVE_ARG(F) f, const A&) const + { + promise_invoker(p_, ASIO_MOVE_CAST(F)(f))(); + } + + template + void post(ASIO_MOVE_ARG(F) f, const A& a) const + { + system_executor().post( + promise_invoker(p_, ASIO_MOVE_CAST(F)(f)), a); + } + + template + void defer(ASIO_MOVE_ARG(F) f, const A& a) const + { + system_executor().defer( + promise_invoker(p_, ASIO_MOVE_CAST(F)(f)), a); + } + + friend bool operator==(const promise_executor& a, + const promise_executor& b) ASIO_NOEXCEPT + { + return a.p_ == b.p_; + } + + friend bool operator!=(const promise_executor& a, + const promise_executor& b) ASIO_NOEXCEPT + { + return a.p_ != b.p_; + } + +private: + shared_ptr > p_; +}; + +// The base class for all completion handlers that create promises. +template +class promise_creator +{ +public: + typedef promise_executor executor_type; + + executor_type get_executor() const ASIO_NOEXCEPT + { + return executor_type(p_); + } + + typedef std::future future_type; + + future_type get_future() + { + return p_->get_future(); + } + +protected: + template + void create_promise(const Allocator& a) + { + ASIO_REBIND_ALLOC(Allocator, char) b(a); + p_ = std::allocate_shared>(b, std::allocator_arg, b); + } + + shared_ptr > p_; +}; + +// For completion signature void(). +class promise_handler_0 + : public promise_creator +{ +public: + void operator()() + { + this->p_->set_value(); + } +}; + +// For completion signature void(error_code). +class promise_handler_ec_0 + : public promise_creator +{ +public: + void operator()(const asio::error_code& ec) + { + if (ec) + { + this->p_->set_exception( + std::make_exception_ptr( + asio::system_error(ec))); + } + else + { + this->p_->set_value(); + } + } +}; + +// For completion signature void(exception_ptr). +class promise_handler_ex_0 + : public promise_creator +{ +public: + void operator()(const std::exception_ptr& ex) + { + if (ex) + { + this->p_->set_exception(ex); + } + else + { + this->p_->set_value(); + } + } +}; + +// For completion signature void(T). +template +class promise_handler_1 + : public promise_creator +{ +public: + template + void operator()(ASIO_MOVE_ARG(Arg) arg) + { + this->p_->set_value(ASIO_MOVE_CAST(Arg)(arg)); + } +}; + +// For completion signature void(error_code, T). +template +class promise_handler_ec_1 + : public promise_creator +{ +public: + template + void operator()(const asio::error_code& ec, + ASIO_MOVE_ARG(Arg) arg) + { + if (ec) + { + this->p_->set_exception( + std::make_exception_ptr( + asio::system_error(ec))); + } + else + this->p_->set_value(ASIO_MOVE_CAST(Arg)(arg)); + } +}; + +// For completion signature void(exception_ptr, T). +template +class promise_handler_ex_1 + : public promise_creator +{ +public: + template + void operator()(const std::exception_ptr& ex, + ASIO_MOVE_ARG(Arg) arg) + { + if (ex) + this->p_->set_exception(ex); + else + this->p_->set_value(ASIO_MOVE_CAST(Arg)(arg)); + } +}; + +// For completion signature void(T1, ..., Tn); +template +class promise_handler_n + : public promise_creator +{ +public: +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(ASIO_MOVE_ARG(Args)... args) + { + this->p_->set_value( + std::forward_as_tuple( + ASIO_MOVE_CAST(Args)(args)...)); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_CALL_OP_DEF(n) \ + template \ + void operator()(ASIO_VARIADIC_MOVE_PARAMS(n)) \ + {\ + this->p_->set_value( \ + std::forward_as_tuple( \ + ASIO_VARIADIC_MOVE_ARGS(n))); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CALL_OP_DEF) +#undef ASIO_PRIVATE_CALL_OP_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +}; + +// For completion signature void(error_code, T1, ..., Tn); +template +class promise_handler_ec_n + : public promise_creator +{ +public: +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(const asio::error_code& ec, + ASIO_MOVE_ARG(Args)... args) + { + if (ec) + { + this->p_->set_exception( + std::make_exception_ptr( + asio::system_error(ec))); + } + else + { + this->p_->set_value( + std::forward_as_tuple( + ASIO_MOVE_CAST(Args)(args)...)); + } + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_CALL_OP_DEF(n) \ + template \ + void operator()(const asio::error_code& ec, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + {\ + if (ec) \ + { \ + this->p_->set_exception( \ + std::make_exception_ptr( \ + asio::system_error(ec))); \ + } \ + else \ + { \ + this->p_->set_value( \ + std::forward_as_tuple( \ + ASIO_VARIADIC_MOVE_ARGS(n))); \ + } \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CALL_OP_DEF) +#undef ASIO_PRIVATE_CALL_OP_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +}; + +// For completion signature void(exception_ptr, T1, ..., Tn); +template +class promise_handler_ex_n + : public promise_creator +{ +public: +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(const std::exception_ptr& ex, + ASIO_MOVE_ARG(Args)... args) + { + if (ex) + this->p_->set_exception(ex); + else + { + this->p_->set_value( + std::forward_as_tuple( + ASIO_MOVE_CAST(Args)(args)...)); + } + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_CALL_OP_DEF(n) \ + template \ + void operator()(const std::exception_ptr& ex, \ + ASIO_VARIADIC_MOVE_PARAMS(n)) \ + {\ + if (ex) \ + this->p_->set_exception(ex); \ + else \ + { \ + this->p_->set_value( \ + std::forward_as_tuple( \ + ASIO_VARIADIC_MOVE_ARGS(n))); \ + } \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CALL_OP_DEF) +#undef ASIO_PRIVATE_CALL_OP_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) +}; + +// Helper template to choose the appropriate concrete promise handler +// implementation based on the supplied completion signature. +template class promise_handler_selector; + +template <> +class promise_handler_selector + : public promise_handler_0 {}; + +template <> +class promise_handler_selector + : public promise_handler_ec_0 {}; + +template <> +class promise_handler_selector + : public promise_handler_ex_0 {}; + +template +class promise_handler_selector + : public promise_handler_1 {}; + +template +class promise_handler_selector + : public promise_handler_ec_1 {}; + +template +class promise_handler_selector + : public promise_handler_ex_1 {}; + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +class promise_handler_selector + : public promise_handler_n > {}; + +template +class promise_handler_selector + : public promise_handler_ec_n > {}; + +template +class promise_handler_selector + : public promise_handler_ex_n > {}; + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#define ASIO_PRIVATE_PROMISE_SELECTOR_DEF(n) \ + template \ + class promise_handler_selector< \ + void(Arg, ASIO_VARIADIC_TARGS(n))> \ + : public promise_handler_n< \ + std::tuple > {}; \ + \ + template \ + class promise_handler_selector< \ + void(asio::error_code, Arg, ASIO_VARIADIC_TARGS(n))> \ + : public promise_handler_ec_n< \ + std::tuple > {}; \ + \ + template \ + class promise_handler_selector< \ + void(std::exception_ptr, Arg, ASIO_VARIADIC_TARGS(n))> \ + : public promise_handler_ex_n< \ + std::tuple > {}; \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_PROMISE_SELECTOR_DEF) +#undef ASIO_PRIVATE_PROMISE_SELECTOR_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +// Completion handlers produced from the use_future completion token, when not +// using use_future::operator(). +template +class promise_handler + : public promise_handler_selector +{ +public: + typedef Allocator allocator_type; + typedef void result_type; + + promise_handler(use_future_t u) + : allocator_(u.get_allocator()) + { + this->create_promise(allocator_); + } + + allocator_type get_allocator() const ASIO_NOEXCEPT + { + return allocator_; + } + +private: + Allocator allocator_; +}; + +template +inline void asio_handler_invoke(Function& f, + promise_handler* h) +{ + typename promise_handler::executor_type + ex(h->get_executor()); + ex.dispatch(ASIO_MOVE_CAST(Function)(f), std::allocator()); +} + +template +inline void asio_handler_invoke(const Function& f, + promise_handler* h) +{ + typename promise_handler::executor_type + ex(h->get_executor()); + ex.dispatch(f, std::allocator()); +} + +// Helper base class for async_result specialisation. +template +class promise_async_result +{ +public: + typedef promise_handler completion_handler_type; + typedef typename completion_handler_type::future_type return_type; + + explicit promise_async_result(completion_handler_type& h) + : future_(h.get_future()) + { + } + + return_type get() + { + return ASIO_MOVE_CAST(return_type)(future_); + } + +private: + return_type future_; +}; + +// Return value from use_future::operator(). +template +class packaged_token +{ +public: + packaged_token(Function f, const Allocator& a) + : function_(ASIO_MOVE_CAST(Function)(f)), + allocator_(a) + { + } + +//private: + Function function_; + Allocator allocator_; +}; + +// Completion handlers produced from the use_future completion token, when +// using use_future::operator(). +template +class packaged_handler + : public promise_creator +{ +public: + typedef Allocator allocator_type; + typedef void result_type; + + packaged_handler(packaged_token t) + : function_(ASIO_MOVE_CAST(Function)(t.function_)), + allocator_(t.allocator_) + { + this->create_promise(allocator_); + } + + allocator_type get_allocator() const ASIO_NOEXCEPT + { + return allocator_; + } + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + + template + void operator()(ASIO_MOVE_ARG(Args)... args) + { + (promise_invoke_and_set)(*this->p_, + function_, ASIO_MOVE_CAST(Args)(args)...); + } + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + + void operator()() + { + (promise_invoke_and_set)(*this->p_, function_); + } + +#define ASIO_PRIVATE_CALL_OP_DEF(n) \ + template \ + void operator()(ASIO_VARIADIC_MOVE_PARAMS(n)) \ + {\ + (promise_invoke_and_set)(*this->p_, \ + function_, ASIO_VARIADIC_MOVE_ARGS(n)); \ + } \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_CALL_OP_DEF) +#undef ASIO_PRIVATE_CALL_OP_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +private: + Function function_; + Allocator allocator_; +}; + +template +inline void asio_handler_invoke(Function& f, + packaged_handler* h) +{ + typename packaged_handler::executor_type + ex(h->get_executor()); + ex.dispatch(ASIO_MOVE_CAST(Function)(f), std::allocator()); +} + +template +inline void asio_handler_invoke(const Function& f, + packaged_handler* h) +{ + typename packaged_handler::executor_type + ex(h->get_executor()); + ex.dispatch(f, std::allocator()); +} + +// Helper base class for async_result specialisation. +template +class packaged_async_result +{ +public: + typedef packaged_handler completion_handler_type; + typedef typename completion_handler_type::future_type return_type; + + explicit packaged_async_result(completion_handler_type& h) + : future_(h.get_future()) + { + } + + return_type get() + { + return ASIO_MOVE_CAST(return_type)(future_); + } + +private: + return_type future_; +}; + +} // namespace detail + +template template +inline detail::packaged_token::type, Allocator> +use_future_t::operator()(ASIO_MOVE_ARG(Function) f) const +{ + return detail::packaged_token::type, Allocator>( + ASIO_MOVE_CAST(Function)(f), allocator_); +} + +#if !defined(GENERATING_DOCUMENTATION) + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +class async_result, Result(Args...)> + : public detail::promise_async_result< + void(typename decay::type...), Allocator> +{ +public: + explicit async_result( + typename detail::promise_async_result::type...), + Allocator>::completion_handler_type& h) + : detail::promise_async_result< + void(typename decay::type...), Allocator>(h) + { + } +}; + +template +class async_result, Result(Args...)> + : public detail::packaged_async_result::type> +{ +public: + explicit async_result( + typename detail::packaged_async_result::type>::completion_handler_type& h) + : detail::packaged_async_result::type>(h) + { + } +}; + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +template +class async_result, Result()> + : public detail::promise_async_result +{ +public: + explicit async_result( + typename detail::promise_async_result< + void(), Allocator>::completion_handler_type& h) + : detail::promise_async_result(h) + { + } +}; + +template +class async_result, Result()> + : public detail::packaged_async_result::type> +{ +public: + explicit async_result( + typename detail::packaged_async_result::type>::completion_handler_type& h) + : detail::packaged_async_result::type>(h) + { + } +}; + +#define ASIO_PRIVATE_ASYNC_RESULT_DEF(n) \ + template \ + class async_result, \ + Result(ASIO_VARIADIC_TARGS(n))> \ + : public detail::promise_async_result< \ + void(ASIO_VARIADIC_DECAY(n)), Allocator> \ + { \ + public: \ + explicit async_result( \ + typename detail::promise_async_result< \ + void(ASIO_VARIADIC_DECAY(n)), \ + Allocator>::completion_handler_type& h) \ + : detail::promise_async_result< \ + void(ASIO_VARIADIC_DECAY(n)), Allocator>(h) \ + { \ + } \ + }; \ + \ + template \ + class async_result, \ + Result(ASIO_VARIADIC_TARGS(n))> \ + : public detail::packaged_async_result::type> \ + { \ + public: \ + explicit async_result( \ + typename detail::packaged_async_result::type \ + >::completion_handler_type& h) \ + : detail::packaged_async_result::type>(h) \ + { \ + } \ + }; \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_ASYNC_RESULT_DEF) +#undef ASIO_PRIVATE_ASYNC_RESULT_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + +#endif // !defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_USE_FUTURE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write.hpp new file mode 100644 index 00000000..aae18add --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write.hpp @@ -0,0 +1,1043 @@ +// +// impl/write.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_WRITE_HPP +#define ASIO_IMPL_WRITE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/base_from_completion_cond.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/consuming_buffers.hpp" +#include "asio/detail/dependent_type.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + std::size_t write_buffer_sequence(SyncWriteStream& s, + const ConstBufferSequence& buffers, const ConstBufferIterator&, + CompletionCondition completion_condition, asio::error_code& ec) + { + ec = asio::error_code(); + asio::detail::consuming_buffers tmp(buffers); + while (!tmp.empty()) + { + if (std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, tmp.total_consumed()))) + tmp.consume(s.write_some(tmp.prepare(max_size), ec)); + else + break; + } + return tmp.total_consumed();; + } +} // namespace detail + +template +inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + return detail::write_buffer_sequence(s, buffers, + asio::buffer_sequence_begin(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, buffers, transfer_all(), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + asio::error_code& ec, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + return write(s, buffers, transfer_all(), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + typename decay::type b( + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers)); + + std::size_t bytes_transferred = write(s, b.data(), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + b.consume(bytes_transferred); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + transfer_all(), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return write(s, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline std::size_t write(SyncWriteStream& s, + asio::basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec) +{ + return write(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, + asio::basic_streambuf& b) +{ + return write(s, basic_streambuf_ref(b)); +} + +template +inline std::size_t write(SyncWriteStream& s, + asio::basic_streambuf& b, + asio::error_code& ec) +{ + return write(s, basic_streambuf_ref(b), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, + asio::basic_streambuf& b, + CompletionCondition completion_condition) +{ + return write(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +template +std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + std::size_t bytes_transferred = write(s, buffers.data(0, buffers.size()), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + buffers.consume(bytes_transferred); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + transfer_all(), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +template +inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return write(s, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + transfer_all(), ec); +} + +template +inline std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + asio::error_code ec; + std::size_t bytes_transferred = write(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "write"); + return bytes_transferred; +} + +namespace detail +{ + template + class write_op + : detail::base_from_completion_cond + { + public: + write_op(AsyncWriteStream& stream, const ConstBufferSequence& buffers, + CompletionCondition& completion_condition, WriteHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + stream_(stream), + buffers_(buffers), + start_(0), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + write_op(const write_op& other) + : detail::base_from_completion_cond(other), + stream_(other.stream_), + buffers_(other.buffers_), + start_(other.start_), + handler_(other.handler_) + { + } + + write_op(write_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(buffers_type)(other.buffers_)), + start_(other.start_), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + do + { + stream_.async_write_some(buffers_.prepare(max_size), + ASIO_MOVE_CAST(write_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + if ((!ec && bytes_transferred == 0) || buffers_.empty()) + break; + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + } while (max_size > 0); + + handler_(ec, buffers_.total_consumed()); + } + } + + //private: + typedef asio::detail::consuming_buffers buffers_type; + + AsyncWriteStream& stream_; + buffers_type buffers_; + int start_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + write_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void start_write_buffer_sequence_op(AsyncWriteStream& stream, + const ConstBufferSequence& buffers, const ConstBufferIterator&, + CompletionCondition& completion_condition, WriteHandler& handler) + { + detail::write_op( + stream, buffers, completion_condition, handler)( + asio::error_code(), 0, 1); + } + + template + class initiate_async_write_buffer_sequence + { + public: + typedef typename AsyncWriteStream::executor_type executor_type; + + explicit initiate_async_write_buffer_sequence(AsyncWriteStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + start_write_buffer_sequence_op(stream_, buffers, + asio::buffer_sequence_begin(buffers), + completion_cond2.value, handler2.value); + } + + private: + AsyncWriteStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + return async_initiate( + detail::initiate_async_write_buffer_sequence(s), + handler, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_const_buffer_sequence::value + >::type*) +{ + return async_initiate( + detail::initiate_async_write_buffer_sequence(s), + handler, buffers, transfer_all()); +} + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class write_dynbuf_v1_op + { + public: + template + write_dynbuf_v1_op(AsyncWriteStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + CompletionCondition& completion_condition, WriteHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + completion_condition_( + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + write_dynbuf_v1_op(const write_dynbuf_v1_op& other) + : stream_(other.stream_), + buffers_(other.buffers_), + completion_condition_(other.completion_condition_), + handler_(other.handler_) + { + } + + write_dynbuf_v1_op(write_dynbuf_v1_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v1)(other.buffers_)), + completion_condition_( + ASIO_MOVE_CAST(CompletionCondition)( + other.completion_condition_)), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + switch (start) + { + case 1: + async_write(stream_, buffers_.data(), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition_), + ASIO_MOVE_CAST(write_dynbuf_v1_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + handler_(ec, static_cast(bytes_transferred)); + } + } + + //private: + AsyncWriteStream& stream_; + DynamicBuffer_v1 buffers_; + CompletionCondition completion_condition_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_dynbuf_v1_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + write_dynbuf_v1_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_dynbuf_v1_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_dynbuf_v1_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_dynbuf_v1_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_write_dynbuf_v1 + { + public: + typedef typename AsyncWriteStream::executor_type executor_type; + + explicit initiate_async_write_dynbuf_v1(AsyncWriteStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + write_dynbuf_v1_op::type, + CompletionCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + completion_cond2.value, handler2.value)( + asio::error_code(), 0, 1); + } + + private: + AsyncWriteStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_dynbuf_v1_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_dynbuf_v1_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_dynbuf_v1_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_dynbuf_v1_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_write(s, + ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + transfer_all(), ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type*) +{ + return async_initiate( + detail::initiate_async_write_dynbuf_v1(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v1)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + asio::basic_streambuf& b, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_write(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + asio::basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_write(s, basic_streambuf_ref(b), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), + ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +namespace detail +{ + template + class write_dynbuf_v2_op + { + public: + template + write_dynbuf_v2_op(AsyncWriteStream& stream, + ASIO_MOVE_ARG(BufferSequence) buffers, + CompletionCondition& completion_condition, WriteHandler& handler) + : stream_(stream), + buffers_(ASIO_MOVE_CAST(BufferSequence)(buffers)), + completion_condition_( + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + write_dynbuf_v2_op(const write_dynbuf_v2_op& other) + : stream_(other.stream_), + buffers_(other.buffers_), + completion_condition_(other.completion_condition_), + handler_(other.handler_) + { + } + + write_dynbuf_v2_op(write_dynbuf_v2_op&& other) + : stream_(other.stream_), + buffers_(ASIO_MOVE_CAST(DynamicBuffer_v2)(other.buffers_)), + completion_condition_( + ASIO_MOVE_CAST(CompletionCondition)( + other.completion_condition_)), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + switch (start) + { + case 1: + async_write(stream_, buffers_.data(0, buffers_.size()), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition_), + ASIO_MOVE_CAST(write_dynbuf_v2_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + handler_(ec, static_cast(bytes_transferred)); + } + } + + //private: + AsyncWriteStream& stream_; + DynamicBuffer_v2 buffers_; + CompletionCondition completion_condition_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_dynbuf_v2_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + write_dynbuf_v2_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_dynbuf_v2_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_dynbuf_v2_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_dynbuf_v2_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_write_dynbuf_v2 + { + public: + typedef typename AsyncWriteStream::executor_type executor_type; + + explicit initiate_async_write_dynbuf_v2(AsyncWriteStream& stream) + : stream_(stream) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return stream_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + ASIO_MOVE_ARG(DynamicBuffer_v2) buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + write_dynbuf_v2_op::type, + CompletionCondition, typename decay::type>( + stream_, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + completion_cond2.value, handler2.value)( + asio::error_code(), 0, 1); + } + + private: + AsyncWriteStream& stream_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_dynbuf_v2_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_dynbuf_v2_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_dynbuf_v2_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_dynbuf_v2_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_write(s, + ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + transfer_all(), ASIO_MOVE_CAST(WriteHandler)(handler)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler, + typename enable_if< + is_dynamic_buffer_v2::value + >::type*) +{ + return async_initiate( + detail::initiate_async_write_dynbuf_v2(s), + handler, ASIO_MOVE_CAST(DynamicBuffer_v2)(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_WRITE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write_at.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write_at.hpp new file mode 100644 index 00000000..4fa9fce0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/impl/write_at.hpp @@ -0,0 +1,624 @@ +// +// impl/write_at.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IMPL_WRITE_AT_HPP +#define ASIO_IMPL_WRITE_AT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/associated_allocator.hpp" +#include "asio/associated_executor.hpp" +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/detail/array_fwd.hpp" +#include "asio/detail/base_from_completion_cond.hpp" +#include "asio/detail/bind_handler.hpp" +#include "asio/detail/consuming_buffers.hpp" +#include "asio/detail/dependent_type.hpp" +#include "asio/detail/handler_alloc_helpers.hpp" +#include "asio/detail/handler_cont_helpers.hpp" +#include "asio/detail/handler_invoke_helpers.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + template + std::size_t write_at_buffer_sequence(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + const ConstBufferIterator&, CompletionCondition completion_condition, + asio::error_code& ec) + { + ec = asio::error_code(); + asio::detail::consuming_buffers tmp(buffers); + while (!tmp.empty()) + { + if (std::size_t max_size = detail::adapt_completion_condition_result( + completion_condition(ec, tmp.total_consumed()))) + { + tmp.consume(d.write_some_at(offset + tmp.total_consumed(), + tmp.prepare(max_size), ec)); + } + else + break; + } + return tmp.total_consumed();; + } +} // namespace detail + +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec) +{ + return detail::write_at_buffer_sequence(d, offset, buffers, + asio::buffer_sequence_begin(buffers), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers) +{ + asio::error_code ec; + std::size_t bytes_transferred = write_at( + d, offset, buffers, transfer_all(), ec); + asio::detail::throw_error(ec, "write_at"); + return bytes_transferred; +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + asio::error_code& ec) +{ + return write_at(d, offset, buffers, transfer_all(), ec); +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition) +{ + asio::error_code ec; + std::size_t bytes_transferred = write_at(d, offset, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "write_at"); + return bytes_transferred; +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec) +{ + std::size_t bytes_transferred = write_at(d, offset, b.data(), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + b.consume(bytes_transferred); + return bytes_transferred; +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b) +{ + asio::error_code ec; + std::size_t bytes_transferred = write_at(d, offset, b, transfer_all(), ec); + asio::detail::throw_error(ec, "write_at"); + return bytes_transferred; +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b, + asio::error_code& ec) +{ + return write_at(d, offset, b, transfer_all(), ec); +} + +template +inline std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition) +{ + asio::error_code ec; + std::size_t bytes_transferred = write_at(d, offset, b, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), ec); + asio::detail::throw_error(ec, "write_at"); + return bytes_transferred; +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +namespace detail +{ + template + class write_at_op + : detail::base_from_completion_cond + { + public: + write_at_op(AsyncRandomAccessWriteDevice& device, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition& completion_condition, WriteHandler& handler) + : detail::base_from_completion_cond< + CompletionCondition>(completion_condition), + device_(device), + offset_(offset), + buffers_(buffers), + start_(0), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + write_at_op(const write_at_op& other) + : detail::base_from_completion_cond(other), + device_(other.device_), + offset_(other.offset_), + buffers_(other.buffers_), + start_(other.start_), + handler_(other.handler_) + { + } + + write_at_op(write_at_op&& other) + : detail::base_from_completion_cond( + ASIO_MOVE_CAST(detail::base_from_completion_cond< + CompletionCondition>)(other)), + device_(other.device_), + offset_(other.offset_), + buffers_(ASIO_MOVE_CAST(buffers_type)(other.buffers_)), + start_(other.start_), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + std::size_t bytes_transferred, int start = 0) + { + std::size_t max_size; + switch (start_ = start) + { + case 1: + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + do + { + device_.async_write_some_at( + offset_ + buffers_.total_consumed(), buffers_.prepare(max_size), + ASIO_MOVE_CAST(write_at_op)(*this)); + return; default: + buffers_.consume(bytes_transferred); + if ((!ec && bytes_transferred == 0) || buffers_.empty()) + break; + max_size = this->check_for_completion(ec, buffers_.total_consumed()); + } while (max_size > 0); + + handler_(ec, buffers_.total_consumed()); + } + } + + //private: + typedef asio::detail::consuming_buffers buffers_type; + + AsyncRandomAccessWriteDevice& device_; + uint64_t offset_; + buffers_type buffers_; + int start_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_at_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + write_at_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_at_op* this_handler) + { + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_at_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_at_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void start_write_at_buffer_sequence_op(AsyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + const ConstBufferIterator&, CompletionCondition& completion_condition, + WriteHandler& handler) + { + detail::write_at_op( + d, offset, buffers, completion_condition, handler)( + asio::error_code(), 0, 1); + } + + template + class initiate_async_write_at_buffer_sequence + { + public: + typedef typename AsyncRandomAccessWriteDevice::executor_type executor_type; + + explicit initiate_async_write_at_buffer_sequence( + AsyncRandomAccessWriteDevice& device) + : device_(device) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return device_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + uint64_t offset, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(CompletionCondition) completion_cond) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + non_const_lvalue completion_cond2(completion_cond); + start_write_at_buffer_sequence_op(device_, offset, buffers, + asio::buffer_sequence_begin(buffers), + completion_cond2.value, handler2.value); + } + + private: + AsyncRandomAccessWriteDevice& device_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_at_op, + Allocator> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_at_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_at_op, + Executor> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_at_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_write_at_buffer_sequence< + AsyncRandomAccessWriteDevice>(d), + handler, offset, buffers, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_write_at_buffer_sequence< + AsyncRandomAccessWriteDevice>(d), + handler, offset, buffers, transfer_all()); +} + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +namespace detail +{ + template + class write_at_streambuf_op + { + public: + write_at_streambuf_op( + asio::basic_streambuf& streambuf, + WriteHandler& handler) + : streambuf_(streambuf), + handler_(ASIO_MOVE_CAST(WriteHandler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + write_at_streambuf_op(const write_at_streambuf_op& other) + : streambuf_(other.streambuf_), + handler_(other.handler_) + { + } + + write_at_streambuf_op(write_at_streambuf_op&& other) + : streambuf_(other.streambuf_), + handler_(ASIO_MOVE_CAST(WriteHandler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(const asio::error_code& ec, + const std::size_t bytes_transferred) + { + streambuf_.consume(bytes_transferred); + handler_(ec, bytes_transferred); + } + + //private: + asio::basic_streambuf& streambuf_; + WriteHandler handler_; + }; + + template + inline void* asio_handler_allocate(std::size_t size, + write_at_streambuf_op* this_handler) + { + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); + } + + template + inline void asio_handler_deallocate(void* pointer, std::size_t size, + write_at_streambuf_op* this_handler) + { + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); + } + + template + inline bool asio_handler_is_continuation( + write_at_streambuf_op* this_handler) + { + return asio_handler_cont_helpers::is_continuation( + this_handler->handler_); + } + + template + inline void asio_handler_invoke(Function& function, + write_at_streambuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + inline void asio_handler_invoke(const Function& function, + write_at_streambuf_op* this_handler) + { + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); + } + + template + class initiate_async_write_at_streambuf + { + public: + typedef typename AsyncRandomAccessWriteDevice::executor_type executor_type; + + explicit initiate_async_write_at_streambuf( + AsyncRandomAccessWriteDevice& device) + : device_(device) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return device_.get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + uint64_t offset, basic_streambuf* b, + ASIO_MOVE_ARG(CompletionCondition) completion_condition) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + non_const_lvalue handler2(handler); + async_write_at(device_, offset, b->data(), + ASIO_MOVE_CAST(CompletionCondition)(completion_condition), + write_at_streambuf_op::type>( + *b, handler2.value)); + } + + private: + AsyncRandomAccessWriteDevice& device_; + }; +} // namespace detail + +#if !defined(GENERATING_DOCUMENTATION) + +template +struct associated_allocator< + detail::write_at_streambuf_op, + Allocator1> +{ + typedef typename associated_allocator::type type; + + static type get( + const detail::write_at_streambuf_op& h, + const Allocator1& a = Allocator1()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + detail::write_at_streambuf_op, + Executor1> +{ + typedef typename associated_executor::type type; + + static type get( + const detail::write_at_streambuf_op& h, + const Executor1& ex = Executor1()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +#endif // !defined(GENERATING_DOCUMENTATION) + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_write_at_streambuf< + AsyncRandomAccessWriteDevice>(d), + handler, offset, &b, + ASIO_MOVE_CAST(CompletionCondition)(completion_condition)); +} + +template +inline ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, asio::basic_streambuf& b, + ASIO_MOVE_ARG(WriteHandler) handler) +{ + return async_initiate( + detail::initiate_async_write_at_streambuf< + AsyncRandomAccessWriteDevice>(d), + handler, offset, &b, transfer_all()); +} + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IMPL_WRITE_AT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context.hpp new file mode 100644 index 00000000..d9bd4f6c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context.hpp @@ -0,0 +1,872 @@ +// +// io_context.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IO_CONTEXT_HPP +#define ASIO_IO_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include "asio/async_result.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/wrapped_handler.hpp" +#include "asio/error_code.hpp" +#include "asio/execution_context.hpp" + +#if defined(ASIO_HAS_CHRONO) +# include "asio/detail/chrono.hpp" +#endif // defined(ASIO_HAS_CHRONO) + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# include "asio/detail/winsock_init.hpp" +#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \ + || defined(__osf__) +# include "asio/detail/signal_init.hpp" +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail { +#if defined(ASIO_HAS_IOCP) + typedef class win_iocp_io_context io_context_impl; + class win_iocp_overlapped_ptr; +#else + typedef class scheduler io_context_impl; +#endif +} // namespace detail + +/// Provides core I/O functionality. +/** + * The io_context class provides the core I/O functionality for users of the + * asynchronous I/O objects, including: + * + * @li asio::ip::tcp::socket + * @li asio::ip::tcp::acceptor + * @li asio::ip::udp::socket + * @li asio::deadline_timer. + * + * The io_context class also includes facilities intended for developers of + * custom asynchronous services. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe, with the specific exceptions of the restart() + * and notify_fork() functions. Calling restart() while there are unfinished + * run(), run_one(), run_for(), run_until(), poll() or poll_one() calls results + * in undefined behaviour. The notify_fork() function should not be called + * while any io_context function, or any function on an I/O object that is + * associated with the io_context, is being called in another thread. + * + * @par Concepts: + * Dispatcher. + * + * @par Synchronous and asynchronous operations + * + * Synchronous operations on I/O objects implicitly run the io_context object + * for an individual operation. The io_context functions run(), run_one(), + * run_for(), run_until(), poll() or poll_one() must be called for the + * io_context to perform asynchronous operations on behalf of a C++ program. + * Notification that an asynchronous operation has completed is delivered by + * invocation of the associated handler. Handlers are invoked only by a thread + * that is currently calling any overload of run(), run_one(), run_for(), + * run_until(), poll() or poll_one() for the io_context. + * + * @par Effect of exceptions thrown from handlers + * + * If an exception is thrown from a handler, the exception is allowed to + * propagate through the throwing thread's invocation of run(), run_one(), + * run_for(), run_until(), poll() or poll_one(). No other threads that are + * calling any of these functions are affected. It is then the responsibility + * of the application to catch the exception. + * + * After the exception has been caught, the run(), run_one(), run_for(), + * run_until(), poll() or poll_one() call may be restarted @em without the need + * for an intervening call to restart(). This allows the thread to rejoin the + * io_context object's thread pool without impacting any other threads in the + * pool. + * + * For example: + * + * @code + * asio::io_context io_context; + * ... + * for (;;) + * { + * try + * { + * io_context.run(); + * break; // run() exited normally + * } + * catch (my_exception& e) + * { + * // Deal with exception as appropriate. + * } + * } + * @endcode + * + * @par Submitting arbitrary tasks to the io_context + * + * To submit functions to the io_context, use the @ref asio::dispatch, + * @ref asio::post or @ref asio::defer free functions. + * + * For example: + * + * @code void my_task() + * { + * ... + * } + * + * ... + * + * asio::io_context io_context; + * + * // Submit a function to the io_context. + * asio::post(io_context, my_task); + * + * // Submit a lambda object to the io_context. + * asio::post(io_context, + * []() + * { + * ... + * }); + * + * // Run the io_context until it runs out of work. + * io_context.run(); @endcode + * + * @par Stopping the io_context from running out of work + * + * Some applications may need to prevent an io_context object's run() call from + * returning when there is no more work to do. For example, the io_context may + * be being run in a background thread that is launched prior to the + * application's asynchronous operations. The run() call may be kept running by + * creating an object of type + * asio::executor_work_guard: + * + * @code asio::io_context io_context; + * asio::executor_work_guard + * = asio::make_work_guard(io_context); + * ... @endcode + * + * To effect a shutdown, the application will then need to call the io_context + * object's stop() member function. This will cause the io_context run() call + * to return as soon as possible, abandoning unfinished operations and without + * permitting ready handlers to be dispatched. + * + * Alternatively, if the application requires that all operations and handlers + * be allowed to finish normally, the work object may be explicitly reset. + * + * @code asio::io_context io_context; + * asio::executor_work_guard + * = asio::make_work_guard(io_context); + * ... + * work.reset(); // Allow run() to exit. @endcode + */ +class io_context + : public execution_context +{ +private: + typedef detail::io_context_impl impl_type; +#if defined(ASIO_HAS_IOCP) + friend class detail::win_iocp_overlapped_ptr; +#endif + +public: + class executor_type; + friend class executor_type; + +#if !defined(ASIO_NO_DEPRECATED) + class work; + friend class work; +#endif // !defined(ASIO_NO_DEPRECATED) + + class service; + +#if !defined(ASIO_NO_EXTENSIONS) + class strand; +#endif // !defined(ASIO_NO_EXTENSIONS) + + /// The type used to count the number of handlers executed by the context. + typedef std::size_t count_type; + + /// Constructor. + ASIO_DECL io_context(); + + /// Constructor. + /** + * Construct with a hint about the required level of concurrency. + * + * @param concurrency_hint A suggestion to the implementation on how many + * threads it should allow to run simultaneously. + */ + ASIO_DECL explicit io_context(int concurrency_hint); + + /// Destructor. + /** + * On destruction, the io_context performs the following sequence of + * operations: + * + * @li For each service object @c svc in the io_context set, in reverse order + * of the beginning of service object lifetime, performs + * @c svc->shutdown(). + * + * @li Uninvoked handler objects that were scheduled for deferred invocation + * on the io_context, or any associated strand, are destroyed. + * + * @li For each service object @c svc in the io_context set, in reverse order + * of the beginning of service object lifetime, performs + * delete static_cast(svc). + * + * @note The destruction sequence described above permits programs to + * simplify their resource management by using @c shared_ptr<>. Where an + * object's lifetime is tied to the lifetime of a connection (or some other + * sequence of asynchronous operations), a @c shared_ptr to the object would + * be bound into the handlers for all asynchronous operations associated with + * it. This works as follows: + * + * @li When a single connection ends, all associated asynchronous operations + * complete. The corresponding handler objects are destroyed, and all + * @c shared_ptr references to the objects are destroyed. + * + * @li To shut down the whole program, the io_context function stop() is + * called to terminate any run() calls as soon as possible. The io_context + * destructor defined above destroys all handlers, causing all @c shared_ptr + * references to all connection objects to be destroyed. + */ + ASIO_DECL ~io_context(); + + /// Obtains the executor associated with the io_context. + executor_type get_executor() ASIO_NOEXCEPT; + + /// Run the io_context object's event processing loop. + /** + * The run() function blocks until all work has finished and there are no + * more handlers to be dispatched, or until the io_context has been stopped. + * + * Multiple threads may call the run() function to set up a pool of threads + * from which the io_context may execute handlers. All threads that are + * waiting in the pool are equivalent and the io_context may choose any one + * of them to invoke a handler. + * + * A normal exit from the run() function implies that the io_context object + * is stopped (the stopped() function returns @c true). Subsequent calls to + * run(), run_one(), poll() or poll_one() will return immediately unless there + * is a prior call to restart(). + * + * @return The number of handlers that were executed. + * + * @note Calling the run() function from a thread that is currently calling + * one of run(), run_one(), run_for(), run_until(), poll() or poll_one() on + * the same io_context object may introduce the potential for deadlock. It is + * the caller's reponsibility to avoid this. + * + * The poll() function may also be used to dispatch ready handlers, but + * without blocking. + */ + ASIO_DECL count_type run(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Run the io_context object's + /// event processing loop. + /** + * The run() function blocks until all work has finished and there are no + * more handlers to be dispatched, or until the io_context has been stopped. + * + * Multiple threads may call the run() function to set up a pool of threads + * from which the io_context may execute handlers. All threads that are + * waiting in the pool are equivalent and the io_context may choose any one + * of them to invoke a handler. + * + * A normal exit from the run() function implies that the io_context object + * is stopped (the stopped() function returns @c true). Subsequent calls to + * run(), run_one(), poll() or poll_one() will return immediately unless there + * is a prior call to restart(). + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of handlers that were executed. + * + * @note Calling the run() function from a thread that is currently calling + * one of run(), run_one(), run_for(), run_until(), poll() or poll_one() on + * the same io_context object may introduce the potential for deadlock. It is + * the caller's reponsibility to avoid this. + * + * The poll() function may also be used to dispatch ready handlers, but + * without blocking. + */ + ASIO_DECL count_type run(asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + +#if defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + /// Run the io_context object's event processing loop for a specified + /// duration. + /** + * The run_for() function blocks until all work has finished and there are no + * more handlers to be dispatched, until the io_context has been stopped, or + * until the specified duration has elapsed. + * + * @param rel_time The duration for which the call may block. + * + * @return The number of handlers that were executed. + */ + template + std::size_t run_for(const chrono::duration& rel_time); + + /// Run the io_context object's event processing loop until a specified time. + /** + * The run_until() function blocks until all work has finished and there are + * no more handlers to be dispatched, until the io_context has been stopped, + * or until the specified time has been reached. + * + * @param abs_time The time point until which the call may block. + * + * @return The number of handlers that were executed. + */ + template + std::size_t run_until(const chrono::time_point& abs_time); +#endif // defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + + /// Run the io_context object's event processing loop to execute at most one + /// handler. + /** + * The run_one() function blocks until one handler has been dispatched, or + * until the io_context has been stopped. + * + * @return The number of handlers that were executed. A zero return value + * implies that the io_context object is stopped (the stopped() function + * returns @c true). Subsequent calls to run(), run_one(), poll() or + * poll_one() will return immediately unless there is a prior call to + * restart(). + * + * @note Calling the run_one() function from a thread that is currently + * calling one of run(), run_one(), run_for(), run_until(), poll() or + * poll_one() on the same io_context object may introduce the potential for + * deadlock. It is the caller's reponsibility to avoid this. + */ + ASIO_DECL count_type run_one(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overlaod.) Run the io_context object's + /// event processing loop to execute at most one handler. + /** + * The run_one() function blocks until one handler has been dispatched, or + * until the io_context has been stopped. + * + * @return The number of handlers that were executed. A zero return value + * implies that the io_context object is stopped (the stopped() function + * returns @c true). Subsequent calls to run(), run_one(), poll() or + * poll_one() will return immediately unless there is a prior call to + * restart(). + * + * @return The number of handlers that were executed. + * + * @note Calling the run_one() function from a thread that is currently + * calling one of run(), run_one(), run_for(), run_until(), poll() or + * poll_one() on the same io_context object may introduce the potential for + * deadlock. It is the caller's reponsibility to avoid this. + */ + ASIO_DECL count_type run_one(asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + +#if defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + /// Run the io_context object's event processing loop for a specified duration + /// to execute at most one handler. + /** + * The run_one_for() function blocks until one handler has been dispatched, + * until the io_context has been stopped, or until the specified duration has + * elapsed. + * + * @param rel_time The duration for which the call may block. + * + * @return The number of handlers that were executed. + */ + template + std::size_t run_one_for(const chrono::duration& rel_time); + + /// Run the io_context object's event processing loop until a specified time + /// to execute at most one handler. + /** + * The run_one_until() function blocks until one handler has been dispatched, + * until the io_context has been stopped, or until the specified time has + * been reached. + * + * @param abs_time The time point until which the call may block. + * + * @return The number of handlers that were executed. + */ + template + std::size_t run_one_until( + const chrono::time_point& abs_time); +#endif // defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + + /// Run the io_context object's event processing loop to execute ready + /// handlers. + /** + * The poll() function runs handlers that are ready to run, without blocking, + * until the io_context has been stopped or there are no more ready handlers. + * + * @return The number of handlers that were executed. + */ + ASIO_DECL count_type poll(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Run the io_context object's + /// event processing loop to execute ready handlers. + /** + * The poll() function runs handlers that are ready to run, without blocking, + * until the io_context has been stopped or there are no more ready handlers. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of handlers that were executed. + */ + ASIO_DECL count_type poll(asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Run the io_context object's event processing loop to execute one ready + /// handler. + /** + * The poll_one() function runs at most one handler that is ready to run, + * without blocking. + * + * @return The number of handlers that were executed. + */ + ASIO_DECL count_type poll_one(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use non-error_code overload.) Run the io_context object's + /// event processing loop to execute one ready handler. + /** + * The poll_one() function runs at most one handler that is ready to run, + * without blocking. + * + * @param ec Set to indicate what error occurred, if any. + * + * @return The number of handlers that were executed. + */ + ASIO_DECL count_type poll_one(asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Stop the io_context object's event processing loop. + /** + * This function does not block, but instead simply signals the io_context to + * stop. All invocations of its run() or run_one() member functions should + * return as soon as possible. Subsequent calls to run(), run_one(), poll() + * or poll_one() will return immediately until restart() is called. + */ + ASIO_DECL void stop(); + + /// Determine whether the io_context object has been stopped. + /** + * This function is used to determine whether an io_context object has been + * stopped, either through an explicit call to stop(), or due to running out + * of work. When an io_context object is stopped, calls to run(), run_one(), + * poll() or poll_one() will return immediately without invoking any + * handlers. + * + * @return @c true if the io_context object is stopped, otherwise @c false. + */ + ASIO_DECL bool stopped() const; + + /// Restart the io_context in preparation for a subsequent run() invocation. + /** + * This function must be called prior to any second or later set of + * invocations of the run(), run_one(), poll() or poll_one() functions when a + * previous invocation of these functions returned due to the io_context + * being stopped or running out of work. After a call to restart(), the + * io_context object's stopped() function will return @c false. + * + * This function must not be called while there are any unfinished calls to + * the run(), run_one(), poll() or poll_one() functions. + */ + ASIO_DECL void restart(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use restart().) Reset the io_context in preparation for a + /// subsequent run() invocation. + /** + * This function must be called prior to any second or later set of + * invocations of the run(), run_one(), poll() or poll_one() functions when a + * previous invocation of these functions returned due to the io_context + * being stopped or running out of work. After a call to restart(), the + * io_context object's stopped() function will return @c false. + * + * This function must not be called while there are any unfinished calls to + * the run(), run_one(), poll() or poll_one() functions. + */ + void reset(); + + /// (Deprecated: Use asio::dispatch().) Request the io_context to + /// invoke the given handler. + /** + * This function is used to ask the io_context to execute the given handler. + * + * The io_context guarantees that the handler will only be called in a thread + * in which the run(), run_one(), poll() or poll_one() member functions is + * currently being invoked. The handler may be executed inside this function + * if the guarantee can be met. + * + * @param handler The handler to be called. The io_context will make + * a copy of the handler object as required. The function signature of the + * handler must be: @code void handler(); @endcode + * + * @note This function throws an exception only if: + * + * @li the handler's @c asio_handler_allocate function; or + * + * @li the handler's copy constructor + * + * throws an exception. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) + dispatch(ASIO_MOVE_ARG(LegacyCompletionHandler) handler); + + /// (Deprecated: Use asio::post().) Request the io_context to invoke + /// the given handler and return immediately. + /** + * This function is used to ask the io_context to execute the given handler, + * but without allowing the io_context to call the handler from inside this + * function. + * + * The io_context guarantees that the handler will only be called in a thread + * in which the run(), run_one(), poll() or poll_one() member functions is + * currently being invoked. + * + * @param handler The handler to be called. The io_context will make + * a copy of the handler object as required. The function signature of the + * handler must be: @code void handler(); @endcode + * + * @note This function throws an exception only if: + * + * @li the handler's @c asio_handler_allocate function; or + * + * @li the handler's copy constructor + * + * throws an exception. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) + post(ASIO_MOVE_ARG(LegacyCompletionHandler) handler); + + /// (Deprecated: Use asio::bind_executor().) Create a new handler that + /// automatically dispatches the wrapped handler on the io_context. + /** + * This function is used to create a new handler function object that, when + * invoked, will automatically pass the wrapped handler to the io_context + * object's dispatch function. + * + * @param handler The handler to be wrapped. The io_context will make a copy + * of the handler object as required. The function signature of the handler + * must be: @code void handler(A1 a1, ... An an); @endcode + * + * @return A function object that, when invoked, passes the wrapped handler to + * the io_context object's dispatch function. Given a function object with the + * signature: + * @code R f(A1 a1, ... An an); @endcode + * If this function object is passed to the wrap function like so: + * @code io_context.wrap(f); @endcode + * then the return value is a function object with the signature + * @code void g(A1 a1, ... An an); @endcode + * that, when invoked, executes code equivalent to: + * @code io_context.dispatch(boost::bind(f, a1, ... an)); @endcode + */ + template +#if defined(GENERATING_DOCUMENTATION) + unspecified +#else + detail::wrapped_handler +#endif + wrap(Handler handler); +#endif // !defined(ASIO_NO_DEPRECATED) + +private: +#if !defined(ASIO_NO_DEPRECATED) + struct initiate_dispatch; + struct initiate_post; +#endif // !defined(ASIO_NO_DEPRECATED) + + // Helper function to add the implementation. + ASIO_DECL impl_type& add_impl(impl_type* impl); + + // Backwards compatible overload for use with services derived from + // io_context::service. + template + friend Service& use_service(io_context& ioc); + +#if defined(ASIO_WINDOWS) || defined(__CYGWIN__) + detail::winsock_init<> init_; +#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \ + || defined(__osf__) + detail::signal_init<> init_; +#endif + + // The implementation. + impl_type& impl_; +}; + +/// Executor used to submit functions to an io_context. +class io_context::executor_type +{ +public: + /// Obtain the underlying execution context. + io_context& context() const ASIO_NOEXCEPT; + + /// Inform the io_context that it has some outstanding work to do. + /** + * This function is used to inform the io_context that some work has begun. + * This ensures that the io_context's run() and run_one() functions do not + * exit while the work is underway. + */ + void on_work_started() const ASIO_NOEXCEPT; + + /// Inform the io_context that some work is no longer outstanding. + /** + * This function is used to inform the io_context that some work has + * finished. Once the count of unfinished work reaches zero, the io_context + * is stopped and the run() and run_one() functions may exit. + */ + void on_work_finished() const ASIO_NOEXCEPT; + + /// Request the io_context to invoke the given function object. + /** + * This function is used to ask the io_context to execute the given function + * object. If the current thread is running the io_context, @c dispatch() + * executes the function before returning. Otherwise, the function will be + * scheduled to run on the io_context. + * + * @param f The function object to be called. The executor will make a copy + * of the handler object as required. The function signature of the function + * object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the io_context to invoke the given function object. + /** + * This function is used to ask the io_context to execute the given function + * object. The function object will never be executed inside @c post(). + * Instead, it will be scheduled to run on the io_context. + * + * @param f The function object to be called. The executor will make a copy + * of the handler object as required. The function signature of the function + * object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the io_context to invoke the given function object. + /** + * This function is used to ask the io_context to execute the given function + * object. The function object will never be executed inside @c defer(). + * Instead, it will be scheduled to run on the io_context. + * + * If the current thread belongs to the io_context, @c defer() will delay + * scheduling the function object until the current thread returns control to + * the pool. + * + * @param f The function object to be called. The executor will make a copy + * of the handler object as required. The function signature of the function + * object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Determine whether the io_context is running in the current thread. + /** + * @return @c true if the current thread is running the io_context. Otherwise + * returns @c false. + */ + bool running_in_this_thread() const ASIO_NOEXCEPT; + + /// Compare two executors for equality. + /** + * Two executors are equal if they refer to the same underlying io_context. + */ + friend bool operator==(const executor_type& a, + const executor_type& b) ASIO_NOEXCEPT + { + return &a.io_context_ == &b.io_context_; + } + + /// Compare two executors for inequality. + /** + * Two executors are equal if they refer to the same underlying io_context. + */ + friend bool operator!=(const executor_type& a, + const executor_type& b) ASIO_NOEXCEPT + { + return &a.io_context_ != &b.io_context_; + } + +private: + friend class io_context; + + // Constructor. + explicit executor_type(io_context& i) : io_context_(i) {} + + // The underlying io_context. + io_context& io_context_; +}; + +#if !defined(ASIO_NO_DEPRECATED) +/// (Deprecated: Use executor_work_guard.) Class to inform the io_context when +/// it has work to do. +/** + * The work class is used to inform the io_context when work starts and + * finishes. This ensures that the io_context object's run() function will not + * exit while work is underway, and that it does exit when there is no + * unfinished work remaining. + * + * The work class is copy-constructible so that it may be used as a data member + * in a handler class. It is not assignable. + */ +class io_context::work +{ +public: + /// Constructor notifies the io_context that work is starting. + /** + * The constructor is used to inform the io_context that some work has begun. + * This ensures that the io_context object's run() function will not exit + * while the work is underway. + */ + explicit work(asio::io_context& io_context); + + /// Copy constructor notifies the io_context that work is starting. + /** + * The constructor is used to inform the io_context that some work has begun. + * This ensures that the io_context object's run() function will not exit + * while the work is underway. + */ + work(const work& other); + + /// Destructor notifies the io_context that the work is complete. + /** + * The destructor is used to inform the io_context that some work has + * finished. Once the count of unfinished work reaches zero, the io_context + * object's run() function is permitted to exit. + */ + ~work(); + + /// Get the io_context associated with the work. + asio::io_context& get_io_context(); + +private: + // Prevent assignment. + void operator=(const work& other); + + // The io_context implementation. + detail::io_context_impl& io_context_impl_; +}; +#endif // !defined(ASIO_NO_DEPRECATED) + +/// Base class for all io_context services. +class io_context::service + : public execution_context::service +{ +public: + /// Get the io_context object that owns the service. + asio::io_context& get_io_context(); + +private: + /// Destroy all user-defined handler objects owned by the service. + ASIO_DECL virtual void shutdown(); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use shutdown().) Destroy all user-defined handler objects + /// owned by the service. + ASIO_DECL virtual void shutdown_service(); +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Handle notification of a fork-related event to perform any necessary + /// housekeeping. + /** + * This function is not a pure virtual so that services only have to + * implement it if necessary. The default implementation does nothing. + */ + ASIO_DECL virtual void notify_fork( + execution_context::fork_event event); + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use notify_fork().) Handle notification of a fork-related + /// event to perform any necessary housekeeping. + /** + * This function is not a pure virtual so that services only have to + * implement it if necessary. The default implementation does nothing. + */ + ASIO_DECL virtual void fork_service( + execution_context::fork_event event); +#endif // !defined(ASIO_NO_DEPRECATED) + +protected: + /// Constructor. + /** + * @param owner The io_context object that owns the service. + */ + ASIO_DECL service(asio::io_context& owner); + + /// Destructor. + ASIO_DECL virtual ~service(); +}; + +namespace detail { + +// Special service base class to keep classes header-file only. +template +class service_base + : public asio::io_context::service +{ +public: + static asio::detail::service_id id; + + // Constructor. + service_base(asio::io_context& io_context) + : asio::io_context::service(io_context) + { + } +}; + +template +asio::detail::service_id service_base::id; + +} // namespace detail +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/io_context.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/io_context.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +// If both io_context.hpp and strand.hpp have been included, automatically +// include the header file needed for the io_context::strand class. +#if !defined(ASIO_NO_EXTENSIONS) +# if defined(ASIO_STRAND_HPP) +# include "asio/io_context_strand.hpp" +# endif // defined(ASIO_STRAND_HPP) +#endif // !defined(ASIO_NO_EXTENSIONS) + +#endif // ASIO_IO_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context_strand.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context_strand.hpp new file mode 100644 index 00000000..54ad7f5a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_context_strand.hpp @@ -0,0 +1,374 @@ +// +// io_context_strand.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IO_CONTEXT_STRAND_HPP +#define ASIO_IO_CONTEXT_STRAND_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) + +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/strand_service.hpp" +#include "asio/detail/wrapped_handler.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides serialised handler execution. +/** + * The io_context::strand class provides the ability to post and dispatch + * handlers with the guarantee that none of those handlers will execute + * concurrently. + * + * @par Order of handler invocation + * Given: + * + * @li a strand object @c s + * + * @li an object @c a meeting completion handler requirements + * + * @li an object @c a1 which is an arbitrary copy of @c a made by the + * implementation + * + * @li an object @c b meeting completion handler requirements + * + * @li an object @c b1 which is an arbitrary copy of @c b made by the + * implementation + * + * if any of the following conditions are true: + * + * @li @c s.post(a) happens-before @c s.post(b) + * + * @li @c s.post(a) happens-before @c s.dispatch(b), where the latter is + * performed outside the strand + * + * @li @c s.dispatch(a) happens-before @c s.post(b), where the former is + * performed outside the strand + * + * @li @c s.dispatch(a) happens-before @c s.dispatch(b), where both are + * performed outside the strand + * + * then @c asio_handler_invoke(a1, &a1) happens-before + * @c asio_handler_invoke(b1, &b1). + * + * Note that in the following case: + * @code async_op_1(..., s.wrap(a)); + * async_op_2(..., s.wrap(b)); @endcode + * the completion of the first async operation will perform @c s.dispatch(a), + * and the second will perform @c s.dispatch(b), but the order in which those + * are performed is unspecified. That is, you cannot state whether one + * happens-before the other. Therefore none of the above conditions are met and + * no ordering guarantee is made. + * + * @note The implementation makes no guarantee that handlers posted or + * dispatched through different @c strand objects will be invoked concurrently. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Dispatcher. + */ +class io_context::strand +{ +public: + /// Constructor. + /** + * Constructs the strand. + * + * @param io_context The io_context object that the strand will use to + * dispatch handlers that are ready to be run. + */ + explicit strand(asio::io_context& io_context) + : service_(asio::use_service< + asio::detail::strand_service>(io_context)) + { + service_.construct(impl_); + } + + /// Destructor. + /** + * Destroys a strand. + * + * Handlers posted through the strand that have not yet been invoked will + * still be dispatched in a way that meets the guarantee of non-concurrency. + */ + ~strand() + { + } + + /// Obtain the underlying execution context. + asio::io_context& context() const ASIO_NOEXCEPT + { + return service_.get_io_context(); + } + + /// Inform the strand that it has some outstanding work to do. + /** + * The strand delegates this call to its underlying io_context. + */ + void on_work_started() const ASIO_NOEXCEPT + { + context().get_executor().on_work_started(); + } + + /// Inform the strand that some work is no longer outstanding. + /** + * The strand delegates this call to its underlying io_context. + */ + void on_work_finished() const ASIO_NOEXCEPT + { + context().get_executor().on_work_finished(); + } + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the strand to execute the given function + * object on its underlying io_context. The function object will be executed + * inside this function if the strand is not otherwise busy and if the + * underlying io_context's executor's @c dispatch() function is also able to + * execute the function before returning. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + typename decay::type tmp(ASIO_MOVE_CAST(Function)(f)); + service_.dispatch(impl_, tmp); + (void)a; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use asio::dispatch().) Request the strand to invoke + /// the given handler. + /** + * This function is used to ask the strand to execute the given handler. + * + * The strand object guarantees that handlers posted or dispatched through + * the strand will not be executed concurrently. The handler may be executed + * inside this function if the guarantee can be met. If this function is + * called from within a handler that was posted or dispatched through the same + * strand, then the new handler will be executed immediately. + * + * The strand's guarantee is in addition to the guarantee provided by the + * underlying io_context. The io_context guarantees that the handler will only + * be called in a thread in which the io_context's run member function is + * currently being invoked. + * + * @param handler The handler to be called. The strand will make a copy of the + * handler object as required. The function signature of the handler must be: + * @code void handler(); @endcode + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) + dispatch(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) + { + return async_initiate( + initiate_dispatch(), handler, this); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled to run by the underlying io_context. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + typename decay::type tmp(ASIO_MOVE_CAST(Function)(f)); + service_.post(impl_, tmp); + (void)a; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use asio::post().) Request the strand to invoke the + /// given handler and return immediately. + /** + * This function is used to ask the strand to execute the given handler, but + * without allowing the strand to call the handler from inside this function. + * + * The strand object guarantees that handlers posted or dispatched through + * the strand will not be executed concurrently. The strand's guarantee is in + * addition to the guarantee provided by the underlying io_context. The + * io_context guarantees that the handler will only be called in a thread in + * which the io_context's run member function is currently being invoked. + * + * @param handler The handler to be called. The strand will make a copy of the + * handler object as required. The function signature of the handler must be: + * @code void handler(); @endcode + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(LegacyCompletionHandler, void ()) + post(ASIO_MOVE_ARG(LegacyCompletionHandler) handler) + { + return async_initiate( + initiate_post(), handler, this); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled to run by the underlying io_context. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + typename decay::type tmp(ASIO_MOVE_CAST(Function)(f)); + service_.post(impl_, tmp); + (void)a; + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use asio::bind_executor().) Create a new handler that + /// automatically dispatches the wrapped handler on the strand. + /** + * This function is used to create a new handler function object that, when + * invoked, will automatically pass the wrapped handler to the strand's + * dispatch function. + * + * @param handler The handler to be wrapped. The strand will make a copy of + * the handler object as required. The function signature of the handler must + * be: @code void handler(A1 a1, ... An an); @endcode + * + * @return A function object that, when invoked, passes the wrapped handler to + * the strand's dispatch function. Given a function object with the signature: + * @code R f(A1 a1, ... An an); @endcode + * If this function object is passed to the wrap function like so: + * @code strand.wrap(f); @endcode + * then the return value is a function object with the signature + * @code void g(A1 a1, ... An an); @endcode + * that, when invoked, executes code equivalent to: + * @code strand.dispatch(boost::bind(f, a1, ... an)); @endcode + */ + template +#if defined(GENERATING_DOCUMENTATION) + unspecified +#else + detail::wrapped_handler +#endif + wrap(Handler handler) + { + return detail::wrapped_handler(*this, handler); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the strand is running in the current thread. + /** + * @return @c true if the current thread is executing a handler that was + * submitted to the strand using post(), dispatch() or wrap(). Otherwise + * returns @c false. + */ + bool running_in_this_thread() const ASIO_NOEXCEPT + { + return service_.running_in_this_thread(impl_); + } + + /// Compare two strands for equality. + /** + * Two strands are equal if they refer to the same ordered, non-concurrent + * state. + */ + friend bool operator==(const strand& a, const strand& b) ASIO_NOEXCEPT + { + return a.impl_ == b.impl_; + } + + /// Compare two strands for inequality. + /** + * Two strands are equal if they refer to the same ordered, non-concurrent + * state. + */ + friend bool operator!=(const strand& a, const strand& b) ASIO_NOEXCEPT + { + return a.impl_ != b.impl_; + } + +private: +#if !defined(ASIO_NO_DEPRECATED) + struct initiate_dispatch + { + template + void operator()(ASIO_MOVE_ARG(LegacyCompletionHandler) handler, + strand* self) const + { + // If you get an error on the following line it means that your + // handler does not meet the documented type requirements for a + // LegacyCompletionHandler. + ASIO_LEGACY_COMPLETION_HANDLER_CHECK( + LegacyCompletionHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self->service_.dispatch(self->impl_, handler2.value); + } + }; + + struct initiate_post + { + template + void operator()(ASIO_MOVE_ARG(LegacyCompletionHandler) handler, + strand* self) const + { + // If you get an error on the following line it means that your + // handler does not meet the documented type requirements for a + // LegacyCompletionHandler. + ASIO_LEGACY_COMPLETION_HANDLER_CHECK( + LegacyCompletionHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self->service_.post(self->impl_, handler2.value); + } + }; +#endif // !defined(ASIO_NO_DEPRECATED) + + asio::detail::strand_service& service_; + mutable asio::detail::strand_service::implementation_type impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_EXTENSIONS) + +#endif // ASIO_IO_CONTEXT_STRAND_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service.hpp new file mode 100644 index 00000000..2916aff1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service.hpp @@ -0,0 +1,33 @@ +// +// io_service.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IO_SERVICE_HPP +#define ASIO_IO_SERVICE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if !defined(ASIO_NO_DEPRECATED) +/// Typedef for backwards compatibility. +typedef io_context io_service; +#endif // !defined(ASIO_NO_DEPRECATED) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IO_SERVICE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service_strand.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service_strand.hpp new file mode 100644 index 00000000..5d35ee35 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/io_service_strand.hpp @@ -0,0 +1,20 @@ +// +// io_service_strand.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IO_SERVICE_STRAND_HPP +#define ASIO_IO_SERVICE_STRAND_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/io_context_strand.hpp" + +#endif // ASIO_IO_SERVICE_STRAND_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address.hpp new file mode 100644 index 00000000..d493981a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address.hpp @@ -0,0 +1,268 @@ +// +// ip/address.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_HPP +#define ASIO_IP_ADDRESS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/throw_exception.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error_code.hpp" +#include "asio/ip/address_v4.hpp" +#include "asio/ip/address_v6.hpp" +#include "asio/ip/bad_address_cast.hpp" + +#if !defined(ASIO_NO_IOSTREAM) +# include +#endif // !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Implements version-independent IP addresses. +/** + * The asio::ip::address class provides the ability to use either IP + * version 4 or version 6 addresses. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class address +{ +public: + /// Default constructor. + ASIO_DECL address() ASIO_NOEXCEPT; + + /// Construct an address from an IPv4 address. + ASIO_DECL address( + const asio::ip::address_v4& ipv4_address) ASIO_NOEXCEPT; + + /// Construct an address from an IPv6 address. + ASIO_DECL address( + const asio::ip::address_v6& ipv6_address) ASIO_NOEXCEPT; + + /// Copy constructor. + ASIO_DECL address(const address& other) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + ASIO_DECL address(address&& other) ASIO_NOEXCEPT; +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + ASIO_DECL address& operator=(const address& other) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + ASIO_DECL address& operator=(address&& other) ASIO_NOEXCEPT; +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from an IPv4 address. + ASIO_DECL address& operator=( + const asio::ip::address_v4& ipv4_address) ASIO_NOEXCEPT; + + /// Assign from an IPv6 address. + ASIO_DECL address& operator=( + const asio::ip::address_v6& ipv6_address) ASIO_NOEXCEPT; + + /// Get whether the address is an IP version 4 address. + bool is_v4() const ASIO_NOEXCEPT + { + return type_ == ipv4; + } + + /// Get whether the address is an IP version 6 address. + bool is_v6() const ASIO_NOEXCEPT + { + return type_ == ipv6; + } + + /// Get the address as an IP version 4 address. + ASIO_DECL asio::ip::address_v4 to_v4() const; + + /// Get the address as an IP version 6 address. + ASIO_DECL asio::ip::address_v6 to_v6() const; + + /// Get the address as a string. + ASIO_DECL std::string to_string() const; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use other overload.) Get the address as a string. + ASIO_DECL std::string to_string(asio::error_code& ec) const; + + /// (Deprecated: Use make_address().) Create an address from an IPv4 address + /// string in dotted decimal form, or from an IPv6 address in hexadecimal + /// notation. + static address from_string(const char* str); + + /// (Deprecated: Use make_address().) Create an address from an IPv4 address + /// string in dotted decimal form, or from an IPv6 address in hexadecimal + /// notation. + static address from_string(const char* str, asio::error_code& ec); + + /// (Deprecated: Use make_address().) Create an address from an IPv4 address + /// string in dotted decimal form, or from an IPv6 address in hexadecimal + /// notation. + static address from_string(const std::string& str); + + /// (Deprecated: Use make_address().) Create an address from an IPv4 address + /// string in dotted decimal form, or from an IPv6 address in hexadecimal + /// notation. + static address from_string( + const std::string& str, asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the address is a loopback address. + ASIO_DECL bool is_loopback() const ASIO_NOEXCEPT; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const ASIO_NOEXCEPT; + + /// Determine whether the address is a multicast address. + ASIO_DECL bool is_multicast() const ASIO_NOEXCEPT; + + /// Compare two addresses for equality. + ASIO_DECL friend bool operator==(const address& a1, + const address& a2) ASIO_NOEXCEPT; + + /// Compare two addresses for inequality. + friend bool operator!=(const address& a1, + const address& a2) ASIO_NOEXCEPT + { + return !(a1 == a2); + } + + /// Compare addresses for ordering. + ASIO_DECL friend bool operator<(const address& a1, + const address& a2) ASIO_NOEXCEPT; + + /// Compare addresses for ordering. + friend bool operator>(const address& a1, + const address& a2) ASIO_NOEXCEPT + { + return a2 < a1; + } + + /// Compare addresses for ordering. + friend bool operator<=(const address& a1, + const address& a2) ASIO_NOEXCEPT + { + return !(a2 < a1); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address& a1, + const address& a2) ASIO_NOEXCEPT + { + return !(a1 < a2); + } + +private: + // The type of the address. + enum { ipv4, ipv6 } type_; + + // The underlying IPv4 address. + asio::ip::address_v4 ipv4_address_; + + // The underlying IPv6 address. + asio::ip::address_v6 ipv6_address_; +}; + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(const char* str); + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(const char* str, + asio::error_code& ec) ASIO_NOEXCEPT; + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(const std::string& str); + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(const std::string& str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(string_view str); + +/// Create an address from an IPv4 address string in dotted decimal form, +/// or from an IPv6 address in hexadecimal notation. +/** + * @relates address + */ +ASIO_DECL address make_address(string_view str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output an address as a string. +/** + * Used to output a human-readable string for a specified address. + * + * @param os The output stream to which the string will be written. + * + * @param addr The address to be written. + * + * @return The output stream. + * + * @relates asio::ip::address + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address& addr); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/address.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/address.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_ADDRESS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4.hpp new file mode 100644 index 00000000..4d6af7fd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4.hpp @@ -0,0 +1,335 @@ +// +// ip/address_v4.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V4_HPP +#define ASIO_IP_ADDRESS_V4_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/array.hpp" +#include "asio/detail/cstdint.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/winsock_init.hpp" +#include "asio/error_code.hpp" + +#if !defined(ASIO_NO_IOSTREAM) +# include +#endif // !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Implements IP version 4 style addresses. +/** + * The asio::ip::address_v4 class provides the ability to use and + * manipulate IP version 4 addresses. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class address_v4 +{ +public: + /// The type used to represent an address as an unsigned integer. + typedef uint_least32_t uint_type; + + /// The type used to represent an address as an array of bytes. + /** + * @note This type is defined in terms of the C++0x template @c std::array + * when it is available. Otherwise, it uses @c boost:array. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef array bytes_type; +#else + typedef asio::detail::array bytes_type; +#endif + + /// Default constructor. + address_v4() ASIO_NOEXCEPT + { + addr_.s_addr = 0; + } + + /// Construct an address from raw bytes. + ASIO_DECL explicit address_v4(const bytes_type& bytes); + + /// Construct an address from an unsigned integer in host byte order. + ASIO_DECL explicit address_v4(uint_type addr); + + /// Copy constructor. + address_v4(const address_v4& other) ASIO_NOEXCEPT + : addr_(other.addr_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + address_v4(address_v4&& other) ASIO_NOEXCEPT + : addr_(other.addr_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + address_v4& operator=(const address_v4& other) ASIO_NOEXCEPT + { + addr_ = other.addr_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + address_v4& operator=(address_v4&& other) ASIO_NOEXCEPT + { + addr_ = other.addr_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Get the address in bytes, in network byte order. + ASIO_DECL bytes_type to_bytes() const ASIO_NOEXCEPT; + + /// Get the address as an unsigned integer in host byte order + ASIO_DECL uint_type to_uint() const ASIO_NOEXCEPT; + +#if !defined(ASIO_NO_DEPRECATED) + /// Get the address as an unsigned long in host byte order + ASIO_DECL unsigned long to_ulong() const; +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Get the address as a string in dotted decimal format. + ASIO_DECL std::string to_string() const; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use other overload.) Get the address as a string in dotted + /// decimal format. + ASIO_DECL std::string to_string(asio::error_code& ec) const; + + /// (Deprecated: Use make_address_v4().) Create an address from an IP address + /// string in dotted decimal form. + static address_v4 from_string(const char* str); + + /// (Deprecated: Use make_address_v4().) Create an address from an IP address + /// string in dotted decimal form. + static address_v4 from_string( + const char* str, asio::error_code& ec); + + /// (Deprecated: Use make_address_v4().) Create an address from an IP address + /// string in dotted decimal form. + static address_v4 from_string(const std::string& str); + + /// (Deprecated: Use make_address_v4().) Create an address from an IP address + /// string in dotted decimal form. + static address_v4 from_string( + const std::string& str, asio::error_code& ec); +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the address is a loopback address. + ASIO_DECL bool is_loopback() const ASIO_NOEXCEPT; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const ASIO_NOEXCEPT; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use network_v4 class.) Determine whether the address is a + /// class A address. + ASIO_DECL bool is_class_a() const; + + /// (Deprecated: Use network_v4 class.) Determine whether the address is a + /// class B address. + ASIO_DECL bool is_class_b() const; + + /// (Deprecated: Use network_v4 class.) Determine whether the address is a + /// class C address. + ASIO_DECL bool is_class_c() const; +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the address is a multicast address. + ASIO_DECL bool is_multicast() const ASIO_NOEXCEPT; + + /// Compare two addresses for equality. + friend bool operator==(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.addr_.s_addr == a2.addr_.s_addr; + } + + /// Compare two addresses for inequality. + friend bool operator!=(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.addr_.s_addr != a2.addr_.s_addr; + } + + /// Compare addresses for ordering. + friend bool operator<(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.to_uint() < a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator>(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.to_uint() > a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator<=(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.to_uint() <= a2.to_uint(); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address_v4& a1, + const address_v4& a2) ASIO_NOEXCEPT + { + return a1.to_uint() >= a2.to_uint(); + } + + /// Obtain an address object that represents any address. + static address_v4 any() ASIO_NOEXCEPT + { + return address_v4(); + } + + /// Obtain an address object that represents the loopback address. + static address_v4 loopback() ASIO_NOEXCEPT + { + return address_v4(0x7F000001); + } + + /// Obtain an address object that represents the broadcast address. + static address_v4 broadcast() ASIO_NOEXCEPT + { + return address_v4(0xFFFFFFFF); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use network_v4 class.) Obtain an address object that + /// represents the broadcast address that corresponds to the specified + /// address and netmask. + ASIO_DECL static address_v4 broadcast( + const address_v4& addr, const address_v4& mask); + + /// (Deprecated: Use network_v4 class.) Obtain the netmask that corresponds + /// to the address, based on its address class. + ASIO_DECL static address_v4 netmask(const address_v4& addr); +#endif // !defined(ASIO_NO_DEPRECATED) + +private: + // The underlying IPv4 address. + asio::detail::in4_addr_type addr_; +}; + +/// Create an IPv4 address from raw bytes in network order. +/** + * @relates address_v4 + */ +inline address_v4 make_address_v4(const address_v4::bytes_type& bytes) +{ + return address_v4(bytes); +} + +/// Create an IPv4 address from an unsigned integer in host byte order. +/** + * @relates address_v4 + */ +inline address_v4 make_address_v4(address_v4::uint_type addr) +{ + return address_v4(addr); +} + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(const char* str); + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(const char* str, + asio::error_code& ec) ASIO_NOEXCEPT; + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(const std::string& str); + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(const std::string& str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(string_view str); + +/// Create an IPv4 address from an IP address string in dotted decimal form. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4(string_view str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output an address as a string. +/** + * Used to output a human-readable string for a specified address. + * + * @param os The output stream to which the string will be written. + * + * @param addr The address to be written. + * + * @return The output stream. + * + * @relates asio::ip::address_v4 + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address_v4& addr); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/address_v4.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/address_v4.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_ADDRESS_V4_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_iterator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_iterator.hpp new file mode 100644 index 00000000..3702d93e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_iterator.hpp @@ -0,0 +1,162 @@ +// +// ip/address_v4_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V4_ITERATOR_HPP +#define ASIO_IP_ADDRESS_V4_ITERATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/address_v4.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template class basic_address_iterator; + +/// An input iterator that can be used for traversing IPv4 addresses. +/** + * In addition to satisfying the input iterator requirements, this iterator + * also supports decrement. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template <> class basic_address_iterator +{ +public: + /// The type of the elements pointed to by the iterator. + typedef address_v4 value_type; + + /// Distance between two iterators. + typedef std::ptrdiff_t difference_type; + + /// The type of a pointer to an element pointed to by the iterator. + typedef const address_v4* pointer; + + /// The type of a reference to an element pointed to by the iterator. + typedef const address_v4& reference; + + /// Denotes that the iterator satisfies the input iterator requirements. + typedef std::input_iterator_tag iterator_category; + + /// Construct an iterator that points to the specified address. + basic_address_iterator(const address_v4& addr) ASIO_NOEXCEPT + : address_(addr) + { + } + + /// Copy constructor. + basic_address_iterator( + const basic_address_iterator& other) ASIO_NOEXCEPT + : address_(other.address_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_address_iterator(basic_address_iterator&& other) ASIO_NOEXCEPT + : address_(ASIO_MOVE_CAST(address_v4)(other.address_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assignment operator. + basic_address_iterator& operator=( + const basic_address_iterator& other) ASIO_NOEXCEPT + { + address_ = other.address_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move assignment operator. + basic_address_iterator& operator=( + basic_address_iterator&& other) ASIO_NOEXCEPT + { + address_ = ASIO_MOVE_CAST(address_v4)(other.address_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Dereference the iterator. + const address_v4& operator*() const ASIO_NOEXCEPT + { + return address_; + } + + /// Dereference the iterator. + const address_v4* operator->() const ASIO_NOEXCEPT + { + return &address_; + } + + /// Pre-increment operator. + basic_address_iterator& operator++() ASIO_NOEXCEPT + { + address_ = address_v4((address_.to_uint() + 1) & 0xFFFFFFFF); + return *this; + } + + /// Post-increment operator. + basic_address_iterator operator++(int) ASIO_NOEXCEPT + { + basic_address_iterator tmp(*this); + ++*this; + return tmp; + } + + /// Pre-decrement operator. + basic_address_iterator& operator--() ASIO_NOEXCEPT + { + address_ = address_v4((address_.to_uint() - 1) & 0xFFFFFFFF); + return *this; + } + + /// Post-decrement operator. + basic_address_iterator operator--(int) + { + basic_address_iterator tmp(*this); + --*this; + return tmp; + } + + /// Compare two addresses for equality. + friend bool operator==(const basic_address_iterator& a, + const basic_address_iterator& b) + { + return a.address_ == b.address_; + } + + /// Compare two addresses for inequality. + friend bool operator!=(const basic_address_iterator& a, + const basic_address_iterator& b) + { + return a.address_ != b.address_; + } + +private: + address_v4 address_; +}; + +/// An input iterator that can be used for traversing IPv4 addresses. +typedef basic_address_iterator address_v4_iterator; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ADDRESS_V4_ITERATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_range.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_range.hpp new file mode 100644 index 00000000..369e395b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v4_range.hpp @@ -0,0 +1,134 @@ +// +// ip/address_v4_range.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V4_RANGE_HPP +#define ASIO_IP_ADDRESS_V4_RANGE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/address_v4_iterator.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template class basic_address_range; + +/// Represents a range of IPv4 addresses. +/** + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template <> class basic_address_range +{ +public: + /// The type of an iterator that points into the range. + typedef basic_address_iterator iterator; + + /// Construct an empty range. + basic_address_range() ASIO_NOEXCEPT + : begin_(address_v4()), + end_(address_v4()) + { + } + + /// Construct an range that represents the given range of addresses. + explicit basic_address_range(const iterator& first, + const iterator& last) ASIO_NOEXCEPT + : begin_(first), + end_(last) + { + } + + /// Copy constructor. + basic_address_range(const basic_address_range& other) ASIO_NOEXCEPT + : begin_(other.begin_), + end_(other.end_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_address_range(basic_address_range&& other) ASIO_NOEXCEPT + : begin_(ASIO_MOVE_CAST(iterator)(other.begin_)), + end_(ASIO_MOVE_CAST(iterator)(other.end_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assignment operator. + basic_address_range& operator=( + const basic_address_range& other) ASIO_NOEXCEPT + { + begin_ = other.begin_; + end_ = other.end_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move assignment operator. + basic_address_range& operator=( + basic_address_range&& other) ASIO_NOEXCEPT + { + begin_ = ASIO_MOVE_CAST(iterator)(other.begin_); + end_ = ASIO_MOVE_CAST(iterator)(other.end_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Obtain an iterator that points to the start of the range. + iterator begin() const ASIO_NOEXCEPT + { + return begin_; + } + + /// Obtain an iterator that points to the end of the range. + iterator end() const ASIO_NOEXCEPT + { + return end_; + } + + /// Determine whether the range is empty. + bool empty() const ASIO_NOEXCEPT + { + return size() == 0; + } + + /// Return the size of the range. + std::size_t size() const ASIO_NOEXCEPT + { + return end_->to_uint() - begin_->to_uint(); + } + + /// Find an address in the range. + iterator find(const address_v4& addr) const ASIO_NOEXCEPT + { + return addr >= *begin_ && addr < *end_ ? iterator(addr) : end_; + } + +private: + iterator begin_; + iterator end_; +}; + +/// Represents a range of IPv4 addresses. +typedef basic_address_range address_v4_range; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ADDRESS_V4_RANGE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6.hpp new file mode 100644 index 00000000..db3af3c4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6.hpp @@ -0,0 +1,341 @@ +// +// ip/address_v6.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V6_HPP +#define ASIO_IP_ADDRESS_V6_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/array.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/winsock_init.hpp" +#include "asio/error_code.hpp" +#include "asio/ip/address_v4.hpp" + +#if !defined(ASIO_NO_IOSTREAM) +# include +#endif // !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template class basic_address_iterator; + +/// Implements IP version 6 style addresses. +/** + * The asio::ip::address_v6 class provides the ability to use and + * manipulate IP version 6 addresses. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class address_v6 +{ +public: + /// The type used to represent an address as an array of bytes. + /** + * @note This type is defined in terms of the C++0x template @c std::array + * when it is available. Otherwise, it uses @c boost:array. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef array bytes_type; +#else + typedef asio::detail::array bytes_type; +#endif + + /// Default constructor. + ASIO_DECL address_v6() ASIO_NOEXCEPT; + + /// Construct an address from raw bytes and scope ID. + ASIO_DECL explicit address_v6(const bytes_type& bytes, + unsigned long scope_id = 0); + + /// Copy constructor. + ASIO_DECL address_v6(const address_v6& other) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + ASIO_DECL address_v6(address_v6&& other) ASIO_NOEXCEPT; +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another address. + ASIO_DECL address_v6& operator=( + const address_v6& other) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another address. + ASIO_DECL address_v6& operator=(address_v6&& other) ASIO_NOEXCEPT; +#endif // defined(ASIO_HAS_MOVE) + + /// The scope ID of the address. + /** + * Returns the scope ID associated with the IPv6 address. + */ + unsigned long scope_id() const ASIO_NOEXCEPT + { + return scope_id_; + } + + /// The scope ID of the address. + /** + * Modifies the scope ID associated with the IPv6 address. + */ + void scope_id(unsigned long id) ASIO_NOEXCEPT + { + scope_id_ = id; + } + + /// Get the address in bytes, in network byte order. + ASIO_DECL bytes_type to_bytes() const ASIO_NOEXCEPT; + + /// Get the address as a string. + ASIO_DECL std::string to_string() const; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use other overload.) Get the address as a string. + ASIO_DECL std::string to_string(asio::error_code& ec) const; + + /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP + /// address string. + static address_v6 from_string(const char* str); + + /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP + /// address string. + static address_v6 from_string( + const char* str, asio::error_code& ec); + + /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP + /// address string. + static address_v6 from_string(const std::string& str); + + /// (Deprecated: Use make_address_v6().) Create an IPv6 address from an IP + /// address string. + static address_v6 from_string( + const std::string& str, asio::error_code& ec); + + /// (Deprecated: Use make_address_v4().) Converts an IPv4-mapped or + /// IPv4-compatible address to an IPv4 address. + ASIO_DECL address_v4 to_v4() const; +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the address is a loopback address. + ASIO_DECL bool is_loopback() const ASIO_NOEXCEPT; + + /// Determine whether the address is unspecified. + ASIO_DECL bool is_unspecified() const ASIO_NOEXCEPT; + + /// Determine whether the address is link local. + ASIO_DECL bool is_link_local() const ASIO_NOEXCEPT; + + /// Determine whether the address is site local. + ASIO_DECL bool is_site_local() const ASIO_NOEXCEPT; + + /// Determine whether the address is a mapped IPv4 address. + ASIO_DECL bool is_v4_mapped() const ASIO_NOEXCEPT; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: No replacement.) Determine whether the address is an + /// IPv4-compatible address. + ASIO_DECL bool is_v4_compatible() const; +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Determine whether the address is a multicast address. + ASIO_DECL bool is_multicast() const ASIO_NOEXCEPT; + + /// Determine whether the address is a global multicast address. + ASIO_DECL bool is_multicast_global() const ASIO_NOEXCEPT; + + /// Determine whether the address is a link-local multicast address. + ASIO_DECL bool is_multicast_link_local() const ASIO_NOEXCEPT; + + /// Determine whether the address is a node-local multicast address. + ASIO_DECL bool is_multicast_node_local() const ASIO_NOEXCEPT; + + /// Determine whether the address is a org-local multicast address. + ASIO_DECL bool is_multicast_org_local() const ASIO_NOEXCEPT; + + /// Determine whether the address is a site-local multicast address. + ASIO_DECL bool is_multicast_site_local() const ASIO_NOEXCEPT; + + /// Compare two addresses for equality. + ASIO_DECL friend bool operator==(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT; + + /// Compare two addresses for inequality. + friend bool operator!=(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT + { + return !(a1 == a2); + } + + /// Compare addresses for ordering. + ASIO_DECL friend bool operator<(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT; + + /// Compare addresses for ordering. + friend bool operator>(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT + { + return a2 < a1; + } + + /// Compare addresses for ordering. + friend bool operator<=(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT + { + return !(a2 < a1); + } + + /// Compare addresses for ordering. + friend bool operator>=(const address_v6& a1, + const address_v6& a2) ASIO_NOEXCEPT + { + return !(a1 < a2); + } + + /// Obtain an address object that represents any address. + static address_v6 any() ASIO_NOEXCEPT + { + return address_v6(); + } + + /// Obtain an address object that represents the loopback address. + ASIO_DECL static address_v6 loopback() ASIO_NOEXCEPT; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use make_address_v6().) Create an IPv4-mapped IPv6 address. + ASIO_DECL static address_v6 v4_mapped(const address_v4& addr); + + /// (Deprecated: No replacement.) Create an IPv4-compatible IPv6 address. + ASIO_DECL static address_v6 v4_compatible(const address_v4& addr); +#endif // !defined(ASIO_NO_DEPRECATED) + +private: + friend class basic_address_iterator; + + // The underlying IPv6 address. + asio::detail::in6_addr_type addr_; + + // The scope ID associated with the address. + unsigned long scope_id_; +}; + +/// Create an IPv6 address from raw bytes and scope ID. +/** + * @relates address_v6 + */ +inline address_v6 make_address_v6(const address_v6::bytes_type& bytes, + unsigned long scope_id = 0) +{ + return address_v6(bytes, scope_id); +} + +/// Create an IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(const char* str); + +/// Create an IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(const char* str, + asio::error_code& ec) ASIO_NOEXCEPT; + +/// Createan IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(const std::string& str); + +/// Create an IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(const std::string& str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create an IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(string_view str); + +/// Create an IPv6 address from an IP address string. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6(string_view str, + asio::error_code& ec) ASIO_NOEXCEPT; + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +/// Tag type used for distinguishing overloads that deal in IPv4-mapped IPv6 +/// addresses. +enum v4_mapped_t { v4_mapped }; + +/// Create an IPv4 address from a IPv4-mapped IPv6 address. +/** + * @relates address_v4 + */ +ASIO_DECL address_v4 make_address_v4( + v4_mapped_t, const address_v6& v6_addr); + +/// Create an IPv4-mapped IPv6 address from an IPv4 address. +/** + * @relates address_v6 + */ +ASIO_DECL address_v6 make_address_v6( + v4_mapped_t, const address_v4& v4_addr); + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output an address as a string. +/** + * Used to output a human-readable string for a specified address. + * + * @param os The output stream to which the string will be written. + * + * @param addr The address to be written. + * + * @return The output stream. + * + * @relates asio::ip::address_v6 + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address_v6& addr); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/address_v6.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/address_v6.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_ADDRESS_V6_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_iterator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_iterator.hpp new file mode 100644 index 00000000..ba127961 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_iterator.hpp @@ -0,0 +1,183 @@ +// +// ip/address_v6_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Oliver Kowalke (oliver dot kowalke at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V6_ITERATOR_HPP +#define ASIO_IP_ADDRESS_V6_ITERATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/address_v6.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template class basic_address_iterator; + +/// An input iterator that can be used for traversing IPv6 addresses. +/** + * In addition to satisfying the input iterator requirements, this iterator + * also supports decrement. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template <> class basic_address_iterator +{ +public: + /// The type of the elements pointed to by the iterator. + typedef address_v6 value_type; + + /// Distance between two iterators. + typedef std::ptrdiff_t difference_type; + + /// The type of a pointer to an element pointed to by the iterator. + typedef const address_v6* pointer; + + /// The type of a reference to an element pointed to by the iterator. + typedef const address_v6& reference; + + /// Denotes that the iterator satisfies the input iterator requirements. + typedef std::input_iterator_tag iterator_category; + + /// Construct an iterator that points to the specified address. + basic_address_iterator(const address_v6& addr) ASIO_NOEXCEPT + : address_(addr) + { + } + + /// Copy constructor. + basic_address_iterator( + const basic_address_iterator& other) ASIO_NOEXCEPT + : address_(other.address_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_address_iterator(basic_address_iterator&& other) ASIO_NOEXCEPT + : address_(ASIO_MOVE_CAST(address_v6)(other.address_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assignment operator. + basic_address_iterator& operator=( + const basic_address_iterator& other) ASIO_NOEXCEPT + { + address_ = other.address_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move assignment operator. + basic_address_iterator& operator=( + basic_address_iterator&& other) ASIO_NOEXCEPT + { + address_ = ASIO_MOVE_CAST(address_v6)(other.address_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Dereference the iterator. + const address_v6& operator*() const ASIO_NOEXCEPT + { + return address_; + } + + /// Dereference the iterator. + const address_v6* operator->() const ASIO_NOEXCEPT + { + return &address_; + } + + /// Pre-increment operator. + basic_address_iterator& operator++() ASIO_NOEXCEPT + { + for (int i = 15; i >= 0; --i) + { + if (address_.addr_.s6_addr[i] < 0xFF) + { + ++address_.addr_.s6_addr[i]; + break; + } + + address_.addr_.s6_addr[i] = 0; + } + + return *this; + } + + /// Post-increment operator. + basic_address_iterator operator++(int) ASIO_NOEXCEPT + { + basic_address_iterator tmp(*this); + ++*this; + return tmp; + } + + /// Pre-decrement operator. + basic_address_iterator& operator--() ASIO_NOEXCEPT + { + for (int i = 15; i >= 0; --i) + { + if (address_.addr_.s6_addr[i] > 0) + { + --address_.addr_.s6_addr[i]; + break; + } + + address_.addr_.s6_addr[i] = 0xFF; + } + + return *this; + } + + /// Post-decrement operator. + basic_address_iterator operator--(int) + { + basic_address_iterator tmp(*this); + --*this; + return tmp; + } + + /// Compare two addresses for equality. + friend bool operator==(const basic_address_iterator& a, + const basic_address_iterator& b) + { + return a.address_ == b.address_; + } + + /// Compare two addresses for inequality. + friend bool operator!=(const basic_address_iterator& a, + const basic_address_iterator& b) + { + return a.address_ != b.address_; + } + +private: + address_v6 address_; +}; + +/// An input iterator that can be used for traversing IPv6 addresses. +typedef basic_address_iterator address_v6_iterator; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ADDRESS_V6_ITERATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_range.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_range.hpp new file mode 100644 index 00000000..7a461dd9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/address_v6_range.hpp @@ -0,0 +1,129 @@ +// +// ip/address_v6_range.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Oliver Kowalke (oliver dot kowalke at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ADDRESS_V6_RANGE_HPP +#define ASIO_IP_ADDRESS_V6_RANGE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/address_v6_iterator.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template class basic_address_range; + +/// Represents a range of IPv6 addresses. +/** + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template <> class basic_address_range +{ +public: + /// The type of an iterator that points into the range. + typedef basic_address_iterator iterator; + + /// Construct an empty range. + basic_address_range() ASIO_NOEXCEPT + : begin_(address_v6()), + end_(address_v6()) + { + } + + /// Construct an range that represents the given range of addresses. + explicit basic_address_range(const iterator& first, + const iterator& last) ASIO_NOEXCEPT + : begin_(first), + end_(last) + { + } + + /// Copy constructor. + basic_address_range(const basic_address_range& other) ASIO_NOEXCEPT + : begin_(other.begin_), + end_(other.end_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_address_range(basic_address_range&& other) ASIO_NOEXCEPT + : begin_(ASIO_MOVE_CAST(iterator)(other.begin_)), + end_(ASIO_MOVE_CAST(iterator)(other.end_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assignment operator. + basic_address_range& operator=( + const basic_address_range& other) ASIO_NOEXCEPT + { + begin_ = other.begin_; + end_ = other.end_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move assignment operator. + basic_address_range& operator=( + basic_address_range&& other) ASIO_NOEXCEPT + { + begin_ = ASIO_MOVE_CAST(iterator)(other.begin_); + end_ = ASIO_MOVE_CAST(iterator)(other.end_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Obtain an iterator that points to the start of the range. + iterator begin() const ASIO_NOEXCEPT + { + return begin_; + } + + /// Obtain an iterator that points to the end of the range. + iterator end() const ASIO_NOEXCEPT + { + return end_; + } + + /// Determine whether the range is empty. + bool empty() const ASIO_NOEXCEPT + { + return begin_ == end_; + } + + /// Find an address in the range. + iterator find(const address_v6& addr) const ASIO_NOEXCEPT + { + return addr >= *begin_ && addr < *end_ ? iterator(addr) : end_; + } + +private: + iterator begin_; + iterator end_; +}; + +/// Represents a range of IPv6 addresses. +typedef basic_address_range address_v6_range; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ADDRESS_V6_RANGE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/bad_address_cast.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/bad_address_cast.hpp new file mode 100644 index 00000000..32fda742 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/bad_address_cast.hpp @@ -0,0 +1,53 @@ +// +// ip/bad_address_cast.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BAD_ADDRESS_CAST_HPP +#define ASIO_IP_BAD_ADDRESS_CAST_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Thrown to indicate a failed address conversion. +class bad_address_cast : +#if defined(ASIO_MSVC) && defined(_HAS_EXCEPTIONS) && !_HAS_EXCEPTIONS + public std::exception +#else + public std::bad_cast +#endif +{ +public: + /// Default constructor. + bad_address_cast() {} + + /// Destructor. + virtual ~bad_address_cast() ASIO_NOEXCEPT_OR_NOTHROW {} + + /// Get the message associated with the exception. + virtual const char* what() const ASIO_NOEXCEPT_OR_NOTHROW + { + return "bad address cast"; + } +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ADDRESS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_endpoint.hpp new file mode 100644 index 00000000..92e02a91 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_endpoint.hpp @@ -0,0 +1,264 @@ +// +// ip/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_ENDPOINT_HPP +#define ASIO_IP_BASIC_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/address.hpp" +#include "asio/ip/detail/endpoint.hpp" + +#if !defined(ASIO_NO_IOSTREAM) +# include +#endif // !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Describes an endpoint for a version-independent IP socket. +/** + * The asio::ip::basic_endpoint class template describes an endpoint that + * may be associated with a particular socket. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * Endpoint. + */ +template +class basic_endpoint +{ +public: + /// The protocol type associated with the endpoint. + typedef InternetProtocol protocol_type; + + /// The type of the endpoint structure. This type is dependent on the + /// underlying implementation of the socket layer. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined data_type; +#else + typedef asio::detail::socket_addr_type data_type; +#endif + + /// Default constructor. + basic_endpoint() ASIO_NOEXCEPT + : impl_() + { + } + + /// Construct an endpoint using a port number, specified in the host's byte + /// order. The IP address will be the any address (i.e. INADDR_ANY or + /// in6addr_any). This constructor would typically be used for accepting new + /// connections. + /** + * @par Examples + * To initialise an IPv4 TCP endpoint for port 1234, use: + * @code + * asio::ip::tcp::endpoint ep(asio::ip::tcp::v4(), 1234); + * @endcode + * + * To specify an IPv6 UDP endpoint for port 9876, use: + * @code + * asio::ip::udp::endpoint ep(asio::ip::udp::v6(), 9876); + * @endcode + */ + basic_endpoint(const InternetProtocol& internet_protocol, + unsigned short port_num) ASIO_NOEXCEPT + : impl_(internet_protocol.family(), port_num) + { + } + + /// Construct an endpoint using a port number and an IP address. This + /// constructor may be used for accepting connections on a specific interface + /// or for making a connection to a remote endpoint. + basic_endpoint(const asio::ip::address& addr, + unsigned short port_num) ASIO_NOEXCEPT + : impl_(addr, port_num) + { + } + + /// Copy constructor. + basic_endpoint(const basic_endpoint& other) ASIO_NOEXCEPT + : impl_(other.impl_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + basic_endpoint(basic_endpoint&& other) ASIO_NOEXCEPT + : impl_(other.impl_) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Assign from another endpoint. + basic_endpoint& operator=(const basic_endpoint& other) ASIO_NOEXCEPT + { + impl_ = other.impl_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-assign from another endpoint. + basic_endpoint& operator=(basic_endpoint&& other) ASIO_NOEXCEPT + { + impl_ = other.impl_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// The protocol associated with the endpoint. + protocol_type protocol() const ASIO_NOEXCEPT + { + if (impl_.is_v4()) + return InternetProtocol::v4(); + return InternetProtocol::v6(); + } + + /// Get the underlying endpoint in the native type. + data_type* data() ASIO_NOEXCEPT + { + return impl_.data(); + } + + /// Get the underlying endpoint in the native type. + const data_type* data() const ASIO_NOEXCEPT + { + return impl_.data(); + } + + /// Get the underlying size of the endpoint in the native type. + std::size_t size() const ASIO_NOEXCEPT + { + return impl_.size(); + } + + /// Set the underlying size of the endpoint in the native type. + void resize(std::size_t new_size) + { + impl_.resize(new_size); + } + + /// Get the capacity of the endpoint in the native type. + std::size_t capacity() const ASIO_NOEXCEPT + { + return impl_.capacity(); + } + + /// Get the port associated with the endpoint. The port number is always in + /// the host's byte order. + unsigned short port() const ASIO_NOEXCEPT + { + return impl_.port(); + } + + /// Set the port associated with the endpoint. The port number is always in + /// the host's byte order. + void port(unsigned short port_num) ASIO_NOEXCEPT + { + impl_.port(port_num); + } + + /// Get the IP address associated with the endpoint. + asio::ip::address address() const ASIO_NOEXCEPT + { + return impl_.address(); + } + + /// Set the IP address associated with the endpoint. + void address(const asio::ip::address& addr) ASIO_NOEXCEPT + { + impl_.address(addr); + } + + /// Compare two endpoints for equality. + friend bool operator==(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return e1.impl_ == e2.impl_; + } + + /// Compare two endpoints for inequality. + friend bool operator!=(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return !(e1 == e2); + } + + /// Compare endpoints for ordering. + friend bool operator<(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return e1.impl_ < e2.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator>(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return e2.impl_ < e1.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator<=(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return !(e2 < e1); + } + + /// Compare endpoints for ordering. + friend bool operator>=(const basic_endpoint& e1, + const basic_endpoint& e2) ASIO_NOEXCEPT + { + return !(e1 < e2); + } + +private: + // The underlying IP endpoint. + asio::ip::detail::endpoint impl_; +}; + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output an endpoint as a string. +/** + * Used to output a human-readable string for a specified endpoint. + * + * @param os The output stream to which the string will be written. + * + * @param endpoint The endpoint to be written. + * + * @return The output stream. + * + * @relates asio::ip::basic_endpoint + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const basic_endpoint& endpoint); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/basic_endpoint.hpp" + +#endif // ASIO_IP_BASIC_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver.hpp new file mode 100644 index 00000000..c5a9229b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver.hpp @@ -0,0 +1,1030 @@ +// +// ip/basic_resolver.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_RESOLVER_HPP +#define ASIO_IP_BASIC_RESOLVER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_results.hpp" +#include "asio/ip/resolver_base.hpp" +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_resolver_service.hpp" +#else +# include "asio/detail/resolver_service.hpp" +#endif + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +#if !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) +#define ASIO_IP_BASIC_RESOLVER_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_resolver; + +#endif // !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) + +/// Provides endpoint resolution functionality. +/** + * The basic_resolver class template provides the ability to resolve a query + * to a list of endpoints. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_resolver + : public resolver_base +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the resolver type to another executor. + template + struct rebind_executor + { + /// The resolver type when rebound to the specified executor. + typedef basic_resolver other; + }; + + /// The protocol type. + typedef InternetProtocol protocol_type; + + /// The endpoint type. + typedef typename InternetProtocol::endpoint endpoint_type; + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated.) The query type. + typedef basic_resolver_query query; + + /// (Deprecated.) The iterator type. + typedef basic_resolver_iterator iterator; +#endif // !defined(ASIO_NO_DEPRECATED) + + /// The results type. + typedef basic_resolver_results results_type; + + /// Construct with executor. + /** + * This constructor creates a basic_resolver. + * + * @param ex The I/O executor that the resolver will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * resolver. + */ + explicit basic_resolver(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct with execution context. + /** + * This constructor creates a basic_resolver. + * + * @param context An execution context which provides the I/O executor that + * the resolver will use, by default, to dispatch handlers for any + * asynchronous operations performed on the resolver. + */ + template + explicit basic_resolver(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a basic_resolver from another. + /** + * This constructor moves a resolver from one object to another. + * + * @param other The other basic_resolver object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_resolver(const executor_type&) constructor. + */ + basic_resolver(basic_resolver&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a basic_resolver from another. + /** + * This assignment operator moves a resolver from one object to another. + * Cancels any outstanding asynchronous operations associated with the target + * object. + * + * @param other The other basic_resolver object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_resolver(const executor_type&) constructor. + */ + basic_resolver& operator=(basic_resolver&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destroys the resolver. + /** + * This function destroys the resolver, cancelling any outstanding + * asynchronous wait operations associated with the resolver as if by calling + * @c cancel. + */ + ~basic_resolver() + { + } + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Cancel any asynchronous operations that are waiting on the resolver. + /** + * This function forces the completion of any pending asynchronous + * operations on the host resolver. The handler for each cancelled operation + * will be invoked with the asio::error::operation_aborted error code. + */ + void cancel() + { + return impl_.get_service().cancel(impl_.get_implementation()); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use overload with separate host and service parameters.) + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve a query into a list of endpoint entries. + * + * @param q A query object that determines what endpoints will be returned. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + */ + results_type resolve(const query& q) + { + asio::error_code ec; + results_type r = impl_.get_service().resolve( + impl_.get_implementation(), q, ec); + asio::detail::throw_error(ec, "resolve"); + return r; + } + + /// (Deprecated: Use overload with separate host and service parameters.) + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve a query into a list of endpoint entries. + * + * @param q A query object that determines what endpoints will be returned. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + */ + results_type resolve(const query& q, asio::error_code& ec) + { + return impl_.get_service().resolve(impl_.get_implementation(), q, ec); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service) + { + return resolve(host, service, resolver_base::flags()); + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service, asio::error_code& ec) + { + return resolve(host, service, resolver_base::flags(), ec); + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service, resolver_base::flags resolve_flags) + { + asio::error_code ec; + basic_resolver_query q(static_cast(host), + static_cast(service), resolve_flags); + results_type r = impl_.get_service().resolve( + impl_.get_implementation(), q, ec); + asio::detail::throw_error(ec, "resolve"); + return r; + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service, resolver_base::flags resolve_flags, + asio::error_code& ec) + { + basic_resolver_query q(static_cast(host), + static_cast(service), resolve_flags); + return impl_.get_service().resolve(impl_.get_implementation(), q, ec); + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service) + { + return resolve(protocol, host, service, resolver_base::flags()); + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service, + asio::error_code& ec) + { + return resolve(protocol, host, service, resolver_base::flags(), ec); + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service, + resolver_base::flags resolve_flags) + { + asio::error_code ec; + basic_resolver_query q( + protocol, static_cast(host), + static_cast(service), resolve_flags); + results_type r = impl_.get_service().resolve( + impl_.get_implementation(), q, ec); + asio::detail::throw_error(ec, "resolve"); + return r; + } + + /// Perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + results_type resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service, + resolver_base::flags resolve_flags, asio::error_code& ec) + { + basic_resolver_query q( + protocol, static_cast(host), + static_cast(service), resolve_flags); + return impl_.get_service().resolve(impl_.get_implementation(), q, ec); + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use overload with separate host and service parameters.) + /// Asynchronously perform forward resolution of a query to a list of entries. + /** + * This function is used to asynchronously resolve a query into a list of + * endpoint entries. + * + * @param q A query object that determines what endpoints will be returned. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const query& q, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return asio::async_initiate( + initiate_async_resolve(this), handler, q); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Asynchronously perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_resolve(host, service, resolver_base::flags(), + ASIO_MOVE_CAST(ResolveHandler)(handler)); + } + + /// Asynchronously perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(ASIO_STRING_VIEW_PARAM host, + ASIO_STRING_VIEW_PARAM service, + resolver_base::flags resolve_flags, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + basic_resolver_query q(static_cast(host), + static_cast(service), resolve_flags); + + return asio::async_initiate( + initiate_async_resolve(this), handler, q); + } + + /// Asynchronously perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_resolve(protocol, host, service, resolver_base::flags(), + ASIO_MOVE_CAST(ResolveHandler)(handler)); + } + + /// Asynchronously perform forward resolution of a query to a list of entries. + /** + * This function is used to resolve host and service names into a list of + * endpoint entries. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. See the @ref resolver_base documentation for the set of + * available flags. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const protocol_type& protocol, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service, + resolver_base::flags resolve_flags, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + basic_resolver_query q( + protocol, static_cast(host), + static_cast(service), resolve_flags); + + return asio::async_initiate( + initiate_async_resolve(this), handler, q); + } + + /// Perform reverse resolution of an endpoint to a list of entries. + /** + * This function is used to resolve an endpoint into a list of endpoint + * entries. + * + * @param e An endpoint object that determines what endpoints will be + * returned. + * + * @returns A range object representing the list of endpoint entries. A + * successful call to this function is guaranteed to return a non-empty + * range. + * + * @throws asio::system_error Thrown on failure. + */ + results_type resolve(const endpoint_type& e) + { + asio::error_code ec; + results_type i = impl_.get_service().resolve( + impl_.get_implementation(), e, ec); + asio::detail::throw_error(ec, "resolve"); + return i; + } + + /// Perform reverse resolution of an endpoint to a list of entries. + /** + * This function is used to resolve an endpoint into a list of endpoint + * entries. + * + * @param e An endpoint object that determines what endpoints will be + * returned. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns A range object representing the list of endpoint entries. An + * empty range is returned if an error occurs. A successful call to this + * function is guaranteed to return a non-empty range. + */ + results_type resolve(const endpoint_type& e, asio::error_code& ec) + { + return impl_.get_service().resolve(impl_.get_implementation(), e, ec); + } + + /// Asynchronously perform reverse resolution of an endpoint to a list of + /// entries. + /** + * This function is used to asynchronously resolve an endpoint into a list of + * endpoint entries. + * + * @param e An endpoint object that determines what endpoints will be + * returned. + * + * @param handler The handler to be called when the resolve operation + * completes. Copies will be made of the handler as required. The function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * resolver::results_type results // Resolved endpoints as a range. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * A successful resolve operation is guaranteed to pass a non-empty range to + * the handler. + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, + results_type)) ResolveHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ResolveHandler, + void (asio::error_code, results_type)) + async_resolve(const endpoint_type& e, + ASIO_MOVE_ARG(ResolveHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return asio::async_initiate( + initiate_async_resolve(this), handler, e); + } + +private: + // Disallow copying and assignment. + basic_resolver(const basic_resolver&) ASIO_DELETED; + basic_resolver& operator=(const basic_resolver&) ASIO_DELETED; + + class initiate_async_resolve + { + public: + typedef Executor executor_type; + + explicit initiate_async_resolve(basic_resolver* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ResolveHandler) handler, + const Query& q) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ResolveHandler. + ASIO_RESOLVE_HANDLER_CHECK( + ResolveHandler, handler, results_type) type_check; + + asio::detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_resolve( + self_->impl_.get_implementation(), q, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_resolver* self_; + }; + +# if defined(ASIO_WINDOWS_RUNTIME) + asio::detail::io_object_impl< + asio::detail::winrt_resolver_service, + Executor> impl_; +# else + asio::detail::io_object_impl< + asio::detail::resolver_service, + Executor> impl_; +# endif +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_BASIC_RESOLVER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_entry.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_entry.hpp new file mode 100644 index 00000000..a5a14589 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_entry.hpp @@ -0,0 +1,113 @@ +// +// ip/basic_resolver_entry.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_RESOLVER_ENTRY_HPP +#define ASIO_IP_BASIC_RESOLVER_ENTRY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/string_view.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// An entry produced by a resolver. +/** + * The asio::ip::basic_resolver_entry class template describes an entry + * as returned by a resolver. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_resolver_entry +{ +public: + /// The protocol type associated with the endpoint entry. + typedef InternetProtocol protocol_type; + + /// The endpoint type associated with the endpoint entry. + typedef typename InternetProtocol::endpoint endpoint_type; + + /// Default constructor. + basic_resolver_entry() + { + } + + /// Construct with specified endpoint, host name and service name. + basic_resolver_entry(const endpoint_type& ep, + ASIO_STRING_VIEW_PARAM host, ASIO_STRING_VIEW_PARAM service) + : endpoint_(ep), + host_name_(static_cast(host)), + service_name_(static_cast(service)) + { + } + + /// Get the endpoint associated with the entry. + endpoint_type endpoint() const + { + return endpoint_; + } + + /// Convert to the endpoint associated with the entry. + operator endpoint_type() const + { + return endpoint_; + } + + /// Get the host name associated with the entry. + std::string host_name() const + { + return host_name_; + } + + /// Get the host name associated with the entry. + template + std::basic_string, Allocator> host_name( + const Allocator& alloc = Allocator()) const + { + return std::basic_string, Allocator>( + host_name_.c_str(), alloc); + } + + /// Get the service name associated with the entry. + std::string service_name() const + { + return service_name_; + } + + /// Get the service name associated with the entry. + template + std::basic_string, Allocator> service_name( + const Allocator& alloc = Allocator()) const + { + return std::basic_string, Allocator>( + service_name_.c_str(), alloc); + } + +private: + endpoint_type endpoint_; + std::string host_name_; + std::string service_name_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_BASIC_RESOLVER_ENTRY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_iterator.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_iterator.hpp new file mode 100644 index 00000000..aa9f8fd7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_iterator.hpp @@ -0,0 +1,192 @@ +// +// ip/basic_resolver_iterator.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP +#define ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include +#include +#include "asio/detail/memory.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/ip/basic_resolver_entry.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_utils.hpp" +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// An iterator over the entries produced by a resolver. +/** + * The asio::ip::basic_resolver_iterator class template is used to define + * iterators over the results returned by a resolver. + * + * The iterator's value_type, obtained when the iterator is dereferenced, is: + * @code const basic_resolver_entry @endcode + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_resolver_iterator +{ +public: + /// The type used for the distance between two iterators. + typedef std::ptrdiff_t difference_type; + + /// The type of the value pointed to by the iterator. + typedef basic_resolver_entry value_type; + + /// The type of the result of applying operator->() to the iterator. + typedef const basic_resolver_entry* pointer; + + /// The type of the result of applying operator*() to the iterator. + typedef const basic_resolver_entry& reference; + + /// The iterator category. + typedef std::forward_iterator_tag iterator_category; + + /// Default constructor creates an end iterator. + basic_resolver_iterator() + : index_(0) + { + } + + /// Copy constructor. + basic_resolver_iterator(const basic_resolver_iterator& other) + : values_(other.values_), + index_(other.index_) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + basic_resolver_iterator(basic_resolver_iterator&& other) + : values_(ASIO_MOVE_CAST(values_ptr_type)(other.values_)), + index_(other.index_) + { + other.index_ = 0; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Assignment operator. + basic_resolver_iterator& operator=(const basic_resolver_iterator& other) + { + values_ = other.values_; + index_ = other.index_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-assignment operator. + basic_resolver_iterator& operator=(basic_resolver_iterator&& other) + { + if (this != &other) + { + values_ = ASIO_MOVE_CAST(values_ptr_type)(other.values_); + index_ = other.index_; + other.index_ = 0; + } + + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Dereference an iterator. + const basic_resolver_entry& operator*() const + { + return dereference(); + } + + /// Dereference an iterator. + const basic_resolver_entry* operator->() const + { + return &dereference(); + } + + /// Increment operator (prefix). + basic_resolver_iterator& operator++() + { + increment(); + return *this; + } + + /// Increment operator (postfix). + basic_resolver_iterator operator++(int) + { + basic_resolver_iterator tmp(*this); + ++*this; + return tmp; + } + + /// Test two iterators for equality. + friend bool operator==(const basic_resolver_iterator& a, + const basic_resolver_iterator& b) + { + return a.equal(b); + } + + /// Test two iterators for inequality. + friend bool operator!=(const basic_resolver_iterator& a, + const basic_resolver_iterator& b) + { + return !a.equal(b); + } + +protected: + void increment() + { + if (++index_ == values_->size()) + { + // Reset state to match a default constructed end iterator. + values_.reset(); + index_ = 0; + } + } + + bool equal(const basic_resolver_iterator& other) const + { + if (!values_ && !other.values_) + return true; + if (values_ != other.values_) + return false; + return index_ == other.index_; + } + + const basic_resolver_entry& dereference() const + { + return (*values_)[index_]; + } + + typedef std::vector > values_type; + typedef asio::detail::shared_ptr values_ptr_type; + values_ptr_type values_; + std::size_t index_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_query.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_query.hpp new file mode 100644 index 00000000..c8c49d63 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_query.hpp @@ -0,0 +1,244 @@ +// +// ip/basic_resolver_query.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_RESOLVER_QUERY_HPP +#define ASIO_IP_BASIC_RESOLVER_QUERY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/socket_ops.hpp" +#include "asio/ip/resolver_query_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// An query to be passed to a resolver. +/** + * The asio::ip::basic_resolver_query class template describes a query + * that can be passed to a resolver. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_resolver_query + : public resolver_query_base +{ +public: + /// The protocol type associated with the endpoint query. + typedef InternetProtocol protocol_type; + + /// Construct with specified service name for any protocol. + /** + * This constructor is typically used to perform name resolution for local + * service binding. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for local service + * binding. + * + * @note On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + basic_resolver_query(const std::string& service, + resolver_query_base::flags resolve_flags = passive | address_configured) + : hints_(), + host_name_(), + service_name_(service) + { + typename InternetProtocol::endpoint endpoint; + hints_.ai_flags = static_cast(resolve_flags); + hints_.ai_family = PF_UNSPEC; + hints_.ai_socktype = endpoint.protocol().type(); + hints_.ai_protocol = endpoint.protocol().protocol(); + hints_.ai_addrlen = 0; + hints_.ai_canonname = 0; + hints_.ai_addr = 0; + hints_.ai_next = 0; + } + + /// Construct with specified service name for a given protocol. + /** + * This constructor is typically used to perform name resolution for local + * service binding with a specific protocol version. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for local service + * binding. + * + * @note On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + basic_resolver_query(const protocol_type& protocol, + const std::string& service, + resolver_query_base::flags resolve_flags = passive | address_configured) + : hints_(), + host_name_(), + service_name_(service) + { + hints_.ai_flags = static_cast(resolve_flags); + hints_.ai_family = protocol.family(); + hints_.ai_socktype = protocol.type(); + hints_.ai_protocol = protocol.protocol(); + hints_.ai_addrlen = 0; + hints_.ai_canonname = 0; + hints_.ai_addr = 0; + hints_.ai_next = 0; + } + + /// Construct with specified host name and service name for any protocol. + /** + * This constructor is typically used to perform name resolution for + * communication with remote hosts. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + basic_resolver_query(const std::string& host, const std::string& service, + resolver_query_base::flags resolve_flags = address_configured) + : hints_(), + host_name_(host), + service_name_(service) + { + typename InternetProtocol::endpoint endpoint; + hints_.ai_flags = static_cast(resolve_flags); + hints_.ai_family = ASIO_OS_DEF(AF_UNSPEC); + hints_.ai_socktype = endpoint.protocol().type(); + hints_.ai_protocol = endpoint.protocol().protocol(); + hints_.ai_addrlen = 0; + hints_.ai_canonname = 0; + hints_.ai_addr = 0; + hints_.ai_next = 0; + } + + /// Construct with specified host name and service name for a given protocol. + /** + * This constructor is typically used to perform name resolution for + * communication with remote hosts. + * + * @param protocol A protocol object, normally representing either the IPv4 or + * IPv6 version of an internet protocol. + * + * @param host A string identifying a location. May be a descriptive name or + * a numeric address string. If an empty string and the passive flag has been + * specified, the resolved endpoints are suitable for local service binding. + * If an empty string and passive is not specified, the resolved endpoints + * will use the loopback address. + * + * @param service A string identifying the requested service. This may be a + * descriptive name or a numeric string corresponding to a port number. May + * be an empty string, in which case all resolved endpoints will have a port + * number of 0. + * + * @param resolve_flags A set of flags that determine how name resolution + * should be performed. The default flags are suitable for communication with + * remote hosts. + * + * @note On POSIX systems, host names may be locally defined in the file + * /etc/hosts. On Windows, host names may be defined in the file + * c:\\windows\\system32\\drivers\\etc\\hosts. Remote host name + * resolution is performed using DNS. Operating systems may use additional + * locations when resolving host names (such as NETBIOS names on Windows). + * + * On POSIX systems, service names are typically defined in the file + * /etc/services. On Windows, service names may be found in the file + * c:\\windows\\system32\\drivers\\etc\\services. Operating systems + * may use additional locations when resolving service names. + */ + basic_resolver_query(const protocol_type& protocol, + const std::string& host, const std::string& service, + resolver_query_base::flags resolve_flags = address_configured) + : hints_(), + host_name_(host), + service_name_(service) + { + hints_.ai_flags = static_cast(resolve_flags); + hints_.ai_family = protocol.family(); + hints_.ai_socktype = protocol.type(); + hints_.ai_protocol = protocol.protocol(); + hints_.ai_addrlen = 0; + hints_.ai_canonname = 0; + hints_.ai_addr = 0; + hints_.ai_next = 0; + } + + /// Get the hints associated with the query. + const asio::detail::addrinfo_type& hints() const + { + return hints_; + } + + /// Get the host name associated with the query. + std::string host_name() const + { + return host_name_; + } + + /// Get the service name associated with the query. + std::string service_name() const + { + return service_name_; + } + +private: + asio::detail::addrinfo_type hints_; + std::string host_name_; + std::string service_name_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_BASIC_RESOLVER_QUERY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_results.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_results.hpp new file mode 100644 index 00000000..3b3fad49 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/basic_resolver_results.hpp @@ -0,0 +1,311 @@ +// +// ip/basic_resolver_results.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_BASIC_RESOLVER_RESULTS_HPP +#define ASIO_IP_BASIC_RESOLVER_RESULTS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" + +#if defined(ASIO_WINDOWS_RUNTIME) +# include "asio/detail/winrt_utils.hpp" +#endif // defined(ASIO_WINDOWS_RUNTIME) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// A range of entries produced by a resolver. +/** + * The asio::ip::basic_resolver_results class template is used to define + * a range over the results returned by a resolver. + * + * The iterator's value_type, obtained when a results iterator is dereferenced, + * is: @code const basic_resolver_entry @endcode + * + * @note For backward compatibility, basic_resolver_results is derived from + * basic_resolver_iterator. This derivation is deprecated. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_resolver_results +#if !defined(ASIO_NO_DEPRECATED) + : public basic_resolver_iterator +#else // !defined(ASIO_NO_DEPRECATED) + : private basic_resolver_iterator +#endif // !defined(ASIO_NO_DEPRECATED) +{ +public: + /// The protocol type associated with the results. + typedef InternetProtocol protocol_type; + + /// The endpoint type associated with the results. + typedef typename protocol_type::endpoint endpoint_type; + + /// The type of a value in the results range. + typedef basic_resolver_entry value_type; + + /// The type of a const reference to a value in the range. + typedef const value_type& const_reference; + + /// The type of a non-const reference to a value in the range. + typedef value_type& reference; + + /// The type of an iterator into the range. + typedef basic_resolver_iterator const_iterator; + + /// The type of an iterator into the range. + typedef const_iterator iterator; + + /// Type used to represent the distance between two iterators in the range. + typedef std::ptrdiff_t difference_type; + + /// Type used to represent a count of the elements in the range. + typedef std::size_t size_type; + + /// Default constructor creates an empty range. + basic_resolver_results() + { + } + + /// Copy constructor. + basic_resolver_results(const basic_resolver_results& other) + : basic_resolver_iterator(other) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + basic_resolver_results(basic_resolver_results&& other) + : basic_resolver_iterator( + ASIO_MOVE_CAST(basic_resolver_results)(other)) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Assignment operator. + basic_resolver_results& operator=(const basic_resolver_results& other) + { + basic_resolver_iterator::operator=(other); + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-assignment operator. + basic_resolver_results& operator=(basic_resolver_results&& other) + { + basic_resolver_iterator::operator=( + ASIO_MOVE_CAST(basic_resolver_results)(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + +#if !defined(GENERATING_DOCUMENTATION) + // Create results from an addrinfo list returned by getaddrinfo. + static basic_resolver_results create( + asio::detail::addrinfo_type* address_info, + const std::string& host_name, const std::string& service_name) + { + basic_resolver_results results; + if (!address_info) + return results; + + std::string actual_host_name = host_name; + if (address_info->ai_canonname) + actual_host_name = address_info->ai_canonname; + + results.values_.reset(new values_type); + + while (address_info) + { + if (address_info->ai_family == ASIO_OS_DEF(AF_INET) + || address_info->ai_family == ASIO_OS_DEF(AF_INET6)) + { + using namespace std; // For memcpy. + typename InternetProtocol::endpoint endpoint; + endpoint.resize(static_cast(address_info->ai_addrlen)); + memcpy(endpoint.data(), address_info->ai_addr, + address_info->ai_addrlen); + results.values_->push_back( + basic_resolver_entry(endpoint, + actual_host_name, service_name)); + } + address_info = address_info->ai_next; + } + + return results; + } + + // Create results from an endpoint, host name and service name. + static basic_resolver_results create(const endpoint_type& endpoint, + const std::string& host_name, const std::string& service_name) + { + basic_resolver_results results; + results.values_.reset(new values_type); + results.values_->push_back( + basic_resolver_entry( + endpoint, host_name, service_name)); + return results; + } + + // Create results from a sequence of endpoints, host and service name. + template + static basic_resolver_results create( + EndpointIterator begin, EndpointIterator end, + const std::string& host_name, const std::string& service_name) + { + basic_resolver_results results; + if (begin != end) + { + results.values_.reset(new values_type); + for (EndpointIterator ep_iter = begin; ep_iter != end; ++ep_iter) + { + results.values_->push_back( + basic_resolver_entry( + *ep_iter, host_name, service_name)); + } + } + return results; + } + +# if defined(ASIO_WINDOWS_RUNTIME) + // Create results from a Windows Runtime list of EndpointPair objects. + static basic_resolver_results create( + Windows::Foundation::Collections::IVectorView< + Windows::Networking::EndpointPair^>^ endpoints, + const asio::detail::addrinfo_type& hints, + const std::string& host_name, const std::string& service_name) + { + basic_resolver_results results; + if (endpoints->Size) + { + results.values_.reset(new values_type); + for (unsigned int i = 0; i < endpoints->Size; ++i) + { + auto pair = endpoints->GetAt(i); + + if (hints.ai_family == ASIO_OS_DEF(AF_INET) + && pair->RemoteHostName->Type + != Windows::Networking::HostNameType::Ipv4) + continue; + + if (hints.ai_family == ASIO_OS_DEF(AF_INET6) + && pair->RemoteHostName->Type + != Windows::Networking::HostNameType::Ipv6) + continue; + + results.values_->push_back( + basic_resolver_entry( + typename InternetProtocol::endpoint( + ip::make_address( + asio::detail::winrt_utils::string( + pair->RemoteHostName->CanonicalName)), + asio::detail::winrt_utils::integer( + pair->RemoteServiceName)), + host_name, service_name)); + } + } + return results; + } +# endif // defined(ASIO_WINDOWS_RUNTIME) +#endif // !defined(GENERATING_DOCUMENTATION) + + /// Get the number of entries in the results range. + size_type size() const ASIO_NOEXCEPT + { + return this->values_ ? this->values_->size() : 0; + } + + /// Get the maximum number of entries permitted in a results range. + size_type max_size() const ASIO_NOEXCEPT + { + return this->values_ ? this->values_->max_size() : values_type().max_size(); + } + + /// Determine whether the results range is empty. + bool empty() const ASIO_NOEXCEPT + { + return this->values_ ? this->values_->empty() : true; + } + + /// Obtain a begin iterator for the results range. + const_iterator begin() const + { + basic_resolver_results tmp(*this); + tmp.index_ = 0; + return ASIO_MOVE_CAST(basic_resolver_results)(tmp); + } + + /// Obtain an end iterator for the results range. + const_iterator end() const + { + return const_iterator(); + } + + /// Obtain a begin iterator for the results range. + const_iterator cbegin() const + { + return begin(); + } + + /// Obtain an end iterator for the results range. + const_iterator cend() const + { + return end(); + } + + /// Swap the results range with another. + void swap(basic_resolver_results& that) ASIO_NOEXCEPT + { + if (this != &that) + { + this->values_.swap(that.values_); + std::size_t index = this->index_; + this->index_ = that.index_; + that.index_ = index; + } + } + + /// Test two iterators for equality. + friend bool operator==(const basic_resolver_results& a, + const basic_resolver_results& b) + { + return a.equal(b); + } + + /// Test two iterators for inequality. + friend bool operator!=(const basic_resolver_results& a, + const basic_resolver_results& b) + { + return !a.equal(b); + } + +private: + typedef std::vector > values_type; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_BASIC_RESOLVER_RESULTS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/endpoint.hpp new file mode 100644 index 00000000..a422373b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/endpoint.hpp @@ -0,0 +1,141 @@ +// +// ip/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_DETAIL_ENDPOINT_HPP +#define ASIO_IP_DETAIL_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/socket_types.hpp" +#include "asio/detail/winsock_init.hpp" +#include "asio/error_code.hpp" +#include "asio/ip/address.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { +namespace detail { + +// Helper class for implementating an IP endpoint. +class endpoint +{ +public: + // Default constructor. + ASIO_DECL endpoint() ASIO_NOEXCEPT; + + // Construct an endpoint using a family and port number. + ASIO_DECL endpoint(int family, + unsigned short port_num) ASIO_NOEXCEPT; + + // Construct an endpoint using an address and port number. + ASIO_DECL endpoint(const asio::ip::address& addr, + unsigned short port_num) ASIO_NOEXCEPT; + + // Copy constructor. + endpoint(const endpoint& other) ASIO_NOEXCEPT + : data_(other.data_) + { + } + + // Assign from another endpoint. + endpoint& operator=(const endpoint& other) ASIO_NOEXCEPT + { + data_ = other.data_; + return *this; + } + + // Get the underlying endpoint in the native type. + asio::detail::socket_addr_type* data() ASIO_NOEXCEPT + { + return &data_.base; + } + + // Get the underlying endpoint in the native type. + const asio::detail::socket_addr_type* data() const ASIO_NOEXCEPT + { + return &data_.base; + } + + // Get the underlying size of the endpoint in the native type. + std::size_t size() const ASIO_NOEXCEPT + { + if (is_v4()) + return sizeof(asio::detail::sockaddr_in4_type); + else + return sizeof(asio::detail::sockaddr_in6_type); + } + + // Set the underlying size of the endpoint in the native type. + ASIO_DECL void resize(std::size_t new_size); + + // Get the capacity of the endpoint in the native type. + std::size_t capacity() const ASIO_NOEXCEPT + { + return sizeof(data_); + } + + // Get the port associated with the endpoint. + ASIO_DECL unsigned short port() const ASIO_NOEXCEPT; + + // Set the port associated with the endpoint. + ASIO_DECL void port(unsigned short port_num) ASIO_NOEXCEPT; + + // Get the IP address associated with the endpoint. + ASIO_DECL asio::ip::address address() const ASIO_NOEXCEPT; + + // Set the IP address associated with the endpoint. + ASIO_DECL void address( + const asio::ip::address& addr) ASIO_NOEXCEPT; + + // Compare two endpoints for equality. + ASIO_DECL friend bool operator==(const endpoint& e1, + const endpoint& e2) ASIO_NOEXCEPT; + + // Compare endpoints for ordering. + ASIO_DECL friend bool operator<(const endpoint& e1, + const endpoint& e2) ASIO_NOEXCEPT; + + // Determine whether the endpoint is IPv4. + bool is_v4() const ASIO_NOEXCEPT + { + return data_.base.sa_family == ASIO_OS_DEF(AF_INET); + } + +#if !defined(ASIO_NO_IOSTREAM) + // Convert to a string. + ASIO_DECL std::string to_string() const; +#endif // !defined(ASIO_NO_IOSTREAM) + +private: + // The underlying IP socket address. + union data_union + { + asio::detail::socket_addr_type base; + asio::detail::sockaddr_in4_type v4; + asio::detail::sockaddr_in6_type v6; + } data_; +}; + +} // namespace detail +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/detail/impl/endpoint.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_DETAIL_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/socket_option.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/socket_option.hpp new file mode 100644 index 00000000..e4599660 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/detail/socket_option.hpp @@ -0,0 +1,566 @@ +// +// detail/socket_option.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_DETAIL_SOCKET_OPTION_HPP +#define ASIO_IP_DETAIL_SOCKET_OPTION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/detail/throw_exception.hpp" +#include "asio/ip/address.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { +namespace detail { +namespace socket_option { + +// Helper template for implementing multicast enable loopback options. +template +class multicast_enable_loopback +{ +public: +#if defined(__sun) || defined(__osf__) + typedef unsigned char ipv4_value_type; + typedef unsigned char ipv6_value_type; +#elif defined(_AIX) || defined(__hpux) || defined(__QNXNTO__) + typedef unsigned char ipv4_value_type; + typedef unsigned int ipv6_value_type; +#else + typedef int ipv4_value_type; + typedef int ipv6_value_type; +#endif + + // Default constructor. + multicast_enable_loopback() + : ipv4_value_(0), + ipv6_value_(0) + { + } + + // Construct with a specific option value. + explicit multicast_enable_loopback(bool v) + : ipv4_value_(v ? 1 : 0), + ipv6_value_(v ? 1 : 0) + { + } + + // Set the value of the boolean. + multicast_enable_loopback& operator=(bool v) + { + ipv4_value_ = v ? 1 : 0; + ipv6_value_ = v ? 1 : 0; + return *this; + } + + // Get the current value of the boolean. + bool value() const + { + return !!ipv4_value_; + } + + // Convert to bool. + operator bool() const + { + return !!ipv4_value_; + } + + // Test for false. + bool operator!() const + { + return !ipv4_value_; + } + + // Get the level of the socket option. + template + int level(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Level; + return IPv4_Level; + } + + // Get the name of the socket option. + template + int name(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Name; + return IPv4_Name; + } + + // Get the address of the boolean data. + template + void* data(const Protocol& protocol) + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the address of the boolean data. + template + const void* data(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the size of the boolean data. + template + std::size_t size(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return sizeof(ipv6_value_); + return sizeof(ipv4_value_); + } + + // Set the size of the boolean data. + template + void resize(const Protocol& protocol, std::size_t s) + { + if (protocol.family() == PF_INET6) + { + if (s != sizeof(ipv6_value_)) + { + std::length_error ex("multicast_enable_loopback socket option resize"); + asio::detail::throw_exception(ex); + } + ipv4_value_ = ipv6_value_ ? 1 : 0; + } + else + { + if (s != sizeof(ipv4_value_)) + { + std::length_error ex("multicast_enable_loopback socket option resize"); + asio::detail::throw_exception(ex); + } + ipv6_value_ = ipv4_value_ ? 1 : 0; + } + } + +private: + ipv4_value_type ipv4_value_; + ipv6_value_type ipv6_value_; +}; + +// Helper template for implementing unicast hops options. +template +class unicast_hops +{ +public: + // Default constructor. + unicast_hops() + : value_(0) + { + } + + // Construct with a specific option value. + explicit unicast_hops(int v) + : value_(v) + { + } + + // Set the value of the option. + unicast_hops& operator=(int v) + { + value_ = v; + return *this; + } + + // Get the current value of the option. + int value() const + { + return value_; + } + + // Get the level of the socket option. + template + int level(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Level; + return IPv4_Level; + } + + // Get the name of the socket option. + template + int name(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Name; + return IPv4_Name; + } + + // Get the address of the data. + template + int* data(const Protocol&) + { + return &value_; + } + + // Get the address of the data. + template + const int* data(const Protocol&) const + { + return &value_; + } + + // Get the size of the data. + template + std::size_t size(const Protocol&) const + { + return sizeof(value_); + } + + // Set the size of the data. + template + void resize(const Protocol&, std::size_t s) + { + if (s != sizeof(value_)) + { + std::length_error ex("unicast hops socket option resize"); + asio::detail::throw_exception(ex); + } +#if defined(__hpux) + if (value_ < 0) + value_ = value_ & 0xFF; +#endif + } + +private: + int value_; +}; + +// Helper template for implementing multicast hops options. +template +class multicast_hops +{ +public: +#if defined(ASIO_WINDOWS) && defined(UNDER_CE) + typedef int ipv4_value_type; +#else + typedef unsigned char ipv4_value_type; +#endif + typedef int ipv6_value_type; + + // Default constructor. + multicast_hops() + : ipv4_value_(0), + ipv6_value_(0) + { + } + + // Construct with a specific option value. + explicit multicast_hops(int v) + { + if (v < 0 || v > 255) + { + std::out_of_range ex("multicast hops value out of range"); + asio::detail::throw_exception(ex); + } + ipv4_value_ = (ipv4_value_type)v; + ipv6_value_ = v; + } + + // Set the value of the option. + multicast_hops& operator=(int v) + { + if (v < 0 || v > 255) + { + std::out_of_range ex("multicast hops value out of range"); + asio::detail::throw_exception(ex); + } + ipv4_value_ = (ipv4_value_type)v; + ipv6_value_ = v; + return *this; + } + + // Get the current value of the option. + int value() const + { + return ipv6_value_; + } + + // Get the level of the socket option. + template + int level(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Level; + return IPv4_Level; + } + + // Get the name of the socket option. + template + int name(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Name; + return IPv4_Name; + } + + // Get the address of the data. + template + void* data(const Protocol& protocol) + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the address of the data. + template + const void* data(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the size of the data. + template + std::size_t size(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return sizeof(ipv6_value_); + return sizeof(ipv4_value_); + } + + // Set the size of the data. + template + void resize(const Protocol& protocol, std::size_t s) + { + if (protocol.family() == PF_INET6) + { + if (s != sizeof(ipv6_value_)) + { + std::length_error ex("multicast hops socket option resize"); + asio::detail::throw_exception(ex); + } + if (ipv6_value_ < 0) + ipv4_value_ = 0; + else if (ipv6_value_ > 255) + ipv4_value_ = 255; + else + ipv4_value_ = (ipv4_value_type)ipv6_value_; + } + else + { + if (s != sizeof(ipv4_value_)) + { + std::length_error ex("multicast hops socket option resize"); + asio::detail::throw_exception(ex); + } + ipv6_value_ = ipv4_value_; + } + } + +private: + ipv4_value_type ipv4_value_; + ipv6_value_type ipv6_value_; +}; + +// Helper template for implementing ip_mreq-based options. +template +class multicast_request +{ +public: + // Default constructor. + multicast_request() + : ipv4_value_(), // Zero-initialisation gives the "any" address. + ipv6_value_() // Zero-initialisation gives the "any" address. + { + } + + // Construct with multicast address only. + explicit multicast_request(const address& multicast_address) + : ipv4_value_(), // Zero-initialisation gives the "any" address. + ipv6_value_() // Zero-initialisation gives the "any" address. + { + if (multicast_address.is_v6()) + { + using namespace std; // For memcpy. + address_v6 ipv6_address = multicast_address.to_v6(); + address_v6::bytes_type bytes = ipv6_address.to_bytes(); + memcpy(ipv6_value_.ipv6mr_multiaddr.s6_addr, bytes.data(), 16); + ipv6_value_.ipv6mr_interface = ipv6_address.scope_id(); + } + else + { + ipv4_value_.imr_multiaddr.s_addr = + asio::detail::socket_ops::host_to_network_long( + multicast_address.to_v4().to_uint()); + ipv4_value_.imr_interface.s_addr = + asio::detail::socket_ops::host_to_network_long( + address_v4::any().to_uint()); + } + } + + // Construct with multicast address and IPv4 address specifying an interface. + explicit multicast_request(const address_v4& multicast_address, + const address_v4& network_interface = address_v4::any()) + : ipv6_value_() // Zero-initialisation gives the "any" address. + { + ipv4_value_.imr_multiaddr.s_addr = + asio::detail::socket_ops::host_to_network_long( + multicast_address.to_uint()); + ipv4_value_.imr_interface.s_addr = + asio::detail::socket_ops::host_to_network_long( + network_interface.to_uint()); + } + + // Construct with multicast address and IPv6 network interface index. + explicit multicast_request( + const address_v6& multicast_address, + unsigned long network_interface = 0) + : ipv4_value_() // Zero-initialisation gives the "any" address. + { + using namespace std; // For memcpy. + address_v6::bytes_type bytes = multicast_address.to_bytes(); + memcpy(ipv6_value_.ipv6mr_multiaddr.s6_addr, bytes.data(), 16); + if (network_interface) + ipv6_value_.ipv6mr_interface = network_interface; + else + ipv6_value_.ipv6mr_interface = multicast_address.scope_id(); + } + + // Get the level of the socket option. + template + int level(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Level; + return IPv4_Level; + } + + // Get the name of the socket option. + template + int name(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Name; + return IPv4_Name; + } + + // Get the address of the option data. + template + const void* data(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the size of the option data. + template + std::size_t size(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return sizeof(ipv6_value_); + return sizeof(ipv4_value_); + } + +private: + asio::detail::in4_mreq_type ipv4_value_; + asio::detail::in6_mreq_type ipv6_value_; +}; + +// Helper template for implementing options that specify a network interface. +template +class network_interface +{ +public: + // Default constructor. + network_interface() + { + ipv4_value_.s_addr = + asio::detail::socket_ops::host_to_network_long( + address_v4::any().to_uint()); + ipv6_value_ = 0; + } + + // Construct with IPv4 interface. + explicit network_interface(const address_v4& ipv4_interface) + { + ipv4_value_.s_addr = + asio::detail::socket_ops::host_to_network_long( + ipv4_interface.to_uint()); + ipv6_value_ = 0; + } + + // Construct with IPv6 interface. + explicit network_interface(unsigned int ipv6_interface) + { + ipv4_value_.s_addr = + asio::detail::socket_ops::host_to_network_long( + address_v4::any().to_uint()); + ipv6_value_ = ipv6_interface; + } + + // Get the level of the socket option. + template + int level(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Level; + return IPv4_Level; + } + + // Get the name of the socket option. + template + int name(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return IPv6_Name; + return IPv4_Name; + } + + // Get the address of the option data. + template + const void* data(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return &ipv6_value_; + return &ipv4_value_; + } + + // Get the size of the option data. + template + std::size_t size(const Protocol& protocol) const + { + if (protocol.family() == PF_INET6) + return sizeof(ipv6_value_); + return sizeof(ipv4_value_); + } + +private: + asio::detail::in4_addr_type ipv4_value_; + unsigned int ipv6_value_; +}; + +} // namespace socket_option +} // namespace detail +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_DETAIL_SOCKET_OPTION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/host_name.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/host_name.hpp new file mode 100644 index 00000000..2a660a93 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/host_name.hpp @@ -0,0 +1,42 @@ +// +// ip/host_name.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_HOST_NAME_HPP +#define ASIO_IP_HOST_NAME_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/error_code.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Get the current host name. +ASIO_DECL std::string host_name(); + +/// Get the current host name. +ASIO_DECL std::string host_name(asio::error_code& ec); + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/host_name.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_HOST_NAME_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/icmp.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/icmp.hpp new file mode 100644 index 00000000..fe051412 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/icmp.hpp @@ -0,0 +1,115 @@ +// +// ip/icmp.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_ICMP_HPP +#define ASIO_IP_ICMP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/basic_raw_socket.hpp" +#include "asio/ip/basic_endpoint.hpp" +#include "asio/ip/basic_resolver.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Encapsulates the flags needed for ICMP. +/** + * The asio::ip::icmp class contains flags necessary for ICMP sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol, InternetProtocol. + */ +class icmp +{ +public: + /// The type of a ICMP endpoint. + typedef basic_endpoint endpoint; + + /// Construct to represent the IPv4 ICMP protocol. + static icmp v4() ASIO_NOEXCEPT + { + return icmp(ASIO_OS_DEF(IPPROTO_ICMP), + ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 ICMP protocol. + static icmp v6() ASIO_NOEXCEPT + { + return icmp(ASIO_OS_DEF(IPPROTO_ICMPV6), + ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_RAW); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return protocol_; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// The ICMP socket type. + typedef basic_raw_socket socket; + + /// The ICMP resolver type. + typedef basic_resolver resolver; + + /// Compare two protocols for equality. + friend bool operator==(const icmp& p1, const icmp& p2) + { + return p1.protocol_ == p2.protocol_ && p1.family_ == p2.family_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const icmp& p1, const icmp& p2) + { + return p1.protocol_ != p2.protocol_ || p1.family_ != p2.family_; + } + +private: + // Construct with a specific family. + explicit icmp(int protocol_id, int protocol_family) ASIO_NOEXCEPT + : protocol_(protocol_id), + family_(protocol_family) + { + } + + int protocol_; + int family_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_ICMP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address.hpp new file mode 100644 index 00000000..8944c507 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_ADDRESS_HPP +#define ASIO_IP_IMPL_ADDRESS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +#if !defined(ASIO_NO_DEPRECATED) + +inline address address::from_string(const char* str) +{ + return asio::ip::make_address(str); +} + +inline address address::from_string( + const char* str, asio::error_code& ec) +{ + return asio::ip::make_address(str, ec); +} + +inline address address::from_string(const std::string& str) +{ + return asio::ip::make_address(str); +} + +inline address address::from_string( + const std::string& str, asio::error_code& ec) +{ + return asio::ip::make_address(str, ec); +} + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address& addr) +{ + return os << addr.to_string().c_str(); +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_ADDRESS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v4.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v4.hpp new file mode 100644 index 00000000..f8139b87 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v4.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address_v4.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_ADDRESS_V4_HPP +#define ASIO_IP_IMPL_ADDRESS_V4_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +#if !defined(ASIO_NO_DEPRECATED) + +inline address_v4 address_v4::from_string(const char* str) +{ + return asio::ip::make_address_v4(str); +} + +inline address_v4 address_v4::from_string( + const char* str, asio::error_code& ec) +{ + return asio::ip::make_address_v4(str, ec); +} + +inline address_v4 address_v4::from_string(const std::string& str) +{ + return asio::ip::make_address_v4(str); +} + +inline address_v4 address_v4::from_string( + const std::string& str, asio::error_code& ec) +{ + return asio::ip::make_address_v4(str, ec); +} + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address_v4& addr) +{ + return os << addr.to_string().c_str(); +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_ADDRESS_V4_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v6.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v6.hpp new file mode 100644 index 00000000..985203d2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/address_v6.hpp @@ -0,0 +1,67 @@ +// +// ip/impl/address_v6.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_ADDRESS_V6_HPP +#define ASIO_IP_IMPL_ADDRESS_V6_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +#if !defined(ASIO_NO_DEPRECATED) + +inline address_v6 address_v6::from_string(const char* str) +{ + return asio::ip::make_address_v6(str); +} + +inline address_v6 address_v6::from_string( + const char* str, asio::error_code& ec) +{ + return asio::ip::make_address_v6(str, ec); +} + +inline address_v6 address_v6::from_string(const std::string& str) +{ + return asio::ip::make_address_v6(str); +} + +inline address_v6 address_v6::from_string( + const std::string& str, asio::error_code& ec) +{ + return asio::ip::make_address_v6(str, ec); +} + +#endif // !defined(ASIO_NO_DEPRECATED) + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const address_v6& addr) +{ + return os << addr.to_string().c_str(); +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_ADDRESS_V6_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/basic_endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/basic_endpoint.hpp new file mode 100644 index 00000000..f589e511 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/basic_endpoint.hpp @@ -0,0 +1,43 @@ +// +// ip/impl/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_BASIC_ENDPOINT_HPP +#define ASIO_IP_IMPL_BASIC_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const basic_endpoint& endpoint) +{ + asio::ip::detail::endpoint tmp_ep(endpoint.address(), endpoint.port()); + return os << tmp_ep.to_string().c_str(); +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_BASIC_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v4.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v4.hpp new file mode 100644 index 00000000..8912fa0d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v4.hpp @@ -0,0 +1,54 @@ +// +// ip/impl/network_v4.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_NETWORK_V4_HPP +#define ASIO_IP_IMPL_NETWORK_V4_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const network_v4& addr) +{ + asio::error_code ec; + std::string s = addr.to_string(ec); + if (ec) + { + if (os.exceptions() & std::basic_ostream::failbit) + asio::detail::throw_error(ec); + else + os.setstate(std::basic_ostream::failbit); + } + else + for (std::string::iterator i = s.begin(); i != s.end(); ++i) + os << os.widen(*i); + return os; +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_NETWORK_V4_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v6.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v6.hpp new file mode 100644 index 00000000..381b838d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/impl/network_v6.hpp @@ -0,0 +1,53 @@ +// +// ip/impl/network_v6.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_IMPL_NETWORK_V6_HPP +#define ASIO_IP_IMPL_NETWORK_V6_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const network_v6& addr) +{ + asio::error_code ec; + std::string s = addr.to_string(ec); + if (ec) + { + if (os.exceptions() & std::basic_ostream::failbit) + asio::detail::throw_error(ec); + else + os.setstate(std::basic_ostream::failbit); + } + else + for (std::string::iterator i = s.begin(); i != s.end(); ++i) + os << os.widen(*i); + return os; +} + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_IP_IMPL_NETWORK_V6_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/multicast.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/multicast.hpp new file mode 100644 index 00000000..0f711fb1 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/multicast.hpp @@ -0,0 +1,191 @@ +// +// ip/multicast.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_MULTICAST_HPP +#define ASIO_IP_MULTICAST_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/ip/detail/socket_option.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { +namespace multicast { + +/// Socket option to join a multicast group on a specified interface. +/** + * Implements the IPPROTO_IP/IP_ADD_MEMBERSHIP socket option. + * + * @par Examples + * Setting the option to join a multicast group: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::address multicast_address = + * asio::ip::address::from_string("225.0.0.1"); + * asio::ip::multicast::join_group option(multicast_address); + * socket.set_option(option); + * @endcode + * + * @par Concepts: + * SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined join_group; +#else +typedef asio::ip::detail::socket_option::multicast_request< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_ADD_MEMBERSHIP), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_JOIN_GROUP)> join_group; +#endif + +/// Socket option to leave a multicast group on a specified interface. +/** + * Implements the IPPROTO_IP/IP_DROP_MEMBERSHIP socket option. + * + * @par Examples + * Setting the option to leave a multicast group: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::address multicast_address = + * asio::ip::address::from_string("225.0.0.1"); + * asio::ip::multicast::leave_group option(multicast_address); + * socket.set_option(option); + * @endcode + * + * @par Concepts: + * SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined leave_group; +#else +typedef asio::ip::detail::socket_option::multicast_request< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_DROP_MEMBERSHIP), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_LEAVE_GROUP)> leave_group; +#endif + +/// Socket option for local interface to use for outgoing multicast packets. +/** + * Implements the IPPROTO_IP/IP_MULTICAST_IF socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::address_v4 local_interface = + * asio::ip::address_v4::from_string("1.2.3.4"); + * asio::ip::multicast::outbound_interface option(local_interface); + * socket.set_option(option); + * @endcode + * + * @par Concepts: + * SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined outbound_interface; +#else +typedef asio::ip::detail::socket_option::network_interface< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_MULTICAST_IF), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_MULTICAST_IF)> outbound_interface; +#endif + +/// Socket option for time-to-live associated with outgoing multicast packets. +/** + * Implements the IPPROTO_IP/IP_MULTICAST_TTL socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::multicast::hops option(4); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::multicast::hops option; + * socket.get_option(option); + * int ttl = option.value(); + * @endcode + * + * @par Concepts: + * GettableSocketOption, SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined hops; +#else +typedef asio::ip::detail::socket_option::multicast_hops< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_MULTICAST_TTL), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_MULTICAST_HOPS)> hops; +#endif + +/// Socket option determining whether outgoing multicast packets will be +/// received on the same socket if it is a member of the multicast group. +/** + * Implements the IPPROTO_IP/IP_MULTICAST_LOOP socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::multicast::enable_loopback option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::multicast::enable_loopback option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * GettableSocketOption, SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined enable_loopback; +#else +typedef asio::ip::detail::socket_option::multicast_enable_loopback< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_MULTICAST_LOOP), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_MULTICAST_LOOP)> enable_loopback; +#endif + +} // namespace multicast +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_MULTICAST_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v4.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v4.hpp new file mode 100644 index 00000000..1239b9f7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v4.hpp @@ -0,0 +1,261 @@ +// +// ip/network_v4.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_NETWORK_V4_HPP +#define ASIO_IP_NETWORK_V4_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/string_view.hpp" +#include "asio/error_code.hpp" +#include "asio/ip/address_v4_range.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Represents an IPv4 network. +/** + * The asio::ip::network_v4 class provides the ability to use and + * manipulate IP version 4 networks. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class network_v4 +{ +public: + /// Default constructor. + network_v4() ASIO_NOEXCEPT + : address_(), + prefix_length_(0) + { + } + + /// Construct a network based on the specified address and prefix length. + ASIO_DECL network_v4(const address_v4& addr, + unsigned short prefix_len); + + /// Construct network based on the specified address and netmask. + ASIO_DECL network_v4(const address_v4& addr, + const address_v4& mask); + + /// Copy constructor. + network_v4(const network_v4& other) ASIO_NOEXCEPT + : address_(other.address_), + prefix_length_(other.prefix_length_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + network_v4(network_v4&& other) ASIO_NOEXCEPT + : address_(ASIO_MOVE_CAST(address_v4)(other.address_)), + prefix_length_(other.prefix_length_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another network. + network_v4& operator=(const network_v4& other) ASIO_NOEXCEPT + { + address_ = other.address_; + prefix_length_ = other.prefix_length_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another network. + network_v4& operator=(network_v4&& other) ASIO_NOEXCEPT + { + address_ = ASIO_MOVE_CAST(address_v4)(other.address_); + prefix_length_ = other.prefix_length_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Obtain the address object specified when the network object was created. + address_v4 address() const ASIO_NOEXCEPT + { + return address_; + } + + /// Obtain the prefix length that was specified when the network object was + /// created. + unsigned short prefix_length() const ASIO_NOEXCEPT + { + return prefix_length_; + } + + /// Obtain the netmask that was specified when the network object was created. + ASIO_DECL address_v4 netmask() const ASIO_NOEXCEPT; + + /// Obtain an address object that represents the network address. + address_v4 network() const ASIO_NOEXCEPT + { + return address_v4(address_.to_uint() & netmask().to_uint()); + } + + /// Obtain an address object that represents the network's broadcast address. + address_v4 broadcast() const ASIO_NOEXCEPT + { + return address_v4(network().to_uint() | (netmask().to_uint() ^ 0xFFFFFFFF)); + } + + /// Obtain an address range corresponding to the hosts in the network. + ASIO_DECL address_v4_range hosts() const ASIO_NOEXCEPT; + + /// Obtain the true network address, omitting any host bits. + network_v4 canonical() const ASIO_NOEXCEPT + { + return network_v4(network(), netmask()); + } + + /// Test if network is a valid host address. + bool is_host() const ASIO_NOEXCEPT + { + return prefix_length_ == 32; + } + + /// Test if a network is a real subnet of another network. + ASIO_DECL bool is_subnet_of(const network_v4& other) const; + + /// Get the network as an address in dotted decimal format. + ASIO_DECL std::string to_string() const; + + /// Get the network as an address in dotted decimal format. + ASIO_DECL std::string to_string(asio::error_code& ec) const; + + /// Compare two networks for equality. + friend bool operator==(const network_v4& a, const network_v4& b) + { + return a.address_ == b.address_ && a.prefix_length_ == b.prefix_length_; + } + + /// Compare two networks for inequality. + friend bool operator!=(const network_v4& a, const network_v4& b) + { + return !(a == b); + } + +private: + address_v4 address_; + unsigned short prefix_length_; +}; + +/// Create an IPv4 network from an address and prefix length. +/** + * @relates address_v4 + */ +inline network_v4 make_network_v4( + const address_v4& addr, unsigned short prefix_len) +{ + return network_v4(addr, prefix_len); +} + +/// Create an IPv4 network from an address and netmask. +/** + * @relates address_v4 + */ +inline network_v4 make_network_v4( + const address_v4& addr, const address_v4& mask) +{ + return network_v4(addr, mask); +} + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4(const char* str); + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4( + const char* str, asio::error_code& ec); + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4(const std::string& str); + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4( + const std::string& str, asio::error_code& ec); + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4(string_view str); + +/// Create an IPv4 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v4 + */ +ASIO_DECL network_v4 make_network_v4( + string_view str, asio::error_code& ec); + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output a network as a string. +/** + * Used to output a human-readable string for a specified network. + * + * @param os The output stream to which the string will be written. + * + * @param net The network to be written. + * + * @return The output stream. + * + * @relates asio::ip::address_v4 + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const network_v4& net); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/network_v4.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/network_v4.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_NETWORK_V4_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v6.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v6.hpp new file mode 100644 index 00000000..ad5604a5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/network_v6.hpp @@ -0,0 +1,235 @@ +// +// ip/network_v6.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2014 Oliver Kowalke (oliver dot kowalke at gmail dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_NETWORK_V6_HPP +#define ASIO_IP_NETWORK_V6_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/string_view.hpp" +#include "asio/error_code.hpp" +#include "asio/ip/address_v6_range.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Represents an IPv6 network. +/** + * The asio::ip::network_v6 class provides the ability to use and + * manipulate IP version 6 networks. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class network_v6 +{ +public: + /// Default constructor. + network_v6() ASIO_NOEXCEPT + : address_(), + prefix_length_(0) + { + } + + /// Construct a network based on the specified address and prefix length. + ASIO_DECL network_v6(const address_v6& addr, + unsigned short prefix_len); + + /// Copy constructor. + network_v6(const network_v6& other) ASIO_NOEXCEPT + : address_(other.address_), + prefix_length_(other.prefix_length_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + network_v6(network_v6&& other) ASIO_NOEXCEPT + : address_(ASIO_MOVE_CAST(address_v6)(other.address_)), + prefix_length_(other.prefix_length_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another network. + network_v6& operator=(const network_v6& other) ASIO_NOEXCEPT + { + address_ = other.address_; + prefix_length_ = other.prefix_length_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another network. + network_v6& operator=(network_v6&& other) ASIO_NOEXCEPT + { + address_ = ASIO_MOVE_CAST(address_v6)(other.address_); + prefix_length_ = other.prefix_length_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// Obtain the address object specified when the network object was created. + address_v6 address() const ASIO_NOEXCEPT + { + return address_; + } + + /// Obtain the prefix length that was specified when the network object was + /// created. + unsigned short prefix_length() const ASIO_NOEXCEPT + { + return prefix_length_; + } + + /// Obtain an address object that represents the network address. + ASIO_DECL address_v6 network() const ASIO_NOEXCEPT; + + /// Obtain an address range corresponding to the hosts in the network. + ASIO_DECL address_v6_range hosts() const ASIO_NOEXCEPT; + + /// Obtain the true network address, omitting any host bits. + network_v6 canonical() const ASIO_NOEXCEPT + { + return network_v6(network(), prefix_length()); + } + + /// Test if network is a valid host address. + bool is_host() const ASIO_NOEXCEPT + { + return prefix_length_ == 128; + } + + /// Test if a network is a real subnet of another network. + ASIO_DECL bool is_subnet_of(const network_v6& other) const; + + /// Get the network as an address in dotted decimal format. + ASIO_DECL std::string to_string() const; + + /// Get the network as an address in dotted decimal format. + ASIO_DECL std::string to_string(asio::error_code& ec) const; + + /// Compare two networks for equality. + friend bool operator==(const network_v6& a, const network_v6& b) + { + return a.address_ == b.address_ && a.prefix_length_ == b.prefix_length_; + } + + /// Compare two networks for inequality. + friend bool operator!=(const network_v6& a, const network_v6& b) + { + return !(a == b); + } + +private: + address_v6 address_; + unsigned short prefix_length_; +}; + +/// Create an IPv6 network from an address and prefix length. +/** + * @relates address_v6 + */ +inline network_v6 make_network_v6( + const address_v6& addr, unsigned short prefix_len) +{ + return network_v6(addr, prefix_len); +} + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6(const char* str); + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6( + const char* str, asio::error_code& ec); + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6(const std::string& str); + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6( + const std::string& str, asio::error_code& ec); + +#if defined(ASIO_HAS_STRING_VIEW) \ + || defined(GENERATING_DOCUMENTATION) + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6(string_view str); + +/// Create an IPv6 network from a string containing IP address and prefix +/// length. +/** + * @relates network_v6 + */ +ASIO_DECL network_v6 make_network_v6( + string_view str, asio::error_code& ec); + +#endif // defined(ASIO_HAS_STRING_VIEW) + // || defined(GENERATING_DOCUMENTATION) + +#if !defined(ASIO_NO_IOSTREAM) + +/// Output a network as a string. +/** + * Used to output a human-readable string for a specified network. + * + * @param os The output stream to which the string will be written. + * + * @param net The network to be written. + * + * @return The output stream. + * + * @relates asio::ip::address_v6 + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, const network_v6& net); + +#endif // !defined(ASIO_NO_IOSTREAM) + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ip/impl/network_v6.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ip/impl/network_v6.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_IP_NETWORK_V6_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_base.hpp new file mode 100644 index 00000000..6edd7624 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_base.hpp @@ -0,0 +1,129 @@ +// +// ip/resolver_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_RESOLVER_BASE_HPP +#define ASIO_IP_RESOLVER_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// The resolver_base class is used as a base for the basic_resolver class +/// templates to provide a common place to define the flag constants. +class resolver_base +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// A bitmask type (C++ Std [lib.bitmask.types]). + typedef unspecified flags; + + /// Determine the canonical name of the host specified in the query. + static const flags canonical_name = implementation_defined; + + /// Indicate that returned endpoint is intended for use as a locally bound + /// socket endpoint. + static const flags passive = implementation_defined; + + /// Host name should be treated as a numeric string defining an IPv4 or IPv6 + /// address and no name resolution should be attempted. + static const flags numeric_host = implementation_defined; + + /// Service name should be treated as a numeric string defining a port number + /// and no name resolution should be attempted. + static const flags numeric_service = implementation_defined; + + /// If the query protocol family is specified as IPv6, return IPv4-mapped + /// IPv6 addresses on finding no IPv6 addresses. + static const flags v4_mapped = implementation_defined; + + /// If used with v4_mapped, return all matching IPv6 and IPv4 addresses. + static const flags all_matching = implementation_defined; + + /// Only return IPv4 addresses if a non-loopback IPv4 address is configured + /// for the system. Only return IPv6 addresses if a non-loopback IPv6 address + /// is configured for the system. + static const flags address_configured = implementation_defined; +#else + enum flags + { + canonical_name = ASIO_OS_DEF(AI_CANONNAME), + passive = ASIO_OS_DEF(AI_PASSIVE), + numeric_host = ASIO_OS_DEF(AI_NUMERICHOST), + numeric_service = ASIO_OS_DEF(AI_NUMERICSERV), + v4_mapped = ASIO_OS_DEF(AI_V4MAPPED), + all_matching = ASIO_OS_DEF(AI_ALL), + address_configured = ASIO_OS_DEF(AI_ADDRCONFIG) + }; + + // Implement bitmask operations as shown in C++ Std [lib.bitmask.types]. + + friend flags operator&(flags x, flags y) + { + return static_cast( + static_cast(x) & static_cast(y)); + } + + friend flags operator|(flags x, flags y) + { + return static_cast( + static_cast(x) | static_cast(y)); + } + + friend flags operator^(flags x, flags y) + { + return static_cast( + static_cast(x) ^ static_cast(y)); + } + + friend flags operator~(flags x) + { + return static_cast(~static_cast(x)); + } + + friend flags& operator&=(flags& x, flags y) + { + x = x & y; + return x; + } + + friend flags& operator|=(flags& x, flags y) + { + x = x | y; + return x; + } + + friend flags& operator^=(flags& x, flags y) + { + x = x ^ y; + return x; + } +#endif + +protected: + /// Protected destructor to prevent deletion through this type. + ~resolver_base() + { + } +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_RESOLVER_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_query_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_query_base.hpp new file mode 100644 index 00000000..b60ce5aa --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/resolver_query_base.hpp @@ -0,0 +1,43 @@ +// +// ip/resolver_query_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_RESOLVER_QUERY_BASE_HPP +#define ASIO_IP_RESOLVER_QUERY_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ip/resolver_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// The resolver_query_base class is used as a base for the +/// basic_resolver_query class templates to provide a common place to define +/// the flag constants. +class resolver_query_base : public resolver_base +{ +protected: + /// Protected destructor to prevent deletion through this type. + ~resolver_query_base() + { + } +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_RESOLVER_QUERY_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/tcp.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/tcp.hpp new file mode 100644 index 00000000..9507ba63 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/tcp.hpp @@ -0,0 +1,155 @@ +// +// ip/tcp.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_TCP_HPP +#define ASIO_IP_TCP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/basic_socket_acceptor.hpp" +#include "asio/basic_socket_iostream.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/detail/socket_option.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/ip/basic_endpoint.hpp" +#include "asio/ip/basic_resolver.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Encapsulates the flags needed for TCP. +/** + * The asio::ip::tcp class contains flags necessary for TCP sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol, InternetProtocol. + */ +class tcp +{ +public: + /// The type of a TCP endpoint. + typedef basic_endpoint endpoint; + + /// Construct to represent the IPv4 TCP protocol. + static tcp v4() ASIO_NOEXCEPT + { + return tcp(ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 TCP protocol. + static tcp v6() ASIO_NOEXCEPT + { + return tcp(ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_STREAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(IPPROTO_TCP); + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// The TCP socket type. + typedef basic_stream_socket socket; + + /// The TCP acceptor type. + typedef basic_socket_acceptor acceptor; + + /// The TCP resolver type. + typedef basic_resolver resolver; + +#if !defined(ASIO_NO_IOSTREAM) + /// The TCP iostream type. + typedef basic_socket_iostream iostream; +#endif // !defined(ASIO_NO_IOSTREAM) + + /// Socket option for disabling the Nagle algorithm. + /** + * Implements the IPPROTO_TCP/TCP_NODELAY socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::no_delay option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::tcp::no_delay option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined no_delay; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(IPPROTO_TCP), ASIO_OS_DEF(TCP_NODELAY)> no_delay; +#endif + + /// Compare two protocols for equality. + friend bool operator==(const tcp& p1, const tcp& p2) + { + return p1.family_ == p2.family_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const tcp& p1, const tcp& p2) + { + return p1.family_ != p2.family_; + } + +private: + // Construct with a specific family. + explicit tcp(int protocol_family) ASIO_NOEXCEPT + : family_(protocol_family) + { + } + + int family_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_TCP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/udp.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/udp.hpp new file mode 100644 index 00000000..379ee59c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/udp.hpp @@ -0,0 +1,111 @@ +// +// ip/udp.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_UDP_HPP +#define ASIO_IP_UDP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/basic_datagram_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/ip/basic_endpoint.hpp" +#include "asio/ip/basic_resolver.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver_query.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Encapsulates the flags needed for UDP. +/** + * The asio::ip::udp class contains flags necessary for UDP sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol, InternetProtocol. + */ +class udp +{ +public: + /// The type of a UDP endpoint. + typedef basic_endpoint endpoint; + + /// Construct to represent the IPv4 UDP protocol. + static udp v4() ASIO_NOEXCEPT + { + return udp(ASIO_OS_DEF(AF_INET)); + } + + /// Construct to represent the IPv6 UDP protocol. + static udp v6() ASIO_NOEXCEPT + { + return udp(ASIO_OS_DEF(AF_INET6)); + } + + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(SOCK_DGRAM); + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return ASIO_OS_DEF(IPPROTO_UDP); + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return family_; + } + + /// The UDP socket type. + typedef basic_datagram_socket socket; + + /// The UDP resolver type. + typedef basic_resolver resolver; + + /// Compare two protocols for equality. + friend bool operator==(const udp& p1, const udp& p2) + { + return p1.family_ == p2.family_; + } + + /// Compare two protocols for inequality. + friend bool operator!=(const udp& p1, const udp& p2) + { + return p1.family_ != p2.family_; + } + +private: + // Construct with a specific family. + explicit udp(int protocol_family) ASIO_NOEXCEPT + : family_(protocol_family) + { + } + + int family_; +}; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_UDP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/unicast.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/unicast.hpp new file mode 100644 index 00000000..0bc64c8e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/unicast.hpp @@ -0,0 +1,70 @@ +// +// ip/unicast.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_UNICAST_HPP +#define ASIO_IP_UNICAST_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/ip/detail/socket_option.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { +namespace unicast { + +/// Socket option for time-to-live associated with outgoing unicast packets. +/** + * Implements the IPPROTO_IP/IP_UNICAST_TTL socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::unicast::hops option(4); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::ip::unicast::hops option; + * socket.get_option(option); + * int ttl = option.value(); + * @endcode + * + * @par Concepts: + * GettableSocketOption, SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined hops; +#else +typedef asio::ip::detail::socket_option::unicast_hops< + ASIO_OS_DEF(IPPROTO_IP), + ASIO_OS_DEF(IP_TTL), + ASIO_OS_DEF(IPPROTO_IPV6), + ASIO_OS_DEF(IPV6_UNICAST_HOPS)> hops; +#endif + +} // namespace unicast +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_UNICAST_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/v6_only.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/v6_only.hpp new file mode 100644 index 00000000..ff9dac4d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ip/v6_only.hpp @@ -0,0 +1,69 @@ +// +// ip/v6_only.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IP_V6_ONLY_HPP +#define ASIO_IP_V6_ONLY_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/socket_option.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ip { + +/// Socket option for determining whether an IPv6 socket supports IPv6 +/// communication only. +/** + * Implements the IPPROTO_IPV6/IP_V6ONLY socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::v6_only option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::ip::v6_only option; + * socket.get_option(option); + * bool v6_only = option.value(); + * @endcode + * + * @par Concepts: + * GettableSocketOption, SettableSocketOption. + */ +#if defined(GENERATING_DOCUMENTATION) +typedef implementation_defined v6_only; +#elif defined(IPV6_V6ONLY) +typedef asio::detail::socket_option::boolean< + IPPROTO_IPV6, IPV6_V6ONLY> v6_only; +#else +typedef asio::detail::socket_option::boolean< + asio::detail::custom_socket_option_level, + asio::detail::always_fail_option> v6_only; +#endif + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IP_V6_ONLY_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_executor.hpp new file mode 100644 index 00000000..8497da34 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_executor.hpp @@ -0,0 +1,46 @@ +// +// is_executor.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IS_EXECUTOR_HPP +#define ASIO_IS_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// The is_executor trait detects whether a type T meets the Executor type +/// requirements. +/** + * Class template @c is_executor is a UnaryTypeTrait that is derived from @c + * true_type if the type @c T meets the syntactic requirements for Executor, + * otherwise @c false_type. + */ +template +struct is_executor +#if defined(GENERATING_DOCUMENTATION) + : integral_constant +#else // defined(GENERATING_DOCUMENTATION) + : asio::detail::is_executor +#endif // defined(GENERATING_DOCUMENTATION) +{ +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IS_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_read_buffered.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_read_buffered.hpp new file mode 100644 index 00000000..c75b4892 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_read_buffered.hpp @@ -0,0 +1,59 @@ +// +// is_read_buffered.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IS_READ_BUFFERED_HPP +#define ASIO_IS_READ_BUFFERED_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/buffered_read_stream_fwd.hpp" +#include "asio/buffered_stream_fwd.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail { + +template +char is_read_buffered_helper(buffered_stream* s); + +template +char is_read_buffered_helper(buffered_read_stream* s); + +struct is_read_buffered_big_type { char data[10]; }; +is_read_buffered_big_type is_read_buffered_helper(...); + +} // namespace detail + +/// The is_read_buffered class is a traits class that may be used to determine +/// whether a stream type supports buffering of read data. +template +class is_read_buffered +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The value member is true only if the Stream type supports buffering of + /// read data. + static const bool value; +#else + ASIO_STATIC_CONSTANT(bool, + value = sizeof(detail::is_read_buffered_helper((Stream*)0)) == 1); +#endif +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IS_READ_BUFFERED_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_write_buffered.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_write_buffered.hpp new file mode 100644 index 00000000..fd37f3a3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/is_write_buffered.hpp @@ -0,0 +1,59 @@ +// +// is_write_buffered.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_IS_WRITE_BUFFERED_HPP +#define ASIO_IS_WRITE_BUFFERED_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/buffered_stream_fwd.hpp" +#include "asio/buffered_write_stream_fwd.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail { + +template +char is_write_buffered_helper(buffered_stream* s); + +template +char is_write_buffered_helper(buffered_write_stream* s); + +struct is_write_buffered_big_type { char data[10]; }; +is_write_buffered_big_type is_write_buffered_helper(...); + +} // namespace detail + +/// The is_write_buffered class is a traits class that may be used to determine +/// whether a stream type supports buffering of written data. +template +class is_write_buffered +{ +public: +#if defined(GENERATING_DOCUMENTATION) + /// The value member is true only if the Stream type supports buffering of + /// written data. + static const bool value; +#else + ASIO_STATIC_CONSTANT(bool, + value = sizeof(detail::is_write_buffered_helper((Stream*)0)) == 1); +#endif +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_IS_WRITE_BUFFERED_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/basic_endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/basic_endpoint.hpp new file mode 100644 index 00000000..1b1b299f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/basic_endpoint.hpp @@ -0,0 +1,247 @@ +// +// local/basic_endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Derived from a public domain implementation written by Daniel Casimiro. +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_LOCAL_BASIC_ENDPOINT_HPP +#define ASIO_LOCAL_BASIC_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_LOCAL_SOCKETS) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/local/detail/endpoint.hpp" + +#if !defined(ASIO_NO_IOSTREAM) +# include +#endif // !defined(ASIO_NO_IOSTREAM) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace local { + +/// Describes an endpoint for a UNIX socket. +/** + * The asio::local::basic_endpoint class template describes an endpoint + * that may be associated with a particular UNIX socket. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * Endpoint. + */ +template +class basic_endpoint +{ +public: + /// The protocol type associated with the endpoint. + typedef Protocol protocol_type; + + /// The type of the endpoint structure. This type is dependent on the + /// underlying implementation of the socket layer. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined data_type; +#else + typedef asio::detail::socket_addr_type data_type; +#endif + + /// Default constructor. + basic_endpoint() ASIO_NOEXCEPT + { + } + + /// Construct an endpoint using the specified path name. + basic_endpoint(const char* path_name) + : impl_(path_name) + { + } + + /// Construct an endpoint using the specified path name. + basic_endpoint(const std::string& path_name) + : impl_(path_name) + { + } + + #if defined(ASIO_HAS_STRING_VIEW) + /// Construct an endpoint using the specified path name. + basic_endpoint(string_view path_name) + : impl_(path_name) + { + } + #endif // defined(ASIO_HAS_STRING_VIEW) + + /// Copy constructor. + basic_endpoint(const basic_endpoint& other) + : impl_(other.impl_) + { + } + +#if defined(ASIO_HAS_MOVE) + /// Move constructor. + basic_endpoint(basic_endpoint&& other) + : impl_(other.impl_) + { + } +#endif // defined(ASIO_HAS_MOVE) + + /// Assign from another endpoint. + basic_endpoint& operator=(const basic_endpoint& other) + { + impl_ = other.impl_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) + /// Move-assign from another endpoint. + basic_endpoint& operator=(basic_endpoint&& other) + { + impl_ = other.impl_; + return *this; + } +#endif // defined(ASIO_HAS_MOVE) + + /// The protocol associated with the endpoint. + protocol_type protocol() const + { + return protocol_type(); + } + + /// Get the underlying endpoint in the native type. + data_type* data() + { + return impl_.data(); + } + + /// Get the underlying endpoint in the native type. + const data_type* data() const + { + return impl_.data(); + } + + /// Get the underlying size of the endpoint in the native type. + std::size_t size() const + { + return impl_.size(); + } + + /// Set the underlying size of the endpoint in the native type. + void resize(std::size_t new_size) + { + impl_.resize(new_size); + } + + /// Get the capacity of the endpoint in the native type. + std::size_t capacity() const + { + return impl_.capacity(); + } + + /// Get the path associated with the endpoint. + std::string path() const + { + return impl_.path(); + } + + /// Set the path associated with the endpoint. + void path(const char* p) + { + impl_.path(p); + } + + /// Set the path associated with the endpoint. + void path(const std::string& p) + { + impl_.path(p); + } + + /// Compare two endpoints for equality. + friend bool operator==(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e1.impl_ == e2.impl_; + } + + /// Compare two endpoints for inequality. + friend bool operator!=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e1.impl_ == e2.impl_); + } + + /// Compare endpoints for ordering. + friend bool operator<(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e1.impl_ < e2.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator>(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return e2.impl_ < e1.impl_; + } + + /// Compare endpoints for ordering. + friend bool operator<=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e2 < e1); + } + + /// Compare endpoints for ordering. + friend bool operator>=(const basic_endpoint& e1, + const basic_endpoint& e2) + { + return !(e1 < e2); + } + +private: + // The underlying UNIX domain endpoint. + asio::local::detail::endpoint impl_; +}; + +/// Output an endpoint as a string. +/** + * Used to output a human-readable string for a specified endpoint. + * + * @param os The output stream to which the string will be written. + * + * @param endpoint The endpoint to be written. + * + * @return The output stream. + * + * @relates asio::local::basic_endpoint + */ +template +std::basic_ostream& operator<<( + std::basic_ostream& os, + const basic_endpoint& endpoint) +{ + os << endpoint.path(); + return os; +} + +} // namespace local +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_LOCAL_SOCKETS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_LOCAL_BASIC_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/connect_pair.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/connect_pair.hpp new file mode 100644 index 00000000..ed48b61b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/connect_pair.hpp @@ -0,0 +1,101 @@ +// +// local/connect_pair.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_LOCAL_CONNECT_PAIR_HPP +#define ASIO_LOCAL_CONNECT_PAIR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_LOCAL_SOCKETS) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_socket.hpp" +#include "asio/detail/socket_ops.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/local/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace local { + +/// Create a pair of connected sockets. +template +void connect_pair(basic_socket& socket1, + basic_socket& socket2); + +/// Create a pair of connected sockets. +template +ASIO_SYNC_OP_VOID connect_pair(basic_socket& socket1, + basic_socket& socket2, asio::error_code& ec); + +template +inline void connect_pair(basic_socket& socket1, + basic_socket& socket2) +{ + asio::error_code ec; + connect_pair(socket1, socket2, ec); + asio::detail::throw_error(ec, "connect_pair"); +} + +template +inline ASIO_SYNC_OP_VOID connect_pair( + basic_socket& socket1, + basic_socket& socket2, asio::error_code& ec) +{ + // Check that this function is only being used with a UNIX domain socket. + asio::local::basic_endpoint* tmp + = static_cast(0); + (void)tmp; + + Protocol protocol; + asio::detail::socket_type sv[2]; + if (asio::detail::socket_ops::socketpair(protocol.family(), + protocol.type(), protocol.protocol(), sv, ec) + == asio::detail::socket_error_retval) + ASIO_SYNC_OP_VOID_RETURN(ec); + + socket1.assign(protocol, sv[0], ec); + if (ec) + { + asio::error_code temp_ec; + asio::detail::socket_ops::state_type state[2] = { 0, 0 }; + asio::detail::socket_ops::close(sv[0], state[0], true, temp_ec); + asio::detail::socket_ops::close(sv[1], state[1], true, temp_ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + socket2.assign(protocol, sv[1], ec); + if (ec) + { + asio::error_code temp_ec; + socket1.close(temp_ec); + asio::detail::socket_ops::state_type state = 0; + asio::detail::socket_ops::close(sv[1], state, true, temp_ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + ASIO_SYNC_OP_VOID_RETURN(ec); +} + +} // namespace local +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_LOCAL_SOCKETS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_LOCAL_CONNECT_PAIR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/datagram_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/datagram_protocol.hpp new file mode 100644 index 00000000..a2bf5149 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/datagram_protocol.hpp @@ -0,0 +1,80 @@ +// +// local/datagram_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP +#define ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_LOCAL_SOCKETS) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_datagram_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/local/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace local { + +/// Encapsulates the flags needed for datagram-oriented UNIX sockets. +/** + * The asio::local::datagram_protocol class contains flags necessary for + * datagram-oriented UNIX domain sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class datagram_protocol +{ +public: + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return SOCK_DGRAM; + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return 0; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return AF_UNIX; + } + + /// The type of a UNIX domain endpoint. + typedef basic_endpoint endpoint; + + /// The UNIX domain socket type. + typedef basic_datagram_socket socket; +}; + +} // namespace local +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_LOCAL_SOCKETS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_LOCAL_DATAGRAM_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/detail/endpoint.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/detail/endpoint.hpp new file mode 100644 index 00000000..042b21a9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/detail/endpoint.hpp @@ -0,0 +1,139 @@ +// +// local/detail/endpoint.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Derived from a public domain implementation written by Daniel Casimiro. +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_LOCAL_DETAIL_ENDPOINT_HPP +#define ASIO_LOCAL_DETAIL_ENDPOINT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_LOCAL_SOCKETS) + +#include +#include +#include "asio/detail/socket_types.hpp" +#include "asio/detail/string_view.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace local { +namespace detail { + +// Helper class for implementing a UNIX domain endpoint. +class endpoint +{ +public: + // Default constructor. + ASIO_DECL endpoint(); + + // Construct an endpoint using the specified path name. + ASIO_DECL endpoint(const char* path_name); + + // Construct an endpoint using the specified path name. + ASIO_DECL endpoint(const std::string& path_name); + + #if defined(ASIO_HAS_STRING_VIEW) + // Construct an endpoint using the specified path name. + ASIO_DECL endpoint(string_view path_name); + #endif // defined(ASIO_HAS_STRING_VIEW) + + // Copy constructor. + endpoint(const endpoint& other) + : data_(other.data_), + path_length_(other.path_length_) + { + } + + // Assign from another endpoint. + endpoint& operator=(const endpoint& other) + { + data_ = other.data_; + path_length_ = other.path_length_; + return *this; + } + + // Get the underlying endpoint in the native type. + asio::detail::socket_addr_type* data() + { + return &data_.base; + } + + // Get the underlying endpoint in the native type. + const asio::detail::socket_addr_type* data() const + { + return &data_.base; + } + + // Get the underlying size of the endpoint in the native type. + std::size_t size() const + { + return path_length_ + + offsetof(asio::detail::sockaddr_un_type, sun_path); + } + + // Set the underlying size of the endpoint in the native type. + ASIO_DECL void resize(std::size_t size); + + // Get the capacity of the endpoint in the native type. + std::size_t capacity() const + { + return sizeof(asio::detail::sockaddr_un_type); + } + + // Get the path associated with the endpoint. + ASIO_DECL std::string path() const; + + // Set the path associated with the endpoint. + ASIO_DECL void path(const char* p); + + // Set the path associated with the endpoint. + ASIO_DECL void path(const std::string& p); + + // Compare two endpoints for equality. + ASIO_DECL friend bool operator==( + const endpoint& e1, const endpoint& e2); + + // Compare endpoints for ordering. + ASIO_DECL friend bool operator<( + const endpoint& e1, const endpoint& e2); + +private: + // The underlying UNIX socket address. + union data_union + { + asio::detail::socket_addr_type base; + asio::detail::sockaddr_un_type local; + } data_; + + // The length of the path associated with the endpoint. + std::size_t path_length_; + + // Initialise with a specified path. + ASIO_DECL void init(const char* path, std::size_t path_length); +}; + +} // namespace detail +} // namespace local +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/local/detail/impl/endpoint.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_LOCAL_SOCKETS) + +#endif // ASIO_LOCAL_DETAIL_ENDPOINT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/stream_protocol.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/stream_protocol.hpp new file mode 100644 index 00000000..276e71d3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/local/stream_protocol.hpp @@ -0,0 +1,90 @@ +// +// local/stream_protocol.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_LOCAL_STREAM_PROTOCOL_HPP +#define ASIO_LOCAL_STREAM_PROTOCOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_LOCAL_SOCKETS) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_socket_acceptor.hpp" +#include "asio/basic_socket_iostream.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/detail/socket_types.hpp" +#include "asio/local/basic_endpoint.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace local { + +/// Encapsulates the flags needed for stream-oriented UNIX sockets. +/** + * The asio::local::stream_protocol class contains flags necessary for + * stream-oriented UNIX domain sockets. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Safe. + * + * @par Concepts: + * Protocol. + */ +class stream_protocol +{ +public: + /// Obtain an identifier for the type of the protocol. + int type() const ASIO_NOEXCEPT + { + return SOCK_STREAM; + } + + /// Obtain an identifier for the protocol. + int protocol() const ASIO_NOEXCEPT + { + return 0; + } + + /// Obtain an identifier for the protocol family. + int family() const ASIO_NOEXCEPT + { + return AF_UNIX; + } + + /// The type of a UNIX domain endpoint. + typedef basic_endpoint endpoint; + + /// The UNIX domain socket type. + typedef basic_stream_socket socket; + + /// The UNIX domain acceptor type. + typedef basic_socket_acceptor acceptor; + +#if !defined(ASIO_NO_IOSTREAM) + /// The UNIX domain iostream type. + typedef basic_socket_iostream iostream; +#endif // !defined(ASIO_NO_IOSTREAM) +}; + +} // namespace local +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_LOCAL_SOCKETS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_LOCAL_STREAM_PROTOCOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/packaged_task.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/packaged_task.hpp new file mode 100644 index 00000000..49e97712 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/packaged_task.hpp @@ -0,0 +1,126 @@ +// +// packaged_task.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_PACKAGED_TASK_HPP +#define ASIO_PACKAGED_TASK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/future.hpp" + +#if defined(ASIO_HAS_STD_FUTURE_CLASS) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/variadic_templates.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_VARIADIC_TEMPLATES) \ + || defined(GENERATING_DOCUMENTATION) + +/// Partial specialisation of @c async_result for @c std::packaged_task. +template +class async_result, Signature> +{ +public: + /// The packaged task is the concrete completion handler type. + typedef std::packaged_task completion_handler_type; + + /// The return type of the initiating function is the future obtained from + /// the packaged task. + typedef std::future return_type; + + /// The constructor extracts the future from the packaged task. + explicit async_result(completion_handler_type& h) + : future_(h.get_future()) + { + } + + /// Returns the packaged task's future. + return_type get() + { + return std::move(future_); + } + +private: + return_type future_; +}; + +#else // defined(ASIO_HAS_VARIADIC_TEMPLATES) + // || defined(GENERATING_DOCUMENTATION) + +template +struct async_result, Signature> +{ + typedef std::packaged_task completion_handler_type; + typedef std::future return_type; + + explicit async_result(completion_handler_type& h) + : future_(h.get_future()) + { + } + + return_type get() + { + return std::move(future_); + } + +private: + return_type future_; +}; + +#define ASIO_PRIVATE_ASYNC_RESULT_DEF(n) \ + template \ + class async_result< \ + std::packaged_task, Signature> \ + { \ + public: \ + typedef std::packaged_task< \ + Result(ASIO_VARIADIC_TARGS(n))> \ + completion_handler_type; \ + \ + typedef std::future return_type; \ + \ + explicit async_result(completion_handler_type& h) \ + : future_(h.get_future()) \ + { \ + } \ + \ + return_type get() \ + { \ + return std::move(future_); \ + } \ + \ + private: \ + return_type future_; \ + }; \ + /**/ + ASIO_VARIADIC_GENERATE(ASIO_PRIVATE_ASYNC_RESULT_DEF) +#undef ASIO_PRIVATE_ASYNC_RESULT_DEF + +#endif // defined(ASIO_HAS_VARIADIC_TEMPLATES) + // || defined(GENERATING_DOCUMENTATION) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_STD_FUTURE_CLASS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_PACKAGED_TASK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/placeholders.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/placeholders.hpp new file mode 100644 index 00000000..7c89753c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/placeholders.hpp @@ -0,0 +1,151 @@ +// +// placeholders.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_PLACEHOLDERS_HPP +#define ASIO_PLACEHOLDERS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_BIND) +# include +#endif // defined(ASIO_HAS_BOOST_BIND) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace placeholders { + +#if defined(GENERATING_DOCUMENTATION) + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the error argument of a handler for any of the asynchronous functions. +unspecified error; + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the bytes_transferred argument of a handler for asynchronous functions such +/// as asio::basic_stream_socket::async_write_some or +/// asio::async_write. +unspecified bytes_transferred; + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the iterator argument of a handler for asynchronous functions such as +/// asio::async_connect. +unspecified iterator; + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the results argument of a handler for asynchronous functions such as +/// asio::basic_resolver::async_resolve. +unspecified results; + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the results argument of a handler for asynchronous functions such as +/// asio::async_connect. +unspecified endpoint; + +/// An argument placeholder, for use with boost::bind(), that corresponds to +/// the signal_number argument of a handler for asynchronous functions such as +/// asio::signal_set::async_wait. +unspecified signal_number; + +#elif defined(ASIO_HAS_BOOST_BIND) +# if defined(__BORLANDC__) || defined(__GNUC__) + +inline boost::arg<1> error() +{ + return boost::arg<1>(); +} + +inline boost::arg<2> bytes_transferred() +{ + return boost::arg<2>(); +} + +inline boost::arg<2> iterator() +{ + return boost::arg<2>(); +} + +inline boost::arg<2> results() +{ + return boost::arg<2>(); +} + +inline boost::arg<2> endpoint() +{ + return boost::arg<2>(); +} + +inline boost::arg<2> signal_number() +{ + return boost::arg<2>(); +} + +# else + +namespace detail +{ + template + struct placeholder + { + static boost::arg& get() + { + static boost::arg result; + return result; + } + }; +} + +# if defined(ASIO_MSVC) && (ASIO_MSVC < 1400) + +static boost::arg<1>& error + = asio::placeholders::detail::placeholder<1>::get(); +static boost::arg<2>& bytes_transferred + = asio::placeholders::detail::placeholder<2>::get(); +static boost::arg<2>& iterator + = asio::placeholders::detail::placeholder<2>::get(); +static boost::arg<2>& results + = asio::placeholders::detail::placeholder<2>::get(); +static boost::arg<2>& endpoint + = asio::placeholders::detail::placeholder<2>::get(); +static boost::arg<2>& signal_number + = asio::placeholders::detail::placeholder<2>::get(); + +# else + +namespace +{ + boost::arg<1>& error + = asio::placeholders::detail::placeholder<1>::get(); + boost::arg<2>& bytes_transferred + = asio::placeholders::detail::placeholder<2>::get(); + boost::arg<2>& iterator + = asio::placeholders::detail::placeholder<2>::get(); + boost::arg<2>& results + = asio::placeholders::detail::placeholder<2>::get(); + boost::arg<2>& endpoint + = asio::placeholders::detail::placeholder<2>::get(); + boost::arg<2>& signal_number + = asio::placeholders::detail::placeholder<2>::get(); +} // namespace + +# endif +# endif +#endif + +} // namespace placeholders +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_PLACEHOLDERS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_descriptor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_descriptor.hpp new file mode 100644 index 00000000..6164adfd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_descriptor.hpp @@ -0,0 +1,697 @@ +// +// posix/basic_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POSIX_BASIC_DESCRIPTOR_HPP +#define ASIO_POSIX_BASIC_DESCRIPTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/async_result.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/reactive_descriptor_service.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" +#include "asio/posix/descriptor_base.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace posix { + +/// Provides POSIX descriptor functionality. +/** + * The posix::basic_descriptor class template provides the ability to wrap a + * POSIX descriptor. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_descriptor + : public descriptor_base +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the descriptor type to another executor. + template + struct rebind_executor + { + /// The descriptor type when rebound to the specified executor. + typedef basic_descriptor other; + }; + + /// The native representation of a descriptor. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef detail::reactive_descriptor_service::native_handle_type + native_handle_type; +#endif + + /// A descriptor is always the lowest layer. + typedef basic_descriptor lowest_layer_type; + + /// Construct a descriptor without opening it. + /** + * This constructor creates a descriptor without opening it. + * + * @param ex The I/O executor that the descriptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit basic_descriptor(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct a descriptor without opening it. + /** + * This constructor creates a descriptor without opening it. + * + * @param context An execution context which provides the I/O executor that + * the descriptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the descriptor. + */ + template + explicit basic_descriptor(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + } + + /// Construct a descriptor on an existing native descriptor. + /** + * This constructor creates a descriptor object to hold an existing native + * descriptor. + * + * @param ex The I/O executor that the descriptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + * + * @param native_descriptor A native descriptor. + * + * @throws asio::system_error Thrown on failure. + */ + basic_descriptor(const executor_type& ex, + const native_handle_type& native_descriptor) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_descriptor, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct a descriptor on an existing native descriptor. + /** + * This constructor creates a descriptor object to hold an existing native + * descriptor. + * + * @param context An execution context which provides the I/O executor that + * the descriptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the descriptor. + * + * @param native_descriptor A native descriptor. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_descriptor(ExecutionContext& context, + const native_handle_type& native_descriptor, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_descriptor, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a descriptor from another. + /** + * This constructor moves a descriptor from one object to another. + * + * @param other The other descriptor object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_descriptor(const executor_type&) + * constructor. + */ + basic_descriptor(basic_descriptor&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign a descriptor from another. + /** + * This assignment operator moves a descriptor from one object to another. + * + * @param other The other descriptor object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_descriptor(const executor_type&) + * constructor. + */ + basic_descriptor& operator=(basic_descriptor&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since a descriptor cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A reference to the lowest layer in the stack of layers. Ownership + * is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return *this; + } + + /// Get a const reference to the lowest layer. + /** + * This function returns a const reference to the lowest layer in a stack of + * layers. Since a descriptor cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A const reference to the lowest layer in the stack of layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return *this; + } + + /// Assign an existing native descriptor to the descriptor. + /* + * This function opens the descriptor to hold an existing native descriptor. + * + * @param native_descriptor A native descriptor. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const native_handle_type& native_descriptor) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), + native_descriptor, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assign an existing native descriptor to the descriptor. + /* + * This function opens the descriptor to hold an existing native descriptor. + * + * @param native_descriptor A native descriptor. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const native_handle_type& native_descriptor, + asio::error_code& ec) + { + impl_.get_service().assign( + impl_.get_implementation(), native_descriptor, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the descriptor is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Close the descriptor. + /** + * This function is used to close the descriptor. Any asynchronous read or + * write operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. Note that, even if + * the function indicates an error, the underlying descriptor is closed. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the descriptor. + /** + * This function is used to close the descriptor. Any asynchronous read or + * write operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. Note that, even if + * the function indicates an error, the underlying descriptor is closed. + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native descriptor representation. + /** + * This function may be used to obtain the underlying representation of the + * descriptor. This is intended to allow access to native descriptor + * functionality that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Release ownership of the native descriptor implementation. + /** + * This function may be used to obtain the underlying representation of the + * descriptor. After calling this function, @c is_open() returns false. The + * caller is responsible for closing the descriptor. + * + * All outstanding asynchronous read or write operations will finish + * immediately, and the handlers for cancelled operations will be passed the + * asio::error::operation_aborted error. + */ + native_handle_type release() + { + return impl_.get_service().release(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the descriptor. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the descriptor. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform an IO control command on the descriptor. + /** + * This function is used to execute an IO control command on the descriptor. + * + * @param command The IO control command to be performed on the descriptor. + * + * @throws asio::system_error Thrown on failure. + * + * @sa IoControlCommand @n + * asio::posix::descriptor_base::bytes_readable @n + * asio::posix::descriptor_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * asio::posix::stream_descriptor::bytes_readable command; + * descriptor.io_control(command); + * std::size_t bytes_readable = command.get(); + * @endcode + */ + template + void io_control(IoControlCommand& command) + { + asio::error_code ec; + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + asio::detail::throw_error(ec, "io_control"); + } + + /// Perform an IO control command on the descriptor. + /** + * This function is used to execute an IO control command on the descriptor. + * + * @param command The IO control command to be performed on the descriptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @sa IoControlCommand @n + * asio::posix::descriptor_base::bytes_readable @n + * asio::posix::descriptor_base::non_blocking_io + * + * @par Example + * Getting the number of bytes ready to read: + * @code + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * asio::posix::stream_descriptor::bytes_readable command; + * asio::error_code ec; + * descriptor.io_control(command, ec); + * if (ec) + * { + * // An error occurred. + * } + * std::size_t bytes_readable = command.get(); + * @endcode + */ + template + ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, + asio::error_code& ec) + { + impl_.get_service().io_control(impl_.get_implementation(), command, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the descriptor. + /** + * @returns @c true if the descriptor's synchronous operations will fail with + * asio::error::would_block if they are unable to perform the requested + * operation immediately. If @c false, synchronous operations will block + * until complete. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + bool non_blocking() const + { + return impl_.get_service().non_blocking(impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the descriptor. + /** + * @param mode If @c true, the descriptor's synchronous operations will fail + * with asio::error::would_block if they are unable to perform the + * requested operation immediately. If @c false, synchronous operations will + * block until complete. + * + * @throws asio::system_error Thrown on failure. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + void non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "non_blocking"); + } + + /// Sets the non-blocking mode of the descriptor. + /** + * @param mode If @c true, the descriptor's synchronous operations will fail + * with asio::error::would_block if they are unable to perform the + * requested operation immediately. If @c false, synchronous operations will + * block until complete. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note The non-blocking mode has no effect on the behaviour of asynchronous + * operations. Asynchronous operations will never fail with the error + * asio::error::would_block. + */ + ASIO_SYNC_OP_VOID non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Gets the non-blocking mode of the native descriptor implementation. + /** + * This function is used to retrieve the non-blocking mode of the underlying + * native descriptor. This mode has no effect on the behaviour of the + * descriptor object's synchronous operations. + * + * @returns @c true if the underlying descriptor is in non-blocking mode and + * direct system calls may fail with asio::error::would_block (or the + * equivalent system error). + * + * @note The current non-blocking mode is cached by the descriptor object. + * Consequently, the return value may be incorrect if the non-blocking mode + * was set directly on the native descriptor. + */ + bool native_non_blocking() const + { + return impl_.get_service().native_non_blocking( + impl_.get_implementation()); + } + + /// Sets the non-blocking mode of the native descriptor implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native descriptor. It has no effect on the behaviour of the descriptor + * object's synchronous operations. + * + * @param mode If @c true, the underlying descriptor is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @throws asio::system_error Thrown on failure. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + */ + void native_non_blocking(bool mode) + { + asio::error_code ec; + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + asio::detail::throw_error(ec, "native_non_blocking"); + } + + /// Sets the non-blocking mode of the native descriptor implementation. + /** + * This function is used to modify the non-blocking mode of the underlying + * native descriptor. It has no effect on the behaviour of the descriptor + * object's synchronous operations. + * + * @param mode If @c true, the underlying descriptor is put into non-blocking + * mode and direct system calls may fail with asio::error::would_block + * (or the equivalent system error). + * + * @param ec Set to indicate what error occurred, if any. If the @c mode is + * @c false, but the current value of @c non_blocking() is @c true, this + * function fails with asio::error::invalid_argument, as the + * combination does not make sense. + */ + ASIO_SYNC_OP_VOID native_non_blocking( + bool mode, asio::error_code& ec) + { + impl_.get_service().native_non_blocking( + impl_.get_implementation(), mode, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Wait for the descriptor to become ready to read, ready to write, or to + /// have pending error conditions. + /** + * This function is used to perform a blocking wait for a descriptor to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired descriptor state. + * + * @par Example + * Waiting for a descriptor to become readable. + * @code + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * descriptor.wait(asio::posix::stream_descriptor::wait_read); + * @endcode + */ + void wait(wait_type w) + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), w, ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Wait for the descriptor to become ready to read, ready to write, or to + /// have pending error conditions. + /** + * This function is used to perform a blocking wait for a descriptor to enter + * a ready to read, write or error condition state. + * + * @param w Specifies the desired descriptor state. + * + * @param ec Set to indicate what error occurred, if any. + * + * @par Example + * Waiting for a descriptor to become readable. + * @code + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * asio::error_code ec; + * descriptor.wait(asio::posix::stream_descriptor::wait_read, ec); + * @endcode + */ + ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), w, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Asynchronously wait for the descriptor to become ready to read, ready to + /// write, or to have pending error conditions. + /** + * This function is used to perform an asynchronous wait for a descriptor to + * enter a ready to read, write or error condition state. + * + * @param w Specifies the desired descriptor state. + * + * @param handler The handler to be called when the wait operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * @code + * void wait_handler(const asio::error_code& error) + * { + * if (!error) + * { + * // Wait succeeded. + * } + * } + * + * ... + * + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * descriptor.async_wait( + * asio::posix::stream_descriptor::wait_read, + * wait_handler); + * @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait(wait_type w, + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler, w); + } + +protected: + /// Protected destructor to prevent deletion through this type. + /** + * This function destroys the descriptor, cancelling any outstanding + * asynchronous wait operations associated with the descriptor as if by + * calling @c cancel. + */ + ~basic_descriptor() + { + } + + detail::io_object_impl impl_; + +private: + // Disallow copying and assignment. + basic_descriptor(const basic_descriptor&) ASIO_DELETED; + basic_descriptor& operator=(const basic_descriptor&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_descriptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler, wait_type w) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), w, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_descriptor* self_; + }; +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_POSIX_BASIC_DESCRIPTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_stream_descriptor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_stream_descriptor.hpp new file mode 100644 index 00000000..95c7f2a5 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/basic_stream_descriptor.hpp @@ -0,0 +1,470 @@ +// +// posix/basic_stream_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP +#define ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/posix/descriptor.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +namespace asio { +namespace posix { + +/// Provides stream-oriented descriptor functionality. +/** + * The posix::basic_stream_descriptor class template provides asynchronous and + * blocking stream-oriented descriptor functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class basic_stream_descriptor + : public basic_descriptor +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the descriptor type to another executor. + template + struct rebind_executor + { + /// The descriptor type when rebound to the specified executor. + typedef basic_stream_descriptor other; + }; + + /// The native representation of a descriptor. + typedef typename basic_descriptor::native_handle_type + native_handle_type; + + /// Construct a stream descriptor without opening it. + /** + * This constructor creates a stream descriptor without opening it. The + * descriptor needs to be opened and then connected or accepted before data + * can be sent or received on it. + * + * @param ex The I/O executor that the descriptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + */ + explicit basic_stream_descriptor(const executor_type& ex) + : basic_descriptor(ex) + { + } + + /// Construct a stream descriptor without opening it. + /** + * This constructor creates a stream descriptor without opening it. The + * descriptor needs to be opened and then connected or accepted before data + * can be sent or received on it. + * + * @param context An execution context which provides the I/O executor that + * the descriptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the descriptor. + */ + template + explicit basic_stream_descriptor(ExecutionContext& context, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_descriptor(context) + { + } + + /// Construct a stream descriptor on an existing native descriptor. + /** + * This constructor creates a stream descriptor object to hold an existing + * native descriptor. + * + * @param ex The I/O executor that the descriptor will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * descriptor. + * + * @param native_descriptor The new underlying descriptor implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_descriptor(const executor_type& ex, + const native_handle_type& native_descriptor) + : basic_descriptor(ex, native_descriptor) + { + } + + /// Construct a stream descriptor on an existing native descriptor. + /** + * This constructor creates a stream descriptor object to hold an existing + * native descriptor. + * + * @param context An execution context which provides the I/O executor that + * the descriptor will use, by default, to dispatch handlers for any + * asynchronous operations performed on the descriptor. + * + * @param native_descriptor The new underlying descriptor implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_stream_descriptor(ExecutionContext& context, + const native_handle_type& native_descriptor, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_descriptor(context, native_descriptor) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a stream descriptor from another. + /** + * This constructor moves a stream descriptor from one object to another. + * + * @param other The other stream descriptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_descriptor(const executor_type&) + * constructor. + */ + basic_stream_descriptor(basic_stream_descriptor&& other) + : descriptor(std::move(other)) + { + } + + /// Move-assign a stream descriptor from another. + /** + * This assignment operator moves a stream descriptor from one object to + * another. + * + * @param other The other stream descriptor object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_descriptor(const executor_type&) + * constructor. + */ + basic_stream_descriptor& operator=(basic_stream_descriptor&& other) + { + descriptor::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Write some data to the descriptor. + /** + * This function is used to write data to the stream descriptor. The function + * call will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the descriptor. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * descriptor.write_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().write_some( + this->impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "write_some"); + return s; + } + + /// Write some data to the descriptor. + /** + * This function is used to write data to the stream descriptor. The function + * call will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the descriptor. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().write_some( + this->impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous write. + /** + * This function is used to asynchronously write data to the stream + * descriptor. The function call always returns immediately. + * + * @param buffers One or more data buffers to be written to the descriptor. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The write operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * descriptor.async_write_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_write_some(this), handler, buffers); + } + + /// Read some data from the descriptor. + /** + * This function is used to read data from the stream descriptor. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * descriptor.read_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().read_some( + this->impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "read_some"); + return s; + } + + /// Read some data from the descriptor. + /** + * This function is used to read data from the stream descriptor. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().read_some( + this->impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous read. + /** + * This function is used to asynchronously read data from the stream + * descriptor. The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The read operation may not read all of the requested number of bytes. + * Consider using the @ref async_read function if you need to ensure that the + * requested amount of data is read before the asynchronous operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * descriptor.async_read_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_read_some(this), handler, buffers); + } + +private: + class initiate_async_write_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_write_some(basic_stream_descriptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_write_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_descriptor* self_; + }; + + class initiate_async_read_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_read_some(basic_stream_descriptor* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_read_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_descriptor* self_; + }; +}; + +} // namespace posix +} // namespace asio + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor.hpp new file mode 100644 index 00000000..baefa136 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor.hpp @@ -0,0 +1,37 @@ +// +// posix/descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POSIX_DESCRIPTOR_HPP +#define ASIO_POSIX_DESCRIPTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/posix/basic_descriptor.hpp" + +namespace asio { +namespace posix { + +/// Typedef for the typical usage of basic_descriptor. +typedef basic_descriptor<> descriptor; + +} // namespace posix +} // namespace asio + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_POSIX_DESCRIPTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor_base.hpp new file mode 100644 index 00000000..feb00179 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/descriptor_base.hpp @@ -0,0 +1,90 @@ +// +// posix/descriptor_base.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POSIX_DESCRIPTOR_BASE_HPP +#define ASIO_POSIX_DESCRIPTOR_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/io_control.hpp" +#include "asio/detail/socket_option.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace posix { + +/// The descriptor_base class is used as a base for the descriptor class as a +/// place to define the associated IO control commands. +class descriptor_base +{ +public: + /// Wait types. + /** + * For use with descriptor::wait() and descriptor::async_wait(). + */ + enum wait_type + { + /// Wait for a descriptor to become ready to read. + wait_read, + + /// Wait for a descriptor to become ready to write. + wait_write, + + /// Wait for a descriptor to have error conditions pending. + wait_error + }; + + /// IO control command to get the amount of data that can be read without + /// blocking. + /** + * Implements the FIONREAD IO control command. + * + * @par Example + * @code + * asio::posix::stream_descriptor descriptor(my_context); + * ... + * asio::descriptor_base::bytes_readable command(true); + * descriptor.io_control(command); + * std::size_t bytes_readable = command.get(); + * @endcode + * + * @par Concepts: + * IoControlCommand. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined bytes_readable; +#else + typedef asio::detail::io_control::bytes_readable bytes_readable; +#endif + +protected: + /// Protected destructor to prevent deletion through this type. + ~descriptor_base() + { + } +}; + +} // namespace posix +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_POSIX_DESCRIPTOR_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/stream_descriptor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/stream_descriptor.hpp new file mode 100644 index 00000000..cd68b603 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/posix/stream_descriptor.hpp @@ -0,0 +1,37 @@ +// +// posix/stream_descriptor.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POSIX_STREAM_DESCRIPTOR_HPP +#define ASIO_POSIX_STREAM_DESCRIPTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/posix/basic_stream_descriptor.hpp" + +namespace asio { +namespace posix { + +/// Typedef for the typical usage of a stream-oriented descriptor. +typedef basic_stream_descriptor<> stream_descriptor; + +} // namespace posix +} // namespace asio + +#endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_POSIX_STREAM_DESCRIPTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/post.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/post.hpp new file mode 100644 index 00000000..bc19d808 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/post.hpp @@ -0,0 +1,123 @@ +// +// post.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_POST_HPP +#define ASIO_POST_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/async_result.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the object's associated + * executor. The function object is queued for execution, and is never called + * from the current thread prior to returning from post(). + * + * The use of @c post(), rather than @ref defer(), indicates the caller's + * preference that the function object be eagerly queued for execution. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex by performing + * get_associated_executor(handler). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Performs ex.post(std::move(handler), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + ASIO_MOVE_ARG(CompletionToken) token); + +/// Submits a completion token or function object for execution. +/** + * This function submits an object for execution using the specified executor. + * The function object is queued for execution, and is never called from the + * current thread prior to returning from post(). + * + * The use of @c post(), rather than @ref defer(), indicates the caller's + * preference that the function object be eagerly queued for execution. + * + * This function has the following effects: + * + * @li Constructs a function object handler of type @c Handler, initialized + * with handler(forward(token)). + * + * @li Constructs an object @c result of type async_result, + * initializing the object as result(handler). + * + * @li Obtains the handler's associated executor object @c ex1 by performing + * get_associated_executor(handler). + * + * @li Creates a work object @c w by performing make_work(ex1). + * + * @li Obtains the handler's associated allocator object @c alloc by performing + * get_associated_allocator(handler). + * + * @li Constructs a function object @c f with a function call operator that + * performs ex1.dispatch(std::move(handler), alloc) followed by + * w.reset(). + * + * @li Performs Executor(ex).post(std::move(f), alloc). + * + * @li Returns result.get(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + const Executor& ex, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN(Executor), + typename enable_if::value>::type* = 0); + +/// Submits a completion token or function object for execution. +/** + * @returns post(ctx.get_executor(), forward(token)). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken, void()) post( + ExecutionContext& ctx, + ASIO_MOVE_ARG(CompletionToken) token + ASIO_DEFAULT_COMPLETION_TOKEN( + typename ExecutionContext::executor_type), + typename enable_if::value>::type* = 0); + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/post.hpp" + +#endif // ASIO_POST_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read.hpp new file mode 100644 index 00000000..f06b01ea --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read.hpp @@ -0,0 +1,1288 @@ +// +// read.hpp +// ~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_READ_HPP +#define ASIO_READ_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/buffer.hpp" +#include "asio/error.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) +# include "asio/basic_streambuf_fwd.hpp" +#endif // !defined(ASIO_NO_EXTENSIONS) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/** + * @defgroup read asio::read + * + * @brief The @c read function is a composed operation that reads a certain + * amount of data from a stream before returning. + */ +/*@{*/ + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read(s, asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read(s, asio::buffer(data, size), ec); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + asio::error_code& ec, + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read(s, asio::buffer(data, size), + * asio::transfer_at_least(32)); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, b, + * asio::transfer_all()); @endcode + */ +template +std::size_t read(SyncReadStream& s, basic_streambuf& b); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, b, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read(SyncReadStream& s, basic_streambuf& b, + asio::error_code& ec); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t read(SyncReadStream& s, basic_streambuf& b, + CompletionCondition completion_condition); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read(SyncReadStream& s, basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::read( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Attempt to read a certain amount of data from a stream before returning. +/** + * This function is used to read a certain number of bytes of data from a + * stream. The call will block until one of the following conditions is true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's read_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/*@}*/ +/** + * @defgroup async_read asio::async_read + * + * @brief The @c async_read function is a composed asynchronous operation that + * reads a certain amount of data from a stream before completion. + */ +/*@{*/ + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. Although the buffers object may be copied as necessary, ownership of + * the underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * asio::async_read(s, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, buffers, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * stream. Although the buffers object may be copied as necessary, ownership of + * the underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's async_read_some function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::async_read(s, + * asio::buffer(data, size), + * asio::transfer_at_least(32), + * handler); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_mutable_buffer_sequence::value + >::type* = 0); + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, buffers, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's async_read_some function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A basic_streambuf object into which the data will be read. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, b, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, basic_streambuf& b, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type)); + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The supplied buffer is full (that is, it has reached maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A basic_streambuf object into which the data will be read. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's async_read_some function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type)); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read( + * s, buffers, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Start an asynchronous operation to read a certain amount of data from a +/// stream. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions is + * true: + * + * @li The specified dynamic buffer sequence is full (that is, it has reached + * maximum size). + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other read operations (such + * as async_read, the stream's async_read_some function, or any other composed + * operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the stream's async_read_some function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes copied into the + * // buffers. If an error occurred, + * // this will be the number of + * // bytes successfully transferred + * // prior to the error. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/read.hpp" + +#endif // ASIO_READ_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_at.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_at.hpp new file mode 100644 index 00000000..b729d101 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_at.hpp @@ -0,0 +1,694 @@ +// +// read_at.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_READ_AT_HPP +#define ASIO_READ_AT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/detail/cstdint.hpp" +#include "asio/error.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) +# include "asio/basic_streambuf_fwd.hpp" +#endif // !defined(ASIO_NO_EXTENSIONS) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/** + * @defgroup read_at asio::read_at + * + * @brief The @c read_at function is a composed operation that reads a certain + * amount of data at the specified offset before returning. + */ +/*@{*/ + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read_at(d, 42, asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::read_at( + * d, 42, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read_at(d, 42, + * asio::buffer(data, size), ec); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::read_at( + * d, 42, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + asio::error_code& ec); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's read_some_at function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::read_at(d, 42, asio::buffer(data, size), + * asio::transfer_at_least(32)); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's read_some_at function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::read_at( + * d, 42, b, + * asio::transfer_all()); @endcode + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::read_at( + * d, 42, b, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b, + asio::error_code& ec); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's read_some_at function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b, + CompletionCondition completion_condition); + +/// Attempt to read a certain amount of data at the specified offset before +/// returning. +/** + * This function is used to read a certain number of bytes of data from a + * random access device at the specified offset. The call will block until one + * of the following conditions is true: + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the SyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b The basic_streambuf object into which the data will be read. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's read_some_at function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t read_at(SyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ +/** + * @defgroup async_read_at asio::async_read_at + * + * @brief The @c async_read_at function is a composed asynchronous operation + * that reads a certain amount of data at the specified offset. + */ +/*@{*/ + +/// Start an asynchronous operation to read a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a random access device at the specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the AsyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. Although the buffers object may be copied as necessary, ownership of + * the underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes copied into the buffers. If an error + * // occurred, this will be the number of bytes successfully + * // transferred prior to the error. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * asio::async_read_at(d, 42, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::async_read_at( + * d, 42, buffers, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, uint64_t offset, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessReadDevice::executor_type)); + +/// Start an asynchronous operation to read a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a random access device at the specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li The supplied buffers are full. That is, the bytes transferred is equal to + * the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * @param d The device from which the data is to be read. The type must support + * the AsyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. The sum + * of the buffer sizes indicates the maximum number of bytes to read from the + * device. Although the buffers object may be copied as necessary, ownership of + * the underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's async_read_some_at function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes copied into the buffers. If an error + * // occurred, this will be the number of bytes successfully + * // transferred prior to the error. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code asio::async_read_at(d, 42, + * asio::buffer(data, size), + * asio::transfer_at_least(32), + * handler); @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, const MutableBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessReadDevice::executor_type)); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Start an asynchronous operation to read a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a random access device at the specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the AsyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b A basic_streambuf object into which the data will be read. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes copied into the buffers. If an error + * // occurred, this will be the number of bytes successfully + * // transferred prior to the error. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note This overload is equivalent to calling: + * @code asio::async_read_at( + * d, 42, b, + * asio::transfer_all(), + * handler); @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessReadDevice::executor_type)); + +/// Start an asynchronous operation to read a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously read a certain number of bytes of + * data from a random access device at the specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_read_some_at function. + * + * @param d The device from which the data is to be read. The type must support + * the AsyncRandomAccessReadDevice concept. + * + * @param offset The offset at which the data will be read. + * + * @param b A basic_streambuf object into which the data will be read. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the read operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_read_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the read operation is complete. A non-zero + * return value indicates the maximum number of bytes to be read on the next + * call to the device's async_read_some_at function. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes copied into the buffers. If an error + * // occurred, this will be the number of bytes successfully + * // transferred prior to the error. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_at(AsyncRandomAccessReadDevice& d, + uint64_t offset, basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessReadDevice::executor_type)); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/read_at.hpp" + +#endif // ASIO_READ_AT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_until.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_until.hpp new file mode 100644 index 00000000..6d09d1ce --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/read_until.hpp @@ -0,0 +1,2863 @@ +// +// read_until.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_READ_UNTIL_HPP +#define ASIO_READ_UNTIL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include +#include "asio/async_result.hpp" +#include "asio/buffer.hpp" +#include "asio/detail/regex_fwd.hpp" +#include "asio/detail/string_view.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) +# include "asio/basic_streambuf_fwd.hpp" +#endif // !defined(ASIO_NO_EXTENSIONS) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +namespace detail +{ + char (&has_result_type_helper(...))[2]; + + template + char has_result_type_helper(T*, typename T::result_type* = 0); + + template + struct has_result_type + { + enum { value = (sizeof((has_result_type_helper)((T*)(0))) == 1) }; + }; +} // namespace detail + +/// Type trait used to determine whether a type can be used as a match condition +/// function with read_until and async_read_until. +template +struct is_match_condition +{ +#if defined(GENERATING_DOCUMENTATION) + /// The value member is true if the type may be used as a match condition. + static const bool value; +#else + enum + { + value = asio::is_function< + typename asio::remove_pointer::type>::value + || detail::has_result_type::value + }; +#endif +}; + +/** + * @defgroup read_until asio::read_until + * + * @brief The @c read_until function is a composed operation that reads data + * into a dynamic buffer sequence, or into a streambuf, until it contains a + * delimiter, matches a regular expression, or a function object indicates a + * match. + */ +/*@{*/ + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter character. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a newline is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), '\n'); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, char delim, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter character. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + char delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter string. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a CR-LF sequence is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), "\r\n"); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter string. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Read data into a dynamic buffer sequence until some part of the data it +/// contains matches a regular expression. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains some data + * that matches a regular expression. The call will block until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the + * regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains data that matches the regular expression, the function returns + * immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param expr The regular expression. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the substring that matches the regular expression. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a CR-LF sequence is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), boost::regex("\r\n")); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until some part of the data it +/// contains matches a regular expression. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains some data + * that matches a regular expression. The call will block until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the + * regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains data that matches the regular expression, the function returns + * immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param expr The regular expression. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the substring that matches the regular expression. Returns 0 + * if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Read data into a dynamic buffer sequence until a function object indicates a +/// match. + +/** + * This function is used to read data into the specified dynamic buffer + * sequence until a user-defined match condition function object, when applied + * to the data contained in the dynamic buffer sequence, indicates a successful + * match. The call will block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @returns The number of bytes in the dynamic_buffer's get area that + * have been fully consumed by the match function. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the function object. + * An application will typically leave that data in the dynamic buffer sequence + * for a subsequent read_until operation to examine. + + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To read data into a dynamic buffer sequence until whitespace is encountered: + * @code typedef asio::buffers_iterator< + * asio::const_buffers_1> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * std::string data; + * asio::read_until(s, data, match_whitespace); + * @endcode + * + * To read data into a @c std::string until a matching character is found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * std::string data; + * asio::read_until(s, data, match_char('a')); + * @endcode + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until a function object indicates a +/// match. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until a user-defined match condition function object, when applied + * to the data contained in the dynamic buffer sequence, indicates a successful + * match. The call will block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area that + * have been fully consumed by the match function. Returns 0 if an error + * occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the function object. + * An application will typically leave that data in the dynamic buffer sequence + * for a subsequent read_until operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + */ +template +std::size_t read_until(SyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_IOSTREAM) + +/// Read data into a streambuf until it contains a specified delimiter. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains the specified delimiter. The call will block + * until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains the + * delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param delim The delimiter character. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the delimiter. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond the delimiter. An application will typically leave + * that data in the streambuf for a subsequent read_until operation to examine. + * + * @par Example + * To read data into a streambuf until a newline is encountered: + * @code asio::streambuf b; + * asio::read_until(s, b, '\n'); + * std::istream is(&b); + * std::string line; + * std::getline(is, line); @endcode + * After the @c read_until operation completes successfully, the buffer @c b + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, char delim); + +/// Read data into a streambuf until it contains a specified delimiter. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains the specified delimiter. The call will block + * until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains the + * delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param delim The delimiter character. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond the delimiter. An application will typically leave + * that data in the streambuf for a subsequent read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, char delim, + asio::error_code& ec); + +/// Read data into a streambuf until it contains a specified delimiter. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains the specified delimiter. The call will block + * until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains the + * delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param delim The delimiter string. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the delimiter. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond the delimiter. An application will typically leave + * that data in the streambuf for a subsequent read_until operation to examine. + * + * @par Example + * To read data into a streambuf until a newline is encountered: + * @code asio::streambuf b; + * asio::read_until(s, b, "\r\n"); + * std::istream is(&b); + * std::string line; + * std::getline(is, line); @endcode + * After the @c read_until operation completes successfully, the buffer @c b + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim); + +/// Read data into a streambuf until it contains a specified delimiter. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains the specified delimiter. The call will block + * until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains the + * delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param delim The delimiter string. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond the delimiter. An application will typically leave + * that data in the streambuf for a subsequent read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec); + +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Read data into a streambuf until some part of the data it contains matches +/// a regular expression. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains some data that matches a regular expression. + * The call will block until one of the following conditions is true: + * + * @li A substring of the streambuf's get area matches the regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains data that + * matches the regular expression, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param expr The regular expression. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the substring that matches the regular expression. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond that which matched the regular expression. An + * application will typically leave that data in the streambuf for a subsequent + * read_until operation to examine. + * + * @par Example + * To read data into a streambuf until a CR-LF sequence is encountered: + * @code asio::streambuf b; + * asio::read_until(s, b, boost::regex("\r\n")); + * std::istream is(&b); + * std::string line; + * std::getline(is, line); @endcode + * After the @c read_until operation completes successfully, the buffer @c b + * contains the data which matched the regular expression: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr); + +/// Read data into a streambuf until some part of the data it contains matches +/// a regular expression. +/** + * This function is used to read data into the specified streambuf until the + * streambuf's get area contains some data that matches a regular expression. + * The call will block until one of the following conditions is true: + * + * @li A substring of the streambuf's get area matches the regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the streambuf's get area already contains data that + * matches the regular expression, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param expr The regular expression. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the streambuf's get area up to and including + * the substring that matches the regular expression. Returns 0 if an error + * occurred. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond that which matched the regular expression. An + * application will typically leave that data in the streambuf for a subsequent + * read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr, + asio::error_code& ec); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Read data into a streambuf until a function object indicates a match. +/** + * This function is used to read data into the specified streambuf until a + * user-defined match condition function object, when applied to the data + * contained in the streambuf, indicates a successful match. The call will + * block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator::const_buffers_type> + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @returns The number of bytes in the streambuf's get area that have been fully + * consumed by the match function. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond that which matched the function object. An application + * will typically leave that data in the streambuf for a subsequent read_until + * operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To read data into a streambuf until whitespace is encountered: + * @code typedef asio::buffers_iterator< + * asio::streambuf::const_buffers_type> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * asio::streambuf b; + * asio::read_until(s, b, match_whitespace); + * @endcode + * + * To read data into a streambuf until a matching character is found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * asio::streambuf b; + * asio::read_until(s, b, match_char('a')); + * @endcode + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, MatchCondition match_condition, + typename enable_if::value>::type* = 0); + +/// Read data into a streambuf until a function object indicates a match. +/** + * This function is used to read data into the specified streambuf until a + * user-defined match condition function object, when applied to the data + * contained in the streambuf, indicates a successful match. The call will + * block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator::const_buffers_type> + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the streambuf's get area that have been fully + * consumed by the match function. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the streambuf may contain + * additional data beyond that which matched the function object. An application + * will typically leave that data in the streambuf for a subsequent read_until + * operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + */ +template +std::size_t read_until(SyncReadStream& s, + asio::basic_streambuf& b, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if::value>::type* = 0); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter character. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a newline is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), '\n'); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, char delim, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter character. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + char delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter string. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a CR-LF sequence is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), "\r\n"); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_STRING_VIEW_PARAM delim, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until it contains a specified +/// delimiter. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains the specified + * delimiter. The call will block until one of the following conditions is + * true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains the delimiter, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * + * @param delim The delimiter string. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the delimiter. Returns 0 if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond the delimiter. An application will + * typically leave that data in the dynamic buffer sequence for a subsequent + * read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_STRING_VIEW_PARAM delim, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Read data into a dynamic buffer sequence until some part of the data it +/// contains matches a regular expression. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains some data + * that matches a regular expression. The call will block until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the + * regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains data that matches the regular expression, the function returns + * immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param expr The regular expression. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the substring that matches the regular expression. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent read_until operation to examine. + * + * @par Example + * To read data into a @c std::string until a CR-LF sequence is encountered: + * @code std::string data; + * std::string n = asio::read_until(s, + * asio::dynamic_buffer(data), boost::regex("\r\n")); + * std::string line = data.substr(0, n); + * data.erase(0, n); @endcode + * After the @c read_until operation completes successfully, the string @c data + * contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c b as + * follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c read_until operation. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + const boost::regex& expr, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until some part of the data it +/// contains matches a regular expression. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until the dynamic buffer sequence's get area contains some data + * that matches a regular expression. The call will block until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the + * regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the dynamic buffer sequence's get area already + * contains data that matches the regular expression, the function returns + * immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param expr The regular expression. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area up to + * and including the substring that matches the regular expression. Returns 0 + * if an error occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent read_until operation to examine. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + const boost::regex& expr, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Read data into a dynamic buffer sequence until a function object indicates a +/// match. + +/** + * This function is used to read data into the specified dynamic buffer + * sequence until a user-defined match condition function object, when applied + * to the data contained in the dynamic buffer sequence, indicates a successful + * match. The call will block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @returns The number of bytes in the dynamic_buffer's get area that + * have been fully consumed by the match function. + * + * @throws asio::system_error Thrown on failure. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the function object. + * An application will typically leave that data in the dynamic buffer sequence + * for a subsequent read_until operation to examine. + + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To read data into a dynamic buffer sequence until whitespace is encountered: + * @code typedef asio::buffers_iterator< + * asio::const_buffers_1> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * std::string data; + * asio::read_until(s, data, match_whitespace); + * @endcode + * + * To read data into a @c std::string until a matching character is found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * std::string data; + * asio::read_until(s, data, match_char('a')); + * @endcode + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + MatchCondition match_condition, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type* = 0); + +/// Read data into a dynamic buffer sequence until a function object indicates a +/// match. +/** + * This function is used to read data into the specified dynamic buffer + * sequence until a user-defined match condition function object, when applied + * to the data contained in the dynamic buffer sequence, indicates a successful + * match. The call will block until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * read_some function. If the match condition function object already indicates + * a match, the function returns immediately. + * + * @param s The stream from which the data is to be read. The type must support + * the SyncReadStream concept. + * + * @param buffers A dynamic buffer sequence into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes in the dynamic buffer sequence's get area that + * have been fully consumed by the match function. Returns 0 if an error + * occurred. + * + * @note After a successful read_until operation, the dynamic buffer sequence + * may contain additional data beyond that which matched the function object. + * An application will typically leave that data in the dynamic buffer sequence + * for a subsequent read_until operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + */ +template +std::size_t read_until(SyncReadStream& s, DynamicBuffer_v2 buffers, + MatchCondition match_condition, asio::error_code& ec, + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type* = 0); + +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ +/** + * @defgroup async_read_until asio::async_read_until + * + * @brief The @c async_read_until function is a composed asynchronous operation + * that reads data into a dynamic buffer sequence, or into a streambuf, until + * it contains a delimiter, matches a regular expression, or a function object + * indicates a match. + */ +/*@{*/ + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until it contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains the + * specified delimiter. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains the delimiter, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param delim The delimiter character. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond the delimiter. An application + * will typically leave that data in the dynamic buffer sequence for a + * subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a newline is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, '\n', handler); @endcode + * After the @c async_read_until operation completes successfully, the buffer + * @c data contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, char delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until it contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains the + * specified delimiter. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains the delimiter, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param delim The delimiter string. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond the delimiter. An application + * will typically leave that data in the dynamic buffer sequence for a + * subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a CR-LF sequence is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, "\r\n", handler); @endcode + * After the @c async_read_until operation completes successfully, the string + * @c data contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the string @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until some part of its data matches a regular expression. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains some + * data that matches a regular expression. The function call always returns + * immediately. The asynchronous operation will continue until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the regular + * expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains data that matches + * the regular expression, this asynchronous operation completes immediately. + * The program must ensure that the stream performs no other read operations + * (such as async_read, async_read_until, the stream's async_read_some + * function, or any other composed operations that perform reads) until this + * operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param expr The regular expression. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer + * // sequence's get area up to and including the + * // substring that matches the regular expression. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a CR-LF sequence is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, + * boost::regex("\r\n"), handler); @endcode + * After the @c async_read_until operation completes successfully, the string + * @c data contains the data which matched the regular expression: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the match, + * so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the string @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until a function object indicates a match. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until a user-defined match condition function object, when + * applied to the data contained in the dynamic buffer sequence, indicates a + * successful match. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the match condition function object already indicates a match, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area that have been fully consumed by the match + * // function. O if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond that which matched the function + * object. An application will typically leave that data in the dynamic buffer + * sequence for a subsequent async_read_until operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To asynchronously read data into a @c std::string until whitespace is + * encountered: + * @code typedef asio::buffers_iterator< + * asio::const_buffers_1> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * std::string data; + * asio::async_read_until(s, data, match_whitespace, handler); + * @endcode + * + * To asynchronously read data into a @c std::string until a matching character + * is found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * std::string data; + * asio::async_read_until(s, data, match_char('a'), handler); + * @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + MatchCondition match_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_IOSTREAM) + +/// Start an asynchronous operation to read data into a streambuf until it +/// contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified + * streambuf until the streambuf's get area contains the specified delimiter. + * The function call always returns immediately. The asynchronous operation + * will continue until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the streambuf's get area already contains the delimiter, this asynchronous + * operation completes immediately. The program must ensure that the stream + * performs no other read operations (such as async_read, async_read_until, the + * stream's async_read_some function, or any other composed operations that + * perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. Ownership of + * the streambuf is retained by the caller, which must guarantee that it remains + * valid until the handler is called. + * + * @param delim The delimiter character. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the streambuf's get + * // area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the streambuf may + * contain additional data beyond the delimiter. An application will typically + * leave that data in the streambuf for a subsequent async_read_until operation + * to examine. + * + * @par Example + * To asynchronously read data into a streambuf until a newline is encountered: + * @code asio::streambuf b; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::istream is(&b); + * std::string line; + * std::getline(is, line); + * ... + * } + * } + * ... + * asio::async_read_until(s, b, '\n', handler); @endcode + * After the @c async_read_until operation completes successfully, the buffer + * @c b contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, char delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type)); + +/// Start an asynchronous operation to read data into a streambuf until it +/// contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified + * streambuf until the streambuf's get area contains the specified delimiter. + * The function call always returns immediately. The asynchronous operation + * will continue until one of the following conditions is true: + * + * @li The get area of the streambuf contains the specified delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the streambuf's get area already contains the delimiter, this asynchronous + * operation completes immediately. The program must ensure that the stream + * performs no other read operations (such as async_read, async_read_until, the + * stream's async_read_some function, or any other composed operations that + * perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. Ownership of + * the streambuf is retained by the caller, which must guarantee that it remains + * valid until the handler is called. + * + * @param delim The delimiter string. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the streambuf's get + * // area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the streambuf may + * contain additional data beyond the delimiter. An application will typically + * leave that data in the streambuf for a subsequent async_read_until operation + * to examine. + * + * @par Example + * To asynchronously read data into a streambuf until a newline is encountered: + * @code asio::streambuf b; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::istream is(&b); + * std::string line; + * std::getline(is, line); + * ... + * } + * } + * ... + * asio::async_read_until(s, b, "\r\n", handler); @endcode + * After the @c async_read_until operation completes successfully, the buffer + * @c b contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type)); + +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a streambuf until some +/// part of its data matches a regular expression. +/** + * This function is used to asynchronously read data into the specified + * streambuf until the streambuf's get area contains some data that matches a + * regular expression. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li A substring of the streambuf's get area matches the regular expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the streambuf's get area already contains data that matches the regular + * expression, this asynchronous operation completes immediately. The program + * must ensure that the stream performs no other read operations (such as + * async_read, async_read_until, the stream's async_read_some function, or any + * other composed operations that perform reads) until this operation + * completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. Ownership of + * the streambuf is retained by the caller, which must guarantee that it remains + * valid until the handler is called. + * + * @param expr The regular expression. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the streambuf's get + * // area up to and including the substring + * // that matches the regular. expression. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the streambuf may + * contain additional data beyond that which matched the regular expression. An + * application will typically leave that data in the streambuf for a subsequent + * async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a streambuf until a CR-LF sequence is + * encountered: + * @code asio::streambuf b; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::istream is(&b); + * std::string line; + * std::getline(is, line); + * ... + * } + * } + * ... + * asio::async_read_until(s, b, boost::regex("\r\n"), handler); @endcode + * After the @c async_read_until operation completes successfully, the buffer + * @c b contains the data which matched the regular expression: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c std::getline then extracts the data up to and including the + * newline (which is discarded), so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r' } @endcode + * The remaining data is left in the buffer @c b as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type)); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a streambuf until a +/// function object indicates a match. +/** + * This function is used to asynchronously read data into the specified + * streambuf until a user-defined match condition function object, when applied + * to the data contained in the streambuf, indicates a successful match. The + * function call always returns immediately. The asynchronous operation will + * continue until one of the following conditions is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the match condition function object already indicates a match, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param b A streambuf object into which the data will be read. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator::const_buffers_type> + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the streambuf's get + * // area that have been fully consumed by the + * // match function. O if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the streambuf may + * contain additional data beyond that which matched the function object. An + * application will typically leave that data in the streambuf for a subsequent + * async_read_until operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To asynchronously read data into a streambuf until whitespace is encountered: + * @code typedef asio::buffers_iterator< + * asio::streambuf::const_buffers_type> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * asio::streambuf b; + * asio::async_read_until(s, b, match_whitespace, handler); + * @endcode + * + * To asynchronously read data into a streambuf until a matching character is + * found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * asio::streambuf b; + * asio::async_read_until(s, b, match_char('a'), handler); + * @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, + asio::basic_streambuf& b, + MatchCondition match_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if::value>::type* = 0); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until it contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains the + * specified delimiter. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains the delimiter, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param delim The delimiter character. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond the delimiter. An application + * will typically leave that data in the dynamic buffer sequence for a + * subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a newline is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, '\n', handler); @endcode + * After the @c async_read_until operation completes successfully, the buffer + * @c data contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the buffer @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, char delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until it contains a specified delimiter. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains the + * specified delimiter. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The get area of the dynamic buffer sequence contains the specified + * delimiter. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains the delimiter, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param delim The delimiter string. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area up to and including the delimiter. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond the delimiter. An application + * will typically leave that data in the dynamic buffer sequence for a + * subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a CR-LF sequence is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, "\r\n", handler); @endcode + * After the @c async_read_until operation completes successfully, the string + * @c data contains the delimiter: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the + * delimiter, so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the string @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + ASIO_STRING_VIEW_PARAM delim, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if defined(ASIO_HAS_BOOST_REGEX) \ + || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until some part of its data matches a regular expression. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until the dynamic buffer sequence's get area contains some + * data that matches a regular expression. The function call always returns + * immediately. The asynchronous operation will continue until one of the + * following conditions is true: + * + * @li A substring of the dynamic buffer sequence's get area matches the regular + * expression. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the dynamic buffer sequence's get area already contains data that matches + * the regular expression, this asynchronous operation completes immediately. + * The program must ensure that the stream performs no other read operations + * (such as async_read, async_read_until, the stream's async_read_some + * function, or any other composed operations that perform reads) until this + * operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param expr The regular expression. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer + * // sequence's get area up to and including the + * // substring that matches the regular expression. + * // 0 if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond that which matched the regular + * expression. An application will typically leave that data in the dynamic + * buffer sequence for a subsequent async_read_until operation to examine. + * + * @par Example + * To asynchronously read data into a @c std::string until a CR-LF sequence is + * encountered: + * @code std::string data; + * ... + * void handler(const asio::error_code& e, std::size_t size) + * { + * if (!e) + * { + * std::string line = data.substr(0, n); + * data.erase(0, n); + * ... + * } + * } + * ... + * asio::async_read_until(s, data, + * boost::regex("\r\n"), handler); @endcode + * After the @c async_read_until operation completes successfully, the string + * @c data contains the data which matched the regular expression: + * @code { 'a', 'b', ..., 'c', '\r', '\n', 'd', 'e', ... } @endcode + * The call to @c substr then extracts the data up to and including the match, + * so that the string @c line contains: + * @code { 'a', 'b', ..., 'c', '\r', '\n' } @endcode + * After the call to @c erase, the remaining data is left in the string @c data + * as follows: + * @code { 'd', 'e', ... } @endcode + * This data may be the start of a new line, to be extracted by a subsequent + * @c async_read_until operation. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + const boost::regex& expr, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +#endif // defined(ASIO_HAS_BOOST_REGEX) + // || defined(GENERATING_DOCUMENTATION) + +/// Start an asynchronous operation to read data into a dynamic buffer sequence +/// until a function object indicates a match. +/** + * This function is used to asynchronously read data into the specified dynamic + * buffer sequence until a user-defined match condition function object, when + * applied to the data contained in the dynamic buffer sequence, indicates a + * successful match. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li The match condition function object returns a std::pair where the second + * element evaluates to true. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_read_some function, and is known as a composed operation. If + * the match condition function object already indicates a match, this + * asynchronous operation completes immediately. The program must ensure that + * the stream performs no other read operations (such as async_read, + * async_read_until, the stream's async_read_some function, or any other + * composed operations that perform reads) until this operation completes. + * + * @param s The stream from which the data is to be read. The type must support + * the AsyncReadStream concept. + * + * @param buffers The dynamic buffer sequence into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param match_condition The function object to be called to determine whether + * a match exists. The signature of the function object must be: + * @code pair match_condition(iterator begin, iterator end); + * @endcode + * where @c iterator represents the type: + * @code buffers_iterator + * @endcode + * The iterator parameters @c begin and @c end define the range of bytes to be + * scanned to determine whether there is a match. The @c first member of the + * return value is an iterator marking one-past-the-end of the bytes that have + * been consumed by the match function. This iterator is used to calculate the + * @c begin parameter for any subsequent invocation of the match condition. The + * @c second member of the return value is true if a match has been found, false + * otherwise. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // The number of bytes in the dynamic buffer sequence's + * // get area that have been fully consumed by the match + * // function. O if an error occurred. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note After a successful async_read_until operation, the dynamic buffer + * sequence may contain additional data beyond that which matched the function + * object. An application will typically leave that data in the dynamic buffer + * sequence for a subsequent async_read_until operation to examine. + * + * @note The default implementation of the @c is_match_condition type trait + * evaluates to true for function pointers and function objects with a + * @c result_type typedef. It must be specialised for other user-defined + * function objects. + * + * @par Examples + * To asynchronously read data into a @c std::string until whitespace is + * encountered: + * @code typedef asio::buffers_iterator< + * asio::const_buffers_1> iterator; + * + * std::pair + * match_whitespace(iterator begin, iterator end) + * { + * iterator i = begin; + * while (i != end) + * if (std::isspace(*i++)) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * std::string data; + * asio::async_read_until(s, data, match_whitespace, handler); + * @endcode + * + * To asynchronously read data into a @c std::string until a matching character + * is found: + * @code class match_char + * { + * public: + * explicit match_char(char c) : c_(c) {} + * + * template + * std::pair operator()( + * Iterator begin, Iterator end) const + * { + * Iterator i = begin; + * while (i != end) + * if (c_ == *i++) + * return std::make_pair(i, true); + * return std::make_pair(i, false); + * } + * + * private: + * char c_; + * }; + * + * namespace asio { + * template <> struct is_match_condition + * : public boost::true_type {}; + * } // namespace asio + * ... + * void handler(const asio::error_code& e, std::size_t size); + * ... + * std::string data; + * asio::async_read_until(s, data, match_char('a'), handler); + * @endcode + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) +async_read_until(AsyncReadStream& s, DynamicBuffer_v2 buffers, + MatchCondition match_condition, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncReadStream::executor_type), + typename enable_if< + is_match_condition::value + && is_dynamic_buffer_v2::value + >::type* = 0); + +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/read_until.hpp" + +#endif // ASIO_READ_UNTIL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/redirect_error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/redirect_error.hpp new file mode 100644 index 00000000..d7740b9b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/redirect_error.hpp @@ -0,0 +1,66 @@ +// +// redirect_error.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_REDIRECT_ERROR_HPP +#define ASIO_REDIRECT_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/error_code.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Completion token type used to specify that an error produced by an +/// asynchronous operation is captured to an error_code variable. +/** + * The redirect_error_t class is used to indicate that any error_code produced + * by an asynchronous operation is captured to a specified variable. + */ +template +class redirect_error_t +{ +public: + /// Constructor. + template + redirect_error_t(ASIO_MOVE_ARG(T) completion_token, + asio::error_code& ec) + : token_(ASIO_MOVE_CAST(T)(completion_token)), + ec_(ec) + { + } + +//private: + CompletionToken token_; + asio::error_code& ec_; +}; + +/// Create a completion token to capture error_code values to a variable. +template +inline redirect_error_t::type> redirect_error( + ASIO_MOVE_ARG(CompletionToken) completion_token, + asio::error_code& ec) +{ + return redirect_error_t::type>( + ASIO_MOVE_CAST(CompletionToken)(completion_token), ec); +} + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/redirect_error.hpp" + +#endif // ASIO_REDIRECT_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port.hpp new file mode 100644 index 00000000..4551f77d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port.hpp @@ -0,0 +1,36 @@ +// +// serial_port.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SERIAL_PORT_HPP +#define ASIO_SERIAL_PORT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_SERIAL_PORT) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_serial_port.hpp" + +namespace asio { + +/// Typedef for the typical usage of a serial port. +typedef basic_serial_port<> serial_port; + +} // namespace asio + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_SERIAL_PORT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port_base.hpp new file mode 100644 index 00000000..f0a9ca6d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/serial_port_base.hpp @@ -0,0 +1,167 @@ +// +// serial_port_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SERIAL_PORT_BASE_HPP +#define ASIO_SERIAL_PORT_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_SERIAL_PORT) \ + || defined(GENERATING_DOCUMENTATION) + +#if !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) +# include +#endif // !defined(ASIO_WINDOWS) && !defined(__CYGWIN__) + +#include "asio/detail/socket_types.hpp" +#include "asio/error_code.hpp" + +#if defined(GENERATING_DOCUMENTATION) +# define ASIO_OPTION_STORAGE implementation_defined +#elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) +# define ASIO_OPTION_STORAGE DCB +#else +# define ASIO_OPTION_STORAGE termios +#endif + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// The serial_port_base class is used as a base for the basic_serial_port class +/// template so that we have a common place to define the serial port options. +class serial_port_base +{ +public: + /// Serial port option to permit changing the baud rate. + /** + * Implements changing the baud rate for a given serial port. + */ + class baud_rate + { + public: + explicit baud_rate(unsigned int rate = 0); + unsigned int value() const; + ASIO_DECL ASIO_SYNC_OP_VOID store( + ASIO_OPTION_STORAGE& storage, + asio::error_code& ec) const; + ASIO_DECL ASIO_SYNC_OP_VOID load( + const ASIO_OPTION_STORAGE& storage, + asio::error_code& ec); + private: + unsigned int value_; + }; + + /// Serial port option to permit changing the flow control. + /** + * Implements changing the flow control for a given serial port. + */ + class flow_control + { + public: + enum type { none, software, hardware }; + ASIO_DECL explicit flow_control(type t = none); + type value() const; + ASIO_DECL ASIO_SYNC_OP_VOID store( + ASIO_OPTION_STORAGE& storage, + asio::error_code& ec) const; + ASIO_DECL ASIO_SYNC_OP_VOID load( + const ASIO_OPTION_STORAGE& storage, + asio::error_code& ec); + private: + type value_; + }; + + /// Serial port option to permit changing the parity. + /** + * Implements changing the parity for a given serial port. + */ + class parity + { + public: + enum type { none, odd, even }; + ASIO_DECL explicit parity(type t = none); + type value() const; + ASIO_DECL ASIO_SYNC_OP_VOID store( + ASIO_OPTION_STORAGE& storage, + asio::error_code& ec) const; + ASIO_DECL ASIO_SYNC_OP_VOID load( + const ASIO_OPTION_STORAGE& storage, + asio::error_code& ec); + private: + type value_; + }; + + /// Serial port option to permit changing the number of stop bits. + /** + * Implements changing the number of stop bits for a given serial port. + */ + class stop_bits + { + public: + enum type { one, onepointfive, two }; + ASIO_DECL explicit stop_bits(type t = one); + type value() const; + ASIO_DECL ASIO_SYNC_OP_VOID store( + ASIO_OPTION_STORAGE& storage, + asio::error_code& ec) const; + ASIO_DECL ASIO_SYNC_OP_VOID load( + const ASIO_OPTION_STORAGE& storage, + asio::error_code& ec); + private: + type value_; + }; + + /// Serial port option to permit changing the character size. + /** + * Implements changing the character size for a given serial port. + */ + class character_size + { + public: + ASIO_DECL explicit character_size(unsigned int t = 8); + unsigned int value() const; + ASIO_DECL ASIO_SYNC_OP_VOID store( + ASIO_OPTION_STORAGE& storage, + asio::error_code& ec) const; + ASIO_DECL ASIO_SYNC_OP_VOID load( + const ASIO_OPTION_STORAGE& storage, + asio::error_code& ec); + private: + unsigned int value_; + }; + +protected: + /// Protected destructor to prevent deletion through this type. + ~serial_port_base() + { + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#undef ASIO_OPTION_STORAGE + +#include "asio/impl/serial_port_base.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/serial_port_base.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // defined(ASIO_HAS_SERIAL_PORT) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_SERIAL_PORT_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/signal_set.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/signal_set.hpp new file mode 100644 index 00000000..6a27689a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/signal_set.hpp @@ -0,0 +1,28 @@ +// +// signal_set.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SIGNAL_SET_HPP +#define ASIO_SIGNAL_SET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/basic_signal_set.hpp" + +namespace asio { + +/// Typedef for the typical usage of a signal set. +typedef basic_signal_set<> signal_set; + +} // namespace asio + +#endif // ASIO_SIGNAL_SET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/socket_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/socket_base.hpp new file mode 100644 index 00000000..bf06c8c8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/socket_base.hpp @@ -0,0 +1,559 @@ +// +// socket_base.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SOCKET_BASE_HPP +#define ASIO_SOCKET_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/io_control.hpp" +#include "asio/detail/socket_option.hpp" +#include "asio/detail/socket_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// The socket_base class is used as a base for the basic_stream_socket and +/// basic_datagram_socket class templates so that we have a common place to +/// define the shutdown_type and enum. +class socket_base +{ +public: + /// Different ways a socket may be shutdown. + enum shutdown_type + { +#if defined(GENERATING_DOCUMENTATION) + /// Shutdown the receive side of the socket. + shutdown_receive = implementation_defined, + + /// Shutdown the send side of the socket. + shutdown_send = implementation_defined, + + /// Shutdown both send and receive on the socket. + shutdown_both = implementation_defined +#else + shutdown_receive = ASIO_OS_DEF(SHUT_RD), + shutdown_send = ASIO_OS_DEF(SHUT_WR), + shutdown_both = ASIO_OS_DEF(SHUT_RDWR) +#endif + }; + + /// Bitmask type for flags that can be passed to send and receive operations. + typedef int message_flags; + +#if defined(GENERATING_DOCUMENTATION) + /// Peek at incoming data without removing it from the input queue. + static const int message_peek = implementation_defined; + + /// Process out-of-band data. + static const int message_out_of_band = implementation_defined; + + /// Specify that the data should not be subject to routing. + static const int message_do_not_route = implementation_defined; + + /// Specifies that the data marks the end of a record. + static const int message_end_of_record = implementation_defined; +#else + ASIO_STATIC_CONSTANT(int, + message_peek = ASIO_OS_DEF(MSG_PEEK)); + ASIO_STATIC_CONSTANT(int, + message_out_of_band = ASIO_OS_DEF(MSG_OOB)); + ASIO_STATIC_CONSTANT(int, + message_do_not_route = ASIO_OS_DEF(MSG_DONTROUTE)); + ASIO_STATIC_CONSTANT(int, + message_end_of_record = ASIO_OS_DEF(MSG_EOR)); +#endif + + /// Wait types. + /** + * For use with basic_socket::wait() and basic_socket::async_wait(). + */ + enum wait_type + { + /// Wait for a socket to become ready to read. + wait_read, + + /// Wait for a socket to become ready to write. + wait_write, + + /// Wait for a socket to have error conditions pending. + wait_error + }; + + /// Socket option to permit sending of broadcast messages. + /** + * Implements the SOL_SOCKET/SO_BROADCAST socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::socket_base::broadcast option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::socket_base::broadcast option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined broadcast; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_BROADCAST)> + broadcast; +#endif + + /// Socket option to enable socket-level debugging. + /** + * Implements the SOL_SOCKET/SO_DEBUG socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::debug option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::debug option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined debug; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_DEBUG)> debug; +#endif + + /// Socket option to prevent routing, use local interfaces only. + /** + * Implements the SOL_SOCKET/SO_DONTROUTE socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::socket_base::do_not_route option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::udp::socket socket(my_context); + * ... + * asio::socket_base::do_not_route option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined do_not_route; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_DONTROUTE)> + do_not_route; +#endif + + /// Socket option to send keep-alives. + /** + * Implements the SOL_SOCKET/SO_KEEPALIVE socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::keep_alive option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::keep_alive option; + * socket.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined keep_alive; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_KEEPALIVE)> keep_alive; +#endif + + /// Socket option for the send buffer size of a socket. + /** + * Implements the SOL_SOCKET/SO_SNDBUF socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::send_buffer_size option(8192); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::send_buffer_size option; + * socket.get_option(option); + * int size = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Integer_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined send_buffer_size; +#else + typedef asio::detail::socket_option::integer< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_SNDBUF)> + send_buffer_size; +#endif + + /// Socket option for the send low watermark. + /** + * Implements the SOL_SOCKET/SO_SNDLOWAT socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::send_low_watermark option(1024); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::send_low_watermark option; + * socket.get_option(option); + * int size = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Integer_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined send_low_watermark; +#else + typedef asio::detail::socket_option::integer< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_SNDLOWAT)> + send_low_watermark; +#endif + + /// Socket option for the receive buffer size of a socket. + /** + * Implements the SOL_SOCKET/SO_RCVBUF socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::receive_buffer_size option(8192); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::receive_buffer_size option; + * socket.get_option(option); + * int size = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Integer_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined receive_buffer_size; +#else + typedef asio::detail::socket_option::integer< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_RCVBUF)> + receive_buffer_size; +#endif + + /// Socket option for the receive low watermark. + /** + * Implements the SOL_SOCKET/SO_RCVLOWAT socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::receive_low_watermark option(1024); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::receive_low_watermark option; + * socket.get_option(option); + * int size = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Integer_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined receive_low_watermark; +#else + typedef asio::detail::socket_option::integer< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_RCVLOWAT)> + receive_low_watermark; +#endif + + /// Socket option to allow the socket to be bound to an address that is + /// already in use. + /** + * Implements the SOL_SOCKET/SO_REUSEADDR socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::socket_base::reuse_address option(true); + * acceptor.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::socket_base::reuse_address option; + * acceptor.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined reuse_address; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_REUSEADDR)> + reuse_address; +#endif + + /// Socket option to specify whether the socket lingers on close if unsent + /// data is present. + /** + * Implements the SOL_SOCKET/SO_LINGER socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::linger option(true, 30); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::linger option; + * socket.get_option(option); + * bool is_set = option.enabled(); + * unsigned short timeout = option.timeout(); + * @endcode + * + * @par Concepts: + * Socket_Option, Linger_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined linger; +#else + typedef asio::detail::socket_option::linger< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_LINGER)> + linger; +#endif + + /// Socket option for putting received out-of-band data inline. + /** + * Implements the SOL_SOCKET/SO_OOBINLINE socket option. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::out_of_band_inline option(true); + * socket.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::out_of_band_inline option; + * socket.get_option(option); + * bool value = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined out_of_band_inline; +#else + typedef asio::detail::socket_option::boolean< + ASIO_OS_DEF(SOL_SOCKET), ASIO_OS_DEF(SO_OOBINLINE)> + out_of_band_inline; +#endif + + /// Socket option to report aborted connections on accept. + /** + * Implements a custom socket option that determines whether or not an accept + * operation is permitted to fail with asio::error::connection_aborted. + * By default the option is false. + * + * @par Examples + * Setting the option: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::socket_base::enable_connection_aborted option(true); + * acceptor.set_option(option); + * @endcode + * + * @par + * Getting the current option value: + * @code + * asio::ip::tcp::acceptor acceptor(my_context); + * ... + * asio::socket_base::enable_connection_aborted option; + * acceptor.get_option(option); + * bool is_set = option.value(); + * @endcode + * + * @par Concepts: + * Socket_Option, Boolean_Socket_Option. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined enable_connection_aborted; +#else + typedef asio::detail::socket_option::boolean< + asio::detail::custom_socket_option_level, + asio::detail::enable_connection_aborted_option> + enable_connection_aborted; +#endif + + /// IO control command to get the amount of data that can be read without + /// blocking. + /** + * Implements the FIONREAD IO control command. + * + * @par Example + * @code + * asio::ip::tcp::socket socket(my_context); + * ... + * asio::socket_base::bytes_readable command(true); + * socket.io_control(command); + * std::size_t bytes_readable = command.get(); + * @endcode + * + * @par Concepts: + * IO_Control_Command, Size_IO_Control_Command. + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined bytes_readable; +#else + typedef asio::detail::io_control::bytes_readable bytes_readable; +#endif + + /// The maximum length of the queue of pending incoming connections. +#if defined(GENERATING_DOCUMENTATION) + static const int max_listen_connections = implementation_defined; +#else + ASIO_STATIC_CONSTANT(int, max_listen_connections + = ASIO_OS_DEF(SOMAXCONN)); +#endif + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use max_listen_connections.) The maximum length of the queue + /// of pending incoming connections. +#if defined(GENERATING_DOCUMENTATION) + static const int max_connections = implementation_defined; +#else + ASIO_STATIC_CONSTANT(int, max_connections + = ASIO_OS_DEF(SOMAXCONN)); +#endif +#endif // !defined(ASIO_NO_DEPRECATED) + +protected: + /// Protected destructor to prevent deletion through this type. + ~socket_base() + { + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SOCKET_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/spawn.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/spawn.hpp new file mode 100644 index 00000000..4f8b8905 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/spawn.hpp @@ -0,0 +1,336 @@ +// +// spawn.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SPAWN_HPP +#define ASIO_SPAWN_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/bind_executor.hpp" +#include "asio/detail/memory.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/detail/wrapped_handler.hpp" +#include "asio/executor.hpp" +#include "asio/io_context.hpp" +#include "asio/is_executor.hpp" +#include "asio/strand.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Context object the represents the currently executing coroutine. +/** + * The basic_yield_context class is used to represent the currently executing + * stackful coroutine. A basic_yield_context may be passed as a handler to an + * asynchronous operation. For example: + * + * @code template + * void my_coroutine(basic_yield_context yield) + * { + * ... + * std::size_t n = my_socket.async_read_some(buffer, yield); + * ... + * } @endcode + * + * The initiating function (async_read_some in the above example) suspends the + * current coroutine. The coroutine is resumed when the asynchronous operation + * completes, and the result of the operation is returned. + */ +template +class basic_yield_context +{ +public: + /// The coroutine callee type, used by the implementation. + /** + * When using Boost.Coroutine v1, this type is: + * @code typename coroutine @endcode + * When using Boost.Coroutine v2 (unidirectional coroutines), this type is: + * @code push_coroutine @endcode + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined callee_type; +#elif defined(BOOST_COROUTINES_UNIDIRECT) || defined(BOOST_COROUTINES_V2) + typedef boost::coroutines::push_coroutine callee_type; +#else + typedef boost::coroutines::coroutine callee_type; +#endif + + /// The coroutine caller type, used by the implementation. + /** + * When using Boost.Coroutine v1, this type is: + * @code typename coroutine::caller_type @endcode + * When using Boost.Coroutine v2 (unidirectional coroutines), this type is: + * @code pull_coroutine @endcode + */ +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined caller_type; +#elif defined(BOOST_COROUTINES_UNIDIRECT) || defined(BOOST_COROUTINES_V2) + typedef boost::coroutines::pull_coroutine caller_type; +#else + typedef boost::coroutines::coroutine::caller_type caller_type; +#endif + + /// Construct a yield context to represent the specified coroutine. + /** + * Most applications do not need to use this constructor. Instead, the + * spawn() function passes a yield context as an argument to the coroutine + * function. + */ + basic_yield_context( + const detail::weak_ptr& coro, + caller_type& ca, Handler& handler) + : coro_(coro), + ca_(ca), + handler_(handler), + ec_(0) + { + } + + /// Construct a yield context from another yield context type. + /** + * Requires that OtherHandler be convertible to Handler. + */ + template + basic_yield_context(const basic_yield_context& other) + : coro_(other.coro_), + ca_(other.ca_), + handler_(other.handler_), + ec_(other.ec_) + { + } + + /// Return a yield context that sets the specified error_code. + /** + * By default, when a yield context is used with an asynchronous operation, a + * non-success error_code is converted to system_error and thrown. This + * operator may be used to specify an error_code object that should instead be + * set with the asynchronous operation's result. For example: + * + * @code template + * void my_coroutine(basic_yield_context yield) + * { + * ... + * std::size_t n = my_socket.async_read_some(buffer, yield[ec]); + * if (ec) + * { + * // An error occurred. + * } + * ... + * } @endcode + */ + basic_yield_context operator[](asio::error_code& ec) const + { + basic_yield_context tmp(*this); + tmp.ec_ = &ec; + return tmp; + } + +#if defined(GENERATING_DOCUMENTATION) +private: +#endif // defined(GENERATING_DOCUMENTATION) + detail::weak_ptr coro_; + caller_type& ca_; + Handler handler_; + asio::error_code* ec_; +}; + +#if defined(GENERATING_DOCUMENTATION) +/// Context object that represents the currently executing coroutine. +typedef basic_yield_context yield_context; +#else // defined(GENERATING_DOCUMENTATION) +typedef basic_yield_context< + executor_binder > yield_context; +#endif // defined(GENERATING_DOCUMENTATION) + +/** + * @defgroup spawn asio::spawn + * + * @brief Start a new stackful coroutine. + * + * The spawn() function is a high-level wrapper over the Boost.Coroutine + * library. This function enables programs to implement asynchronous logic in a + * synchronous manner, as illustrated by the following example: + * + * @code asio::spawn(my_strand, do_echo); + * + * // ... + * + * void do_echo(asio::yield_context yield) + * { + * try + * { + * char data[128]; + * for (;;) + * { + * std::size_t length = + * my_socket.async_read_some( + * asio::buffer(data), yield); + * + * asio::async_write(my_socket, + * asio::buffer(data, length), yield); + * } + * } + * catch (std::exception& e) + * { + * // ... + * } + * } @endcode + */ +/*@{*/ + +/// Start a new stackful coroutine, calling the specified handler when it +/// completes. +/** + * This function is used to launch a new coroutine. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(basic_yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes()); + +/// Start a new stackful coroutine, calling the specified handler when it +/// completes. +/** + * This function is used to launch a new coroutine. + * + * @param handler A handler to be called when the coroutine exits. More + * importantly, the handler provides an execution context (via the the handler + * invocation hook) for the coroutine. The handler must have the signature: + * @code void handler(); @endcode + * + * @param function The coroutine function. The function must have the signature: + * @code void function(basic_yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(ASIO_MOVE_ARG(Handler) handler, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes(), + typename enable_if::type>::value && + !is_convertible::value>::type* = 0); + +/// Start a new stackful coroutine, inheriting the execution context of another. +/** + * This function is used to launch a new coroutine. + * + * @param ctx Identifies the current coroutine as a parent of the new + * coroutine. This specifies that the new coroutine should inherit the + * execution context of the parent. For example, if the parent coroutine is + * executing in a particular strand, then the new coroutine will execute in the + * same strand. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(basic_yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(basic_yield_context ctx, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes()); + +/// Start a new stackful coroutine that executes on a given executor. +/** + * This function is used to launch a new coroutine. + * + * @param ex Identifies the executor that will run the coroutine. The new + * coroutine is implicitly given its own strand within this executor. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(const Executor& ex, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes(), + typename enable_if::value>::type* = 0); + +/// Start a new stackful coroutine that executes on a given strand. +/** + * This function is used to launch a new coroutine. + * + * @param ex Identifies the strand that will run the coroutine. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(const strand& ex, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes()); + +/// Start a new stackful coroutine that executes in the context of a strand. +/** + * This function is used to launch a new coroutine. + * + * @param s Identifies a strand. By starting multiple coroutines on the same + * strand, the implementation ensures that none of those coroutines can execute + * simultaneously. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(const asio::io_context::strand& s, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes()); + +/// Start a new stackful coroutine that executes on a given execution context. +/** + * This function is used to launch a new coroutine. + * + * @param ctx Identifies the execution context that will run the coroutine. The + * new coroutine is implicitly given its own strand within this execution + * context. + * + * @param function The coroutine function. The function must have the signature: + * @code void function(yield_context yield); @endcode + * + * @param attributes Boost.Coroutine attributes used to customise the coroutine. + */ +template +void spawn(ExecutionContext& ctx, + ASIO_MOVE_ARG(Function) function, + const boost::coroutines::attributes& attributes + = boost::coroutines::attributes(), + typename enable_if::value>::type* = 0); + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/spawn.hpp" + +#endif // ASIO_SPAWN_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl.hpp new file mode 100644 index 00000000..19b1da47 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl.hpp @@ -0,0 +1,27 @@ +// +// ssl.hpp +// ~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_HPP +#define ASIO_SSL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/ssl/context.hpp" +#include "asio/ssl/context_base.hpp" +#include "asio/ssl/error.hpp" +#include "asio/ssl/rfc2818_verification.hpp" +#include "asio/ssl/stream.hpp" +#include "asio/ssl/stream_base.hpp" +#include "asio/ssl/verify_context.hpp" +#include "asio/ssl/verify_mode.hpp" + +#endif // ASIO_SSL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context.hpp new file mode 100644 index 00000000..9657d774 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context.hpp @@ -0,0 +1,758 @@ +// +// ssl/context.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_CONTEXT_HPP +#define ASIO_SSL_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/buffer.hpp" +#include "asio/io_context.hpp" +#include "asio/ssl/context_base.hpp" +#include "asio/ssl/detail/openssl_types.hpp" +#include "asio/ssl/detail/openssl_init.hpp" +#include "asio/ssl/detail/password_callback.hpp" +#include "asio/ssl/detail/verify_callback.hpp" +#include "asio/ssl/verify_mode.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +class context + : public context_base, + private noncopyable +{ +public: + /// The native handle type of the SSL context. + typedef SSL_CTX* native_handle_type; + + /// Constructor. + ASIO_DECL explicit context(method m); + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a context from another. + /** + * This constructor moves an SSL context from one object to another. + * + * @param other The other context object from which the move will occur. + * + * @note Following the move, the following operations only are valid for the + * moved-from object: + * @li Destruction. + * @li As a target for move-assignment. + */ + ASIO_DECL context(context&& other); + + /// Move-assign a context from another. + /** + * This assignment operator moves an SSL context from one object to another. + * + * @param other The other context object from which the move will occur. + * + * @note Following the move, the following operations only are valid for the + * moved-from object: + * @li Destruction. + * @li As a target for move-assignment. + */ + ASIO_DECL context& operator=(context&& other); +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor. + ASIO_DECL ~context(); + + /// Get the underlying implementation in the native type. + /** + * This function may be used to obtain the underlying implementation of the + * context. This is intended to allow access to context functionality that is + * not otherwise provided. + */ + ASIO_DECL native_handle_type native_handle(); + + /// Clear options on the context. + /** + * This function may be used to configure the SSL options used by the context. + * + * @param o A bitmask of options. The available option values are defined in + * the context_base class. The specified options, if currently enabled on the + * context, are cleared. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_clear_options. + */ + ASIO_DECL void clear_options(options o); + + /// Clear options on the context. + /** + * This function may be used to configure the SSL options used by the context. + * + * @param o A bitmask of options. The available option values are defined in + * the context_base class. The specified options, if currently enabled on the + * context, are cleared. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_clear_options. + */ + ASIO_DECL ASIO_SYNC_OP_VOID clear_options(options o, + asio::error_code& ec); + + /// Set options on the context. + /** + * This function may be used to configure the SSL options used by the context. + * + * @param o A bitmask of options. The available option values are defined in + * the context_base class. The options are bitwise-ored with any existing + * value for the options. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_options. + */ + ASIO_DECL void set_options(options o); + + /// Set options on the context. + /** + * This function may be used to configure the SSL options used by the context. + * + * @param o A bitmask of options. The available option values are defined in + * the context_base class. The options are bitwise-ored with any existing + * value for the options. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_options. + */ + ASIO_DECL ASIO_SYNC_OP_VOID set_options(options o, + asio::error_code& ec); + + /// Set the peer verification mode. + /** + * This function may be used to configure the peer verification mode used by + * the context. + * + * @param v A bitmask of peer verification modes. See @ref verify_mode for + * available values. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_verify. + */ + ASIO_DECL void set_verify_mode(verify_mode v); + + /// Set the peer verification mode. + /** + * This function may be used to configure the peer verification mode used by + * the context. + * + * @param v A bitmask of peer verification modes. See @ref verify_mode for + * available values. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_verify. + */ + ASIO_DECL ASIO_SYNC_OP_VOID set_verify_mode( + verify_mode v, asio::error_code& ec); + + /// Set the peer verification depth. + /** + * This function may be used to configure the maximum verification depth + * allowed by the context. + * + * @param depth Maximum depth for the certificate chain verification that + * shall be allowed. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_verify_depth. + */ + ASIO_DECL void set_verify_depth(int depth); + + /// Set the peer verification depth. + /** + * This function may be used to configure the maximum verification depth + * allowed by the context. + * + * @param depth Maximum depth for the certificate chain verification that + * shall be allowed. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_verify_depth. + */ + ASIO_DECL ASIO_SYNC_OP_VOID set_verify_depth( + int depth, asio::error_code& ec); + + /// Set the callback used to verify peer certificates. + /** + * This function is used to specify a callback function that will be called + * by the implementation when it needs to verify a peer certificate. + * + * @param callback The function object to be used for verifying a certificate. + * The function signature of the handler must be: + * @code bool verify_callback( + * bool preverified, // True if the certificate passed pre-verification. + * verify_context& ctx // The peer certificate and other context. + * ); @endcode + * The return value of the callback is true if the certificate has passed + * verification, false otherwise. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_verify. + */ + template + void set_verify_callback(VerifyCallback callback); + + /// Set the callback used to verify peer certificates. + /** + * This function is used to specify a callback function that will be called + * by the implementation when it needs to verify a peer certificate. + * + * @param callback The function object to be used for verifying a certificate. + * The function signature of the handler must be: + * @code bool verify_callback( + * bool preverified, // True if the certificate passed pre-verification. + * verify_context& ctx // The peer certificate and other context. + * ); @endcode + * The return value of the callback is true if the certificate has passed + * verification, false otherwise. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_verify. + */ + template + ASIO_SYNC_OP_VOID set_verify_callback(VerifyCallback callback, + asio::error_code& ec); + + /// Load a certification authority file for performing verification. + /** + * This function is used to load one or more trusted certification authorities + * from a file. + * + * @param filename The name of a file containing certification authority + * certificates in PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_load_verify_locations. + */ + ASIO_DECL void load_verify_file(const std::string& filename); + + /// Load a certification authority file for performing verification. + /** + * This function is used to load the certificates for one or more trusted + * certification authorities from a file. + * + * @param filename The name of a file containing certification authority + * certificates in PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_load_verify_locations. + */ + ASIO_DECL ASIO_SYNC_OP_VOID load_verify_file( + const std::string& filename, asio::error_code& ec); + + /// Add certification authority for performing verification. + /** + * This function is used to add one trusted certification authority + * from a memory buffer. + * + * @param ca The buffer containing the certification authority certificate. + * The certificate must use the PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_get_cert_store and @c X509_STORE_add_cert. + */ + ASIO_DECL void add_certificate_authority(const const_buffer& ca); + + /// Add certification authority for performing verification. + /** + * This function is used to add one trusted certification authority + * from a memory buffer. + * + * @param ca The buffer containing the certification authority certificate. + * The certificate must use the PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_get_cert_store and @c X509_STORE_add_cert. + */ + ASIO_DECL ASIO_SYNC_OP_VOID add_certificate_authority( + const const_buffer& ca, asio::error_code& ec); + + /// Configures the context to use the default directories for finding + /// certification authority certificates. + /** + * This function specifies that the context should use the default, + * system-dependent directories for locating certification authority + * certificates. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_default_verify_paths. + */ + ASIO_DECL void set_default_verify_paths(); + + /// Configures the context to use the default directories for finding + /// certification authority certificates. + /** + * This function specifies that the context should use the default, + * system-dependent directories for locating certification authority + * certificates. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_default_verify_paths. + */ + ASIO_DECL ASIO_SYNC_OP_VOID set_default_verify_paths( + asio::error_code& ec); + + /// Add a directory containing certificate authority files to be used for + /// performing verification. + /** + * This function is used to specify the name of a directory containing + * certification authority certificates. Each file in the directory must + * contain a single certificate. The files must be named using the subject + * name's hash and an extension of ".0". + * + * @param path The name of a directory containing the certificates. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_load_verify_locations. + */ + ASIO_DECL void add_verify_path(const std::string& path); + + /// Add a directory containing certificate authority files to be used for + /// performing verification. + /** + * This function is used to specify the name of a directory containing + * certification authority certificates. Each file in the directory must + * contain a single certificate. The files must be named using the subject + * name's hash and an extension of ".0". + * + * @param path The name of a directory containing the certificates. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_load_verify_locations. + */ + ASIO_DECL ASIO_SYNC_OP_VOID add_verify_path( + const std::string& path, asio::error_code& ec); + + /// Use a certificate from a memory buffer. + /** + * This function is used to load a certificate into the context from a buffer. + * + * @param certificate The buffer containing the certificate. + * + * @param format The certificate format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1. + */ + ASIO_DECL void use_certificate( + const const_buffer& certificate, file_format format); + + /// Use a certificate from a memory buffer. + /** + * This function is used to load a certificate into the context from a buffer. + * + * @param certificate The buffer containing the certificate. + * + * @param format The certificate format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_certificate( + const const_buffer& certificate, file_format format, + asio::error_code& ec); + + /// Use a certificate from a file. + /** + * This function is used to load a certificate into the context from a file. + * + * @param filename The name of the file containing the certificate. + * + * @param format The file format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_certificate_file. + */ + ASIO_DECL void use_certificate_file( + const std::string& filename, file_format format); + + /// Use a certificate from a file. + /** + * This function is used to load a certificate into the context from a file. + * + * @param filename The name of the file containing the certificate. + * + * @param format The file format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_certificate_file. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_file( + const std::string& filename, file_format format, + asio::error_code& ec); + + /// Use a certificate chain from a memory buffer. + /** + * This function is used to load a certificate chain into the context from a + * buffer. + * + * @param chain The buffer containing the certificate chain. The certificate + * chain must use the PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert. + */ + ASIO_DECL void use_certificate_chain(const const_buffer& chain); + + /// Use a certificate chain from a memory buffer. + /** + * This function is used to load a certificate chain into the context from a + * buffer. + * + * @param chain The buffer containing the certificate chain. The certificate + * chain must use the PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_chain( + const const_buffer& chain, asio::error_code& ec); + + /// Use a certificate chain from a file. + /** + * This function is used to load a certificate chain into the context from a + * file. + * + * @param filename The name of the file containing the certificate. The file + * must use the PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_certificate_chain_file. + */ + ASIO_DECL void use_certificate_chain_file(const std::string& filename); + + /// Use a certificate chain from a file. + /** + * This function is used to load a certificate chain into the context from a + * file. + * + * @param filename The name of the file containing the certificate. The file + * must use the PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_certificate_chain_file. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_chain_file( + const std::string& filename, asio::error_code& ec); + + /// Use a private key from a memory buffer. + /** + * This function is used to load a private key into the context from a buffer. + * + * @param private_key The buffer containing the private key. + * + * @param format The private key format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1. + */ + ASIO_DECL void use_private_key( + const const_buffer& private_key, file_format format); + + /// Use a private key from a memory buffer. + /** + * This function is used to load a private key into the context from a buffer. + * + * @param private_key The buffer containing the private key. + * + * @param format The private key format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_private_key( + const const_buffer& private_key, file_format format, + asio::error_code& ec); + + /// Use a private key from a file. + /** + * This function is used to load a private key into the context from a file. + * + * @param filename The name of the file containing the private key. + * + * @param format The file format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_PrivateKey_file. + */ + ASIO_DECL void use_private_key_file( + const std::string& filename, file_format format); + + /// Use a private key from a file. + /** + * This function is used to load a private key into the context from a file. + * + * @param filename The name of the file containing the private key. + * + * @param format The file format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_PrivateKey_file. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_private_key_file( + const std::string& filename, file_format format, + asio::error_code& ec); + + /// Use an RSA private key from a memory buffer. + /** + * This function is used to load an RSA private key into the context from a + * buffer. + * + * @param private_key The buffer containing the RSA private key. + * + * @param format The private key format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1. + */ + ASIO_DECL void use_rsa_private_key( + const const_buffer& private_key, file_format format); + + /// Use an RSA private key from a memory buffer. + /** + * This function is used to load an RSA private key into the context from a + * buffer. + * + * @param private_key The buffer containing the RSA private key. + * + * @param format The private key format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_rsa_private_key( + const const_buffer& private_key, file_format format, + asio::error_code& ec); + + /// Use an RSA private key from a file. + /** + * This function is used to load an RSA private key into the context from a + * file. + * + * @param filename The name of the file containing the RSA private key. + * + * @param format The file format (ASN.1 or PEM). + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_use_RSAPrivateKey_file. + */ + ASIO_DECL void use_rsa_private_key_file( + const std::string& filename, file_format format); + + /// Use an RSA private key from a file. + /** + * This function is used to load an RSA private key into the context from a + * file. + * + * @param filename The name of the file containing the RSA private key. + * + * @param format The file format (ASN.1 or PEM). + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_use_RSAPrivateKey_file. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_rsa_private_key_file( + const std::string& filename, file_format format, + asio::error_code& ec); + + /// Use the specified memory buffer to obtain the temporary Diffie-Hellman + /// parameters. + /** + * This function is used to load Diffie-Hellman parameters into the context + * from a buffer. + * + * @param dh The memory buffer containing the Diffie-Hellman parameters. The + * buffer must use the PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_tmp_dh. + */ + ASIO_DECL void use_tmp_dh(const const_buffer& dh); + + /// Use the specified memory buffer to obtain the temporary Diffie-Hellman + /// parameters. + /** + * This function is used to load Diffie-Hellman parameters into the context + * from a buffer. + * + * @param dh The memory buffer containing the Diffie-Hellman parameters. The + * buffer must use the PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_tmp_dh. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_tmp_dh( + const const_buffer& dh, asio::error_code& ec); + + /// Use the specified file to obtain the temporary Diffie-Hellman parameters. + /** + * This function is used to load Diffie-Hellman parameters into the context + * from a file. + * + * @param filename The name of the file containing the Diffie-Hellman + * parameters. The file must use the PEM format. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_tmp_dh. + */ + ASIO_DECL void use_tmp_dh_file(const std::string& filename); + + /// Use the specified file to obtain the temporary Diffie-Hellman parameters. + /** + * This function is used to load Diffie-Hellman parameters into the context + * from a file. + * + * @param filename The name of the file containing the Diffie-Hellman + * parameters. The file must use the PEM format. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_tmp_dh. + */ + ASIO_DECL ASIO_SYNC_OP_VOID use_tmp_dh_file( + const std::string& filename, asio::error_code& ec); + + /// Set the password callback. + /** + * This function is used to specify a callback function to obtain password + * information about an encrypted key in PEM format. + * + * @param callback The function object to be used for obtaining the password. + * The function signature of the handler must be: + * @code std::string password_callback( + * std::size_t max_length, // The maximum size for a password. + * password_purpose purpose // Whether password is for reading or writing. + * ); @endcode + * The return value of the callback is a string containing the password. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_CTX_set_default_passwd_cb. + */ + template + void set_password_callback(PasswordCallback callback); + + /// Set the password callback. + /** + * This function is used to specify a callback function to obtain password + * information about an encrypted key in PEM format. + * + * @param callback The function object to be used for obtaining the password. + * The function signature of the handler must be: + * @code std::string password_callback( + * std::size_t max_length, // The maximum size for a password. + * password_purpose purpose // Whether password is for reading or writing. + * ); @endcode + * The return value of the callback is a string containing the password. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_CTX_set_default_passwd_cb. + */ + template + ASIO_SYNC_OP_VOID set_password_callback(PasswordCallback callback, + asio::error_code& ec); + +private: + struct bio_cleanup; + struct x509_cleanup; + struct evp_pkey_cleanup; + struct rsa_cleanup; + struct dh_cleanup; + + // Helper function used to set a peer certificate verification callback. + ASIO_DECL ASIO_SYNC_OP_VOID do_set_verify_callback( + detail::verify_callback_base* callback, asio::error_code& ec); + + // Callback used when the SSL implementation wants to verify a certificate. + ASIO_DECL static int verify_callback_function( + int preverified, X509_STORE_CTX* ctx); + + // Helper function used to set a password callback. + ASIO_DECL ASIO_SYNC_OP_VOID do_set_password_callback( + detail::password_callback_base* callback, asio::error_code& ec); + + // Callback used when the SSL implementation wants a password. + ASIO_DECL static int password_callback_function( + char* buf, int size, int purpose, void* data); + + // Helper function to set the temporary Diffie-Hellman parameters from a BIO. + ASIO_DECL ASIO_SYNC_OP_VOID do_use_tmp_dh( + BIO* bio, asio::error_code& ec); + + // Helper function to make a BIO from a memory buffer. + ASIO_DECL BIO* make_buffer_bio(const const_buffer& b); + + // The underlying native implementation. + native_handle_type handle_; + + // Ensure openssl is initialised. + asio::ssl::detail::openssl_init<> init_; +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/ssl/impl/context.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/ssl/impl/context.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SSL_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context_base.hpp new file mode 100644 index 00000000..fd103e7b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/context_base.hpp @@ -0,0 +1,209 @@ +// +// ssl/context_base.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_CONTEXT_BASE_HPP +#define ASIO_SSL_CONTEXT_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ssl/detail/openssl_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// The context_base class is used as a base for the basic_context class +/// template so that we have a common place to define various enums. +class context_base +{ +public: + /// Different methods supported by a context. + enum method + { + /// Generic SSL version 2. + sslv2, + + /// SSL version 2 client. + sslv2_client, + + /// SSL version 2 server. + sslv2_server, + + /// Generic SSL version 3. + sslv3, + + /// SSL version 3 client. + sslv3_client, + + /// SSL version 3 server. + sslv3_server, + + /// Generic TLS version 1. + tlsv1, + + /// TLS version 1 client. + tlsv1_client, + + /// TLS version 1 server. + tlsv1_server, + + /// Generic SSL/TLS. + sslv23, + + /// SSL/TLS client. + sslv23_client, + + /// SSL/TLS server. + sslv23_server, + + /// Generic TLS version 1.1. + tlsv11, + + /// TLS version 1.1 client. + tlsv11_client, + + /// TLS version 1.1 server. + tlsv11_server, + + /// Generic TLS version 1.2. + tlsv12, + + /// TLS version 1.2 client. + tlsv12_client, + + /// TLS version 1.2 server. + tlsv12_server, + + /// Generic TLS version 1.3. + tlsv13, + + /// TLS version 1.3 client. + tlsv13_client, + + /// TLS version 1.3 server. + tlsv13_server, + + /// Generic TLS. + tls, + + /// TLS client. + tls_client, + + /// TLS server. + tls_server + }; + + /// Bitmask type for SSL options. + typedef long options; + +#if defined(GENERATING_DOCUMENTATION) + /// Implement various bug workarounds. + static const long default_workarounds = implementation_defined; + + /// Always create a new key when using tmp_dh parameters. + static const long single_dh_use = implementation_defined; + + /// Disable SSL v2. + static const long no_sslv2 = implementation_defined; + + /// Disable SSL v3. + static const long no_sslv3 = implementation_defined; + + /// Disable TLS v1. + static const long no_tlsv1 = implementation_defined; + + /// Disable TLS v1.1. + static const long no_tlsv1_1 = implementation_defined; + + /// Disable TLS v1.2. + static const long no_tlsv1_2 = implementation_defined; + + /// Disable TLS v1.3. + static const long no_tlsv1_3 = implementation_defined; + + /// Disable compression. Compression is disabled by default. + static const long no_compression = implementation_defined; +#else + ASIO_STATIC_CONSTANT(long, default_workarounds = SSL_OP_ALL); + ASIO_STATIC_CONSTANT(long, single_dh_use = SSL_OP_SINGLE_DH_USE); + ASIO_STATIC_CONSTANT(long, no_sslv2 = SSL_OP_NO_SSLv2); + ASIO_STATIC_CONSTANT(long, no_sslv3 = SSL_OP_NO_SSLv3); + ASIO_STATIC_CONSTANT(long, no_tlsv1 = SSL_OP_NO_TLSv1); +# if defined(SSL_OP_NO_TLSv1_1) + ASIO_STATIC_CONSTANT(long, no_tlsv1_1 = SSL_OP_NO_TLSv1_1); +# else // defined(SSL_OP_NO_TLSv1_1) + ASIO_STATIC_CONSTANT(long, no_tlsv1_1 = 0x10000000L); +# endif // defined(SSL_OP_NO_TLSv1_1) +# if defined(SSL_OP_NO_TLSv1_2) + ASIO_STATIC_CONSTANT(long, no_tlsv1_2 = SSL_OP_NO_TLSv1_2); +# else // defined(SSL_OP_NO_TLSv1_2) + ASIO_STATIC_CONSTANT(long, no_tlsv1_2 = 0x08000000L); +# endif // defined(SSL_OP_NO_TLSv1_2) +# if defined(SSL_OP_NO_TLSv1_3) + ASIO_STATIC_CONSTANT(long, no_tlsv1_3 = SSL_OP_NO_TLSv1_3); +# else // defined(SSL_OP_NO_TLSv1_3) + ASIO_STATIC_CONSTANT(long, no_tlsv1_3 = 0x20000000L); +# endif // defined(SSL_OP_NO_TLSv1_3) +# if defined(SSL_OP_NO_COMPRESSION) + ASIO_STATIC_CONSTANT(long, no_compression = SSL_OP_NO_COMPRESSION); +# else // defined(SSL_OP_NO_COMPRESSION) + ASIO_STATIC_CONSTANT(long, no_compression = 0x20000L); +# endif // defined(SSL_OP_NO_COMPRESSION) +#endif + + /// File format types. + enum file_format + { + /// ASN.1 file. + asn1, + + /// PEM file. + pem + }; + +#if !defined(GENERATING_DOCUMENTATION) + // The following types and constants are preserved for backward compatibility. + // New programs should use the equivalents of the same names that are defined + // in the asio::ssl namespace. + typedef int verify_mode; + ASIO_STATIC_CONSTANT(int, verify_none = SSL_VERIFY_NONE); + ASIO_STATIC_CONSTANT(int, verify_peer = SSL_VERIFY_PEER); + ASIO_STATIC_CONSTANT(int, + verify_fail_if_no_peer_cert = SSL_VERIFY_FAIL_IF_NO_PEER_CERT); + ASIO_STATIC_CONSTANT(int, verify_client_once = SSL_VERIFY_CLIENT_ONCE); +#endif + + /// Purpose of PEM password. + enum password_purpose + { + /// The password is needed for reading/decryption. + for_reading, + + /// The password is needed for writing/encryption. + for_writing + }; + +protected: + /// Protected destructor to prevent deletion through this type. + ~context_base() + { + } +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_CONTEXT_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/buffered_handshake_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/buffered_handshake_op.hpp new file mode 100644 index 00000000..97deb1de --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/buffered_handshake_op.hpp @@ -0,0 +1,114 @@ +// +// ssl/detail/buffered_handshake_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP +#define ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/ssl/detail/engine.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +template +class buffered_handshake_op +{ +public: + buffered_handshake_op(stream_base::handshake_type type, + const ConstBufferSequence& buffers) + : type_(type), + buffers_(buffers), + total_buffer_size_(asio::buffer_size(buffers_)) + { + } + + engine::want operator()(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred) const + { + return this->process(eng, ec, bytes_transferred, + asio::buffer_sequence_begin(buffers_), + asio::buffer_sequence_end(buffers_)); + } + + template + void call_handler(Handler& handler, + const asio::error_code& ec, + const std::size_t& bytes_transferred) const + { + handler(ec, bytes_transferred); + } + +private: + template + engine::want process(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred, + Iterator begin, Iterator end) const + { + Iterator iter = begin; + std::size_t accumulated_size = 0; + + for (;;) + { + engine::want want = eng.handshake(type_, ec); + if (want != engine::want_input_and_retry + || bytes_transferred == total_buffer_size_) + return want; + + // Find the next buffer piece to be fed to the engine. + while (iter != end) + { + const_buffer buffer(*iter); + + // Skip over any buffers which have already been consumed by the engine. + if (bytes_transferred >= accumulated_size + buffer.size()) + { + accumulated_size += buffer.size(); + ++iter; + continue; + } + + // The current buffer may have been partially consumed by the engine on + // a previous iteration. If so, adjust the buffer to point to the + // unused portion. + if (bytes_transferred > accumulated_size) + buffer = buffer + (bytes_transferred - accumulated_size); + + // Pass the buffer to the engine, and update the bytes transferred to + // reflect the total number of bytes consumed so far. + bytes_transferred += buffer.size(); + buffer = eng.put_input(buffer); + bytes_transferred -= buffer.size(); + break; + } + } + } + + stream_base::handshake_type type_; + ConstBufferSequence buffers_; + std::size_t total_buffer_size_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/engine.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/engine.hpp new file mode 100644 index 00000000..8a798c13 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/engine.hpp @@ -0,0 +1,160 @@ +// +// ssl/detail/engine.hpp +// ~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_ENGINE_HPP +#define ASIO_SSL_DETAIL_ENGINE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/buffer.hpp" +#include "asio/detail/static_mutex.hpp" +#include "asio/ssl/detail/openssl_types.hpp" +#include "asio/ssl/detail/verify_callback.hpp" +#include "asio/ssl/stream_base.hpp" +#include "asio/ssl/verify_mode.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class engine +{ +public: + enum want + { + // Returned by functions to indicate that the engine wants input. The input + // buffer should be updated to point to the data. The engine then needs to + // be called again to retry the operation. + want_input_and_retry = -2, + + // Returned by functions to indicate that the engine wants to write output. + // The output buffer points to the data to be written. The engine then + // needs to be called again to retry the operation. + want_output_and_retry = -1, + + // Returned by functions to indicate that the engine doesn't need input or + // output. + want_nothing = 0, + + // Returned by functions to indicate that the engine wants to write output. + // The output buffer points to the data to be written. After that the + // operation is complete, and the engine does not need to be called again. + want_output = 1 + }; + + // Construct a new engine for the specified context. + ASIO_DECL explicit engine(SSL_CTX* context); + + // Destructor. + ASIO_DECL ~engine(); + + // Get the underlying implementation in the native type. + ASIO_DECL SSL* native_handle(); + + // Set the peer verification mode. + ASIO_DECL asio::error_code set_verify_mode( + verify_mode v, asio::error_code& ec); + + // Set the peer verification depth. + ASIO_DECL asio::error_code set_verify_depth( + int depth, asio::error_code& ec); + + // Set a peer certificate verification callback. + ASIO_DECL asio::error_code set_verify_callback( + verify_callback_base* callback, asio::error_code& ec); + + // Perform an SSL handshake using either SSL_connect (client-side) or + // SSL_accept (server-side). + ASIO_DECL want handshake( + stream_base::handshake_type type, asio::error_code& ec); + + // Perform a graceful shutdown of the SSL session. + ASIO_DECL want shutdown(asio::error_code& ec); + + // Write bytes to the SSL session. + ASIO_DECL want write(const asio::const_buffer& data, + asio::error_code& ec, std::size_t& bytes_transferred); + + // Read bytes from the SSL session. + ASIO_DECL want read(const asio::mutable_buffer& data, + asio::error_code& ec, std::size_t& bytes_transferred); + + // Get output data to be written to the transport. + ASIO_DECL asio::mutable_buffer get_output( + const asio::mutable_buffer& data); + + // Put input data that was read from the transport. + ASIO_DECL asio::const_buffer put_input( + const asio::const_buffer& data); + + // Map an error::eof code returned by the underlying transport according to + // the type and state of the SSL session. Returns a const reference to the + // error code object, suitable for passing to a completion handler. + ASIO_DECL const asio::error_code& map_error_code( + asio::error_code& ec) const; + +private: + // Disallow copying and assignment. + engine(const engine&); + engine& operator=(const engine&); + + // Callback used when the SSL implementation wants to verify a certificate. + ASIO_DECL static int verify_callback_function( + int preverified, X509_STORE_CTX* ctx); + +#if (OPENSSL_VERSION_NUMBER < 0x10000000L) + // The SSL_accept function may not be thread safe. This mutex is used to + // protect all calls to the SSL_accept function. + ASIO_DECL static asio::detail::static_mutex& accept_mutex(); +#endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) + + // Perform one operation. Returns >= 0 on success or error, want_read if the + // operation needs more input, or want_write if it needs to write some output + // before the operation can complete. + ASIO_DECL want perform(int (engine::* op)(void*, std::size_t), + void* data, std::size_t length, asio::error_code& ec, + std::size_t* bytes_transferred); + + // Adapt the SSL_accept function to the signature needed for perform(). + ASIO_DECL int do_accept(void*, std::size_t); + + // Adapt the SSL_connect function to the signature needed for perform(). + ASIO_DECL int do_connect(void*, std::size_t); + + // Adapt the SSL_shutdown function to the signature needed for perform(). + ASIO_DECL int do_shutdown(void*, std::size_t); + + // Adapt the SSL_read function to the signature needed for perform(). + ASIO_DECL int do_read(void* data, std::size_t length); + + // Adapt the SSL_write function to the signature needed for perform(). + ASIO_DECL int do_write(void* data, std::size_t length); + + SSL* ssl_; + BIO* ext_bio_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ssl/detail/impl/engine.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SSL_DETAIL_ENGINE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/handshake_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/handshake_op.hpp new file mode 100644 index 00000000..d070c066 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/handshake_op.hpp @@ -0,0 +1,62 @@ +// +// ssl/detail/handshake_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP +#define ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/ssl/detail/engine.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class handshake_op +{ +public: + handshake_op(stream_base::handshake_type type) + : type_(type) + { + } + + engine::want operator()(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred) const + { + bytes_transferred = 0; + return eng.handshake(type_, ec); + } + + template + void call_handler(Handler& handler, + const asio::error_code& ec, + const std::size_t&) const + { + handler(ec); + } + +private: + stream_base::handshake_type type_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/io.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/io.hpp new file mode 100644 index 00000000..b3848cd9 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/io.hpp @@ -0,0 +1,381 @@ +// +// ssl/detail/io.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_IO_HPP +#define ASIO_SSL_DETAIL_IO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/ssl/detail/engine.hpp" +#include "asio/ssl/detail/stream_core.hpp" +#include "asio/write.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +template +std::size_t io(Stream& next_layer, stream_core& core, + const Operation& op, asio::error_code& ec) +{ + asio::error_code io_ec; + std::size_t bytes_transferred = 0; + do switch (op(core.engine_, ec, bytes_transferred)) + { + case engine::want_input_and_retry: + + // If the input buffer is empty then we need to read some more data from + // the underlying transport. + if (core.input_.size() == 0) + { + core.input_ = asio::buffer(core.input_buffer_, + next_layer.read_some(core.input_buffer_, io_ec)); + if (!ec) + ec = io_ec; + } + + // Pass the new input data to the engine. + core.input_ = core.engine_.put_input(core.input_); + + // Try the operation again. + continue; + + case engine::want_output_and_retry: + + // Get output data from the engine and write it to the underlying + // transport. + asio::write(next_layer, + core.engine_.get_output(core.output_buffer_), io_ec); + if (!ec) + ec = io_ec; + + // Try the operation again. + continue; + + case engine::want_output: + + // Get output data from the engine and write it to the underlying + // transport. + asio::write(next_layer, + core.engine_.get_output(core.output_buffer_), io_ec); + if (!ec) + ec = io_ec; + + // Operation is complete. Return result to caller. + core.engine_.map_error_code(ec); + return bytes_transferred; + + default: + + // Operation is complete. Return result to caller. + core.engine_.map_error_code(ec); + return bytes_transferred; + + } while (!ec); + + // Operation failed. Return result to caller. + core.engine_.map_error_code(ec); + return 0; +} + +template +class io_op +{ +public: + io_op(Stream& next_layer, stream_core& core, + const Operation& op, Handler& handler) + : next_layer_(next_layer), + core_(core), + op_(op), + start_(0), + want_(engine::want_nothing), + bytes_transferred_(0), + handler_(ASIO_MOVE_CAST(Handler)(handler)) + { + } + +#if defined(ASIO_HAS_MOVE) + io_op(const io_op& other) + : next_layer_(other.next_layer_), + core_(other.core_), + op_(other.op_), + start_(other.start_), + want_(other.want_), + ec_(other.ec_), + bytes_transferred_(other.bytes_transferred_), + handler_(other.handler_) + { + } + + io_op(io_op&& other) + : next_layer_(other.next_layer_), + core_(other.core_), + op_(ASIO_MOVE_CAST(Operation)(other.op_)), + start_(other.start_), + want_(other.want_), + ec_(other.ec_), + bytes_transferred_(other.bytes_transferred_), + handler_(ASIO_MOVE_CAST(Handler)(other.handler_)) + { + } +#endif // defined(ASIO_HAS_MOVE) + + void operator()(asio::error_code ec, + std::size_t bytes_transferred = ~std::size_t(0), int start = 0) + { + switch (start_ = start) + { + case 1: // Called after at least one async operation. + do + { + switch (want_ = op_(core_.engine_, ec_, bytes_transferred_)) + { + case engine::want_input_and_retry: + + // If the input buffer already has data in it we can pass it to the + // engine and then retry the operation immediately. + if (core_.input_.size() != 0) + { + core_.input_ = core_.engine_.put_input(core_.input_); + continue; + } + + // The engine wants more data to be read from input. However, we + // cannot allow more than one read operation at a time on the + // underlying transport. The pending_read_ timer's expiry is set to + // pos_infin if a read is in progress, and neg_infin otherwise. + if (core_.expiry(core_.pending_read_) == core_.neg_infin()) + { + // Prevent other read operations from being started. + core_.pending_read_.expires_at(core_.pos_infin()); + + // Start reading some data from the underlying transport. + next_layer_.async_read_some( + asio::buffer(core_.input_buffer_), + ASIO_MOVE_CAST(io_op)(*this)); + } + else + { + // Wait until the current read operation completes. + core_.pending_read_.async_wait(ASIO_MOVE_CAST(io_op)(*this)); + } + + // Yield control until asynchronous operation completes. Control + // resumes at the "default:" label below. + return; + + case engine::want_output_and_retry: + case engine::want_output: + + // The engine wants some data to be written to the output. However, we + // cannot allow more than one write operation at a time on the + // underlying transport. The pending_write_ timer's expiry is set to + // pos_infin if a write is in progress, and neg_infin otherwise. + if (core_.expiry(core_.pending_write_) == core_.neg_infin()) + { + // Prevent other write operations from being started. + core_.pending_write_.expires_at(core_.pos_infin()); + + // Start writing all the data to the underlying transport. + asio::async_write(next_layer_, + core_.engine_.get_output(core_.output_buffer_), + ASIO_MOVE_CAST(io_op)(*this)); + } + else + { + // Wait until the current write operation completes. + core_.pending_write_.async_wait(ASIO_MOVE_CAST(io_op)(*this)); + } + + // Yield control until asynchronous operation completes. Control + // resumes at the "default:" label below. + return; + + default: + + // The SSL operation is done and we can invoke the handler, but we + // have to keep in mind that this function might be being called from + // the async operation's initiating function. In this case we're not + // allowed to call the handler directly. Instead, issue a zero-sized + // read so the handler runs "as-if" posted using io_context::post(). + if (start) + { + next_layer_.async_read_some( + asio::buffer(core_.input_buffer_, 0), + ASIO_MOVE_CAST(io_op)(*this)); + + // Yield control until asynchronous operation completes. Control + // resumes at the "default:" label below. + return; + } + else + { + // Continue on to run handler directly. + break; + } + } + + default: + if (bytes_transferred == ~std::size_t(0)) + bytes_transferred = 0; // Timer cancellation, no data transferred. + else if (!ec_) + ec_ = ec; + + switch (want_) + { + case engine::want_input_and_retry: + + // Add received data to the engine's input. + core_.input_ = asio::buffer( + core_.input_buffer_, bytes_transferred); + core_.input_ = core_.engine_.put_input(core_.input_); + + // Release any waiting read operations. + core_.pending_read_.expires_at(core_.neg_infin()); + + // Try the operation again. + continue; + + case engine::want_output_and_retry: + + // Release any waiting write operations. + core_.pending_write_.expires_at(core_.neg_infin()); + + // Try the operation again. + continue; + + case engine::want_output: + + // Release any waiting write operations. + core_.pending_write_.expires_at(core_.neg_infin()); + + // Fall through to call handler. + + default: + + // Pass the result to the handler. + op_.call_handler(handler_, + core_.engine_.map_error_code(ec_), + ec_ ? 0 : bytes_transferred_); + + // Our work here is done. + return; + } + } while (!ec_); + + // Operation failed. Pass the result to the handler. + op_.call_handler(handler_, core_.engine_.map_error_code(ec_), 0); + } + } + +//private: + Stream& next_layer_; + stream_core& core_; + Operation op_; + int start_; + engine::want want_; + asio::error_code ec_; + std::size_t bytes_transferred_; + Handler handler_; +}; + +template +inline void* asio_handler_allocate(std::size_t size, + io_op* this_handler) +{ + return asio_handler_alloc_helpers::allocate( + size, this_handler->handler_); +} + +template +inline void asio_handler_deallocate(void* pointer, std::size_t size, + io_op* this_handler) +{ + asio_handler_alloc_helpers::deallocate( + pointer, size, this_handler->handler_); +} + +template +inline bool asio_handler_is_continuation( + io_op* this_handler) +{ + return this_handler->start_ == 0 ? true + : asio_handler_cont_helpers::is_continuation(this_handler->handler_); +} + +template +inline void asio_handler_invoke(Function& function, + io_op* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void asio_handler_invoke(const Function& function, + io_op* this_handler) +{ + asio_handler_invoke_helpers::invoke( + function, this_handler->handler_); +} + +template +inline void async_io(Stream& next_layer, stream_core& core, + const Operation& op, Handler& handler) +{ + io_op( + next_layer, core, op, handler)( + asio::error_code(), 0, 1); +} + +} // namespace detail +} // namespace ssl + +template +struct associated_allocator< + ssl::detail::io_op, Allocator> +{ + typedef typename associated_allocator::type type; + + static type get(const ssl::detail::io_op& h, + const Allocator& a = Allocator()) ASIO_NOEXCEPT + { + return associated_allocator::get(h.handler_, a); + } +}; + +template +struct associated_executor< + ssl::detail::io_op, Executor> +{ + typedef typename associated_executor::type type; + + static type get(const ssl::detail::io_op& h, + const Executor& ex = Executor()) ASIO_NOEXCEPT + { + return associated_executor::get(h.handler_, ex); + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_IO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_init.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_init.hpp new file mode 100644 index 00000000..1ee3b576 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_init.hpp @@ -0,0 +1,101 @@ +// +// ssl/detail/openssl_init.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_OPENSSL_INIT_HPP +#define ASIO_SSL_DETAIL_OPENSSL_INIT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/detail/memory.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/ssl/detail/openssl_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class openssl_init_base + : private noncopyable +{ +protected: + // Class that performs the actual initialisation. + class do_init; + + // Helper function to manage a do_init singleton. The static instance of the + // openssl_init object ensures that this function is always called before + // main, and therefore before any other threads can get started. The do_init + // instance must be static in this function to ensure that it gets + // initialised before any other global objects try to use it. + ASIO_DECL static asio::detail::shared_ptr instance(); + +#if !defined(SSL_OP_NO_COMPRESSION) \ + && (OPENSSL_VERSION_NUMBER >= 0x00908000L) + // Get an empty stack of compression methods, to be used when disabling + // compression. + ASIO_DECL static STACK_OF(SSL_COMP)* get_null_compression_methods(); +#endif // !defined(SSL_OP_NO_COMPRESSION) + // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) +}; + +template +class openssl_init : private openssl_init_base +{ +public: + // Constructor. + openssl_init() + : ref_(instance()) + { + using namespace std; // For memmove. + + // Ensure openssl_init::instance_ is linked in. + openssl_init* tmp = &instance_; + memmove(&tmp, &tmp, sizeof(openssl_init*)); + } + + // Destructor. + ~openssl_init() + { + } + +#if !defined(SSL_OP_NO_COMPRESSION) \ + && (OPENSSL_VERSION_NUMBER >= 0x00908000L) + using openssl_init_base::get_null_compression_methods; +#endif // !defined(SSL_OP_NO_COMPRESSION) + // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) + +private: + // Instance to force initialisation of openssl at global scope. + static openssl_init instance_; + + // Reference to singleton do_init object to ensure that openssl does not get + // cleaned up until the last user has finished with it. + asio::detail::shared_ptr ref_; +}; + +template +openssl_init openssl_init::instance_; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ssl/detail/impl/openssl_init.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SSL_DETAIL_OPENSSL_INIT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_types.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_types.hpp new file mode 100644 index 00000000..eb3359ee --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/openssl_types.hpp @@ -0,0 +1,33 @@ +// +// ssl/detail/openssl_types.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP +#define ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/socket_types.hpp" +#if defined(ASIO_USE_WOLFSSL) +# include +#endif // defined(ASIO_USE_WOLFSSL) +#include +#include +#if !defined(OPENSSL_NO_ENGINE) +# include +#endif // !defined(OPENSSL_NO_ENGINE) +#include +#include +#include +#include + +#endif // ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/password_callback.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/password_callback.hpp new file mode 100644 index 00000000..82466253 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/password_callback.hpp @@ -0,0 +1,66 @@ +// +// ssl/detail/password_callback.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP +#define ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include +#include "asio/ssl/context_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class password_callback_base +{ +public: + virtual ~password_callback_base() + { + } + + virtual std::string call(std::size_t size, + context_base::password_purpose purpose) = 0; +}; + +template +class password_callback : public password_callback_base +{ +public: + explicit password_callback(PasswordCallback callback) + : callback_(callback) + { + } + + virtual std::string call(std::size_t size, + context_base::password_purpose purpose) + { + return callback_(size, purpose); + } + +private: + PasswordCallback callback_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/read_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/read_op.hpp new file mode 100644 index 00000000..b73070e2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/read_op.hpp @@ -0,0 +1,67 @@ +// +// ssl/detail/read_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_READ_OP_HPP +#define ASIO_SSL_DETAIL_READ_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/ssl/detail/engine.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +template +class read_op +{ +public: + read_op(const MutableBufferSequence& buffers) + : buffers_(buffers) + { + } + + engine::want operator()(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred) const + { + asio::mutable_buffer buffer = + asio::detail::buffer_sequence_adapter::first(buffers_); + + return eng.read(buffer, ec, bytes_transferred); + } + + template + void call_handler(Handler& handler, + const asio::error_code& ec, + const std::size_t& bytes_transferred) const + { + handler(ec, bytes_transferred); + } + +private: + MutableBufferSequence buffers_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_READ_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/shutdown_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/shutdown_op.hpp new file mode 100644 index 00000000..b8c69948 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/shutdown_op.hpp @@ -0,0 +1,64 @@ +// +// ssl/detail/shutdown_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP +#define ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/ssl/detail/engine.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class shutdown_op +{ +public: + engine::want operator()(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred) const + { + bytes_transferred = 0; + return eng.shutdown(ec); + } + + template + void call_handler(Handler& handler, + const asio::error_code& ec, + const std::size_t&) const + { + if (ec == asio::error::eof) + { + // The engine only generates an eof when the shutdown notification has + // been received from the peer. This indicates that the shutdown has + // completed successfully, and thus need not be passed on to the handler. + handler(asio::error_code()); + } + else + { + handler(ec); + } + } +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/stream_core.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/stream_core.hpp new file mode 100644 index 00000000..9533c66f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/stream_core.hpp @@ -0,0 +1,135 @@ +// +// ssl/detail/stream_core.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_STREAM_CORE_HPP +#define ASIO_SSL_DETAIL_STREAM_CORE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_BOOST_DATE_TIME) +# include "asio/deadline_timer.hpp" +#else // defined(ASIO_HAS_BOOST_DATE_TIME) +# include "asio/steady_timer.hpp" +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) +#include "asio/ssl/detail/engine.hpp" +#include "asio/buffer.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +struct stream_core +{ + // According to the OpenSSL documentation, this is the buffer size that is + // sufficient to hold the largest possible TLS record. + enum { max_tls_record_size = 17 * 1024 }; + + template + stream_core(SSL_CTX* context, const Executor& ex) + : engine_(context), + pending_read_(ex), + pending_write_(ex), + output_buffer_space_(max_tls_record_size), + output_buffer_(asio::buffer(output_buffer_space_)), + input_buffer_space_(max_tls_record_size), + input_buffer_(asio::buffer(input_buffer_space_)) + { + pending_read_.expires_at(neg_infin()); + pending_write_.expires_at(neg_infin()); + } + + ~stream_core() + { + } + + // The SSL engine. + engine engine_; + +#if defined(ASIO_HAS_BOOST_DATE_TIME) + // Timer used for storing queued read operations. + asio::deadline_timer pending_read_; + + // Timer used for storing queued write operations. + asio::deadline_timer pending_write_; + + // Helper function for obtaining a time value that always fires. + static asio::deadline_timer::time_type neg_infin() + { + return boost::posix_time::neg_infin; + } + + // Helper function for obtaining a time value that never fires. + static asio::deadline_timer::time_type pos_infin() + { + return boost::posix_time::pos_infin; + } + + // Helper function to get a timer's expiry time. + static asio::deadline_timer::time_type expiry( + const asio::deadline_timer& timer) + { + return timer.expires_at(); + } +#else // defined(ASIO_HAS_BOOST_DATE_TIME) + // Timer used for storing queued read operations. + asio::steady_timer pending_read_; + + // Timer used for storing queued write operations. + asio::steady_timer pending_write_; + + // Helper function for obtaining a time value that always fires. + static asio::steady_timer::time_point neg_infin() + { + return (asio::steady_timer::time_point::min)(); + } + + // Helper function for obtaining a time value that never fires. + static asio::steady_timer::time_point pos_infin() + { + return (asio::steady_timer::time_point::max)(); + } + + // Helper function to get a timer's expiry time. + static asio::steady_timer::time_point expiry( + const asio::steady_timer& timer) + { + return timer.expiry(); + } +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + + // Buffer space used to prepare output intended for the transport. + std::vector output_buffer_space_; + + // A buffer that may be used to prepare output intended for the transport. + const asio::mutable_buffer output_buffer_; + + // Buffer space used to read input intended for the engine. + std::vector input_buffer_space_; + + // A buffer that may be used to read input intended for the engine. + const asio::mutable_buffer input_buffer_; + + // The buffer pointing to the engine's unconsumed input. + asio::const_buffer input_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_STREAM_CORE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/verify_callback.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/verify_callback.hpp new file mode 100644 index 00000000..c26d28c4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/verify_callback.hpp @@ -0,0 +1,62 @@ +// +// ssl/detail/verify_callback.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP +#define ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/ssl/verify_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +class verify_callback_base +{ +public: + virtual ~verify_callback_base() + { + } + + virtual bool call(bool preverified, verify_context& ctx) = 0; +}; + +template +class verify_callback : public verify_callback_base +{ +public: + explicit verify_callback(VerifyCallback callback) + : callback_(callback) + { + } + + virtual bool call(bool preverified, verify_context& ctx) + { + return callback_(preverified, ctx); + } + +private: + VerifyCallback callback_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/write_op.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/write_op.hpp new file mode 100644 index 00000000..a180014a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/detail/write_op.hpp @@ -0,0 +1,67 @@ +// +// ssl/detail/write_op.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_DETAIL_WRITE_OP_HPP +#define ASIO_SSL_DETAIL_WRITE_OP_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/ssl/detail/engine.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { +namespace detail { + +template +class write_op +{ +public: + write_op(const ConstBufferSequence& buffers) + : buffers_(buffers) + { + } + + engine::want operator()(engine& eng, + asio::error_code& ec, + std::size_t& bytes_transferred) const + { + asio::const_buffer buffer = + asio::detail::buffer_sequence_adapter::first(buffers_); + + return eng.write(buffer, ec, bytes_transferred); + } + + template + void call_handler(Handler& handler, + const asio::error_code& ec, + const std::size_t& bytes_transferred) const + { + handler(ec, bytes_transferred); + } + +private: + ConstBufferSequence buffers_; +}; + +} // namespace detail +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_DETAIL_WRITE_OP_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/error.hpp new file mode 100644 index 00000000..71599e7b --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/error.hpp @@ -0,0 +1,126 @@ +// +// ssl/error.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_ERROR_HPP +#define ASIO_SSL_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/error_code.hpp" +#include "asio/ssl/detail/openssl_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace error { + +enum ssl_errors +{ + // Error numbers are those produced by openssl. +}; + +extern ASIO_DECL +const asio::error_category& get_ssl_category(); + +static const asio::error_category& + ssl_category ASIO_UNUSED_VARIABLE + = asio::error::get_ssl_category(); + +} // namespace error +namespace ssl { +namespace error { + +enum stream_errors +{ +#if defined(GENERATING_DOCUMENTATION) + /// The underlying stream closed before the ssl stream gracefully shut down. + stream_truncated, + + /// The underlying SSL library returned a system error without providing + /// further information. + unspecified_system_error, + + /// The underlying SSL library generated an unexpected result from a function + /// call. + unexpected_result +#else // defined(GENERATING_DOCUMENTATION) +# if (OPENSSL_VERSION_NUMBER < 0x10100000L) \ + && !defined(OPENSSL_IS_BORINGSSL) \ + && !defined(ASIO_USE_WOLFSSL) \ + && !defined(ASIO_USE_ESP_OPENSSL) + stream_truncated = ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHORT_READ), +# else + stream_truncated = 1, +# endif + unspecified_system_error = 2, + unexpected_result = 3 +#endif // defined(GENERATING_DOCUMENTATION) +}; + +extern ASIO_DECL +const asio::error_category& get_stream_category(); + +static const asio::error_category& + stream_category ASIO_UNUSED_VARIABLE + = asio::ssl::error::get_stream_category(); + +} // namespace error +} // namespace ssl +} // namespace asio + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) +namespace std { + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +template<> struct is_error_code_enum +{ + static const bool value = true; +}; + +} // namespace std +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +namespace asio { +namespace error { + +inline asio::error_code make_error_code(ssl_errors e) +{ + return asio::error_code( + static_cast(e), get_ssl_category()); +} + +} // namespace error +namespace ssl { +namespace error { + +inline asio::error_code make_error_code(stream_errors e) +{ + return asio::error_code( + static_cast(e), get_stream_category()); +} + +} // namespace error +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ssl/impl/error.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SSL_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/context.hpp new file mode 100644 index 00000000..2831e2b4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/context.hpp @@ -0,0 +1,67 @@ +// +// ssl/impl/context.hpp +// ~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com +// Copyright (c) 2005-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_IMPL_CONTEXT_HPP +#define ASIO_SSL_IMPL_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/throw_error.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +template +void context::set_verify_callback(VerifyCallback callback) +{ + asio::error_code ec; + this->set_verify_callback(callback, ec); + asio::detail::throw_error(ec, "set_verify_callback"); +} + +template +ASIO_SYNC_OP_VOID context::set_verify_callback( + VerifyCallback callback, asio::error_code& ec) +{ + do_set_verify_callback( + new detail::verify_callback(callback), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); +} + +template +void context::set_password_callback(PasswordCallback callback) +{ + asio::error_code ec; + this->set_password_callback(callback, ec); + asio::detail::throw_error(ec, "set_password_callback"); +} + +template +ASIO_SYNC_OP_VOID context::set_password_callback( + PasswordCallback callback, asio::error_code& ec) +{ + do_set_password_callback( + new detail::password_callback(callback), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); +} + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_IMPL_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/src.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/src.hpp new file mode 100644 index 00000000..0c092cf0 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/impl/src.hpp @@ -0,0 +1,28 @@ +// +// impl/ssl/src.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_IMPL_SRC_HPP +#define ASIO_SSL_IMPL_SRC_HPP + +#define ASIO_SOURCE + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HEADER_ONLY) +# error Do not compile Asio library source with ASIO_HEADER_ONLY defined +#endif + +#include "asio/ssl/impl/context.ipp" +#include "asio/ssl/impl/error.ipp" +#include "asio/ssl/detail/impl/engine.ipp" +#include "asio/ssl/detail/impl/openssl_init.ipp" +#include "asio/ssl/impl/rfc2818_verification.ipp" + +#endif // ASIO_SSL_IMPL_SRC_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/rfc2818_verification.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/rfc2818_verification.hpp new file mode 100644 index 00000000..a8bd8d9d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/rfc2818_verification.hpp @@ -0,0 +1,94 @@ +// +// ssl/rfc2818_verification.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_RFC2818_VERIFICATION_HPP +#define ASIO_SSL_RFC2818_VERIFICATION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include +#include "asio/ssl/detail/openssl_types.hpp" +#include "asio/ssl/verify_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// Verifies a certificate against a hostname according to the rules described +/// in RFC 2818. +/** + * @par Example + * The following example shows how to synchronously open a secure connection to + * a given host name: + * @code + * using asio::ip::tcp; + * namespace ssl = asio::ssl; + * typedef ssl::stream ssl_socket; + * + * // Create a context that uses the default paths for finding CA certificates. + * ssl::context ctx(ssl::context::sslv23); + * ctx.set_default_verify_paths(); + * + * // Open a socket and connect it to the remote host. + * asio::io_context io_context; + * ssl_socket sock(io_context, ctx); + * tcp::resolver resolver(io_context); + * tcp::resolver::query query("host.name", "https"); + * asio::connect(sock.lowest_layer(), resolver.resolve(query)); + * sock.lowest_layer().set_option(tcp::no_delay(true)); + * + * // Perform SSL handshake and verify the remote host's certificate. + * sock.set_verify_mode(ssl::verify_peer); + * sock.set_verify_callback(ssl::rfc2818_verification("host.name")); + * sock.handshake(ssl_socket::client); + * + * // ... read and write as normal ... + * @endcode + */ +class rfc2818_verification +{ +public: + /// The type of the function object's result. + typedef bool result_type; + + /// Constructor. + explicit rfc2818_verification(const std::string& host) + : host_(host) + { + } + + /// Perform certificate verification. + ASIO_DECL bool operator()(bool preverified, verify_context& ctx) const; + +private: + // Helper function to check a host name against a pattern. + ASIO_DECL static bool match_pattern(const char* pattern, + std::size_t pattern_length, const char* host); + + // Helper function to check a host name against an IPv4 address + // The host name to be checked. + std::string host_; +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#if defined(ASIO_HEADER_ONLY) +# include "asio/ssl/impl/rfc2818_verification.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SSL_RFC2818_VERIFICATION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream.hpp new file mode 100644 index 00000000..6a2a31c8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream.hpp @@ -0,0 +1,885 @@ +// +// ssl/stream.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_STREAM_HPP +#define ASIO_SSL_STREAM_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/async_result.hpp" +#include "asio/detail/buffer_sequence_adapter.hpp" +#include "asio/detail/handler_type_requirements.hpp" +#include "asio/detail/non_const_lvalue.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/type_traits.hpp" +#include "asio/ssl/context.hpp" +#include "asio/ssl/detail/buffered_handshake_op.hpp" +#include "asio/ssl/detail/handshake_op.hpp" +#include "asio/ssl/detail/io.hpp" +#include "asio/ssl/detail/read_op.hpp" +#include "asio/ssl/detail/shutdown_op.hpp" +#include "asio/ssl/detail/stream_core.hpp" +#include "asio/ssl/detail/write_op.hpp" +#include "asio/ssl/stream_base.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// Provides stream-oriented functionality using SSL. +/** + * The stream class template provides asynchronous and blocking stream-oriented + * functionality using SSL. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. The application must also ensure that all + * asynchronous operations are performed within the same implicit or explicit + * strand. + * + * @par Example + * To use the SSL stream template with an ip::tcp::socket, you would write: + * @code + * asio::io_context my_context; + * asio::ssl::context ctx(asio::ssl::context::sslv23); + * asio::ssl::stream sock(my_context, ctx); + * @endcode + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class stream : + public stream_base, + private noncopyable +{ +public: + /// The native handle type of the SSL stream. + typedef SSL* native_handle_type; + + /// Structure for use with deprecated impl_type. + struct impl_struct + { + SSL* ssl; + }; + + /// The type of the next layer. + typedef typename remove_reference::type next_layer_type; + + /// The type of the lowest layer. + typedef typename next_layer_type::lowest_layer_type lowest_layer_type; + + /// The type of the executor associated with the object. + typedef typename lowest_layer_type::executor_type executor_type; + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Construct a stream. + /** + * This constructor creates a stream and initialises the underlying stream + * object. + * + * @param arg The argument to be passed to initialise the underlying stream. + * + * @param ctx The SSL context to be used for the stream. + */ + template + stream(Arg&& arg, context& ctx) + : next_layer_(ASIO_MOVE_CAST(Arg)(arg)), + core_(ctx.native_handle(), next_layer_.lowest_layer().get_executor()) + { + } +#else // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + template + stream(Arg& arg, context& ctx) + : next_layer_(arg), + core_(ctx.native_handle(), next_layer_.lowest_layer().get_executor()) + { + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor. + /** + * @note A @c stream object must not be destroyed while there are pending + * asynchronous operations associated with it. + */ + ~stream() + { + } + + /// Get the executor associated with the object. + /** + * This function may be used to obtain the executor object that the stream + * uses to dispatch handlers for asynchronous operations. + * + * @return A copy of the executor that stream will use to dispatch handlers. + */ + executor_type get_executor() ASIO_NOEXCEPT + { + return next_layer_.lowest_layer().get_executor(); + } + + /// Get the underlying implementation in the native type. + /** + * This function may be used to obtain the underlying implementation of the + * context. This is intended to allow access to context functionality that is + * not otherwise provided. + * + * @par Example + * The native_handle() function returns a pointer of type @c SSL* that is + * suitable for passing to functions such as @c SSL_get_verify_result and + * @c SSL_get_peer_certificate: + * @code + * asio::ssl::stream sock(my_context, ctx); + * + * // ... establish connection and perform handshake ... + * + * if (X509* cert = SSL_get_peer_certificate(sock.native_handle())) + * { + * if (SSL_get_verify_result(sock.native_handle()) == X509_V_OK) + * { + * // ... + * } + * } + * @endcode + */ + native_handle_type native_handle() + { + return core_.engine_.native_handle(); + } + + /// Get a reference to the next layer. + /** + * This function returns a reference to the next layer in a stack of stream + * layers. + * + * @return A reference to the next layer in the stack of stream layers. + * Ownership is not transferred to the caller. + */ + const next_layer_type& next_layer() const + { + return next_layer_; + } + + /// Get a reference to the next layer. + /** + * This function returns a reference to the next layer in a stack of stream + * layers. + * + * @return A reference to the next layer in the stack of stream layers. + * Ownership is not transferred to the caller. + */ + next_layer_type& next_layer() + { + return next_layer_; + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * stream layers. + * + * @return A reference to the lowest layer in the stack of stream layers. + * Ownership is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return next_layer_.lowest_layer(); + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * stream layers. + * + * @return A reference to the lowest layer in the stack of stream layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return next_layer_.lowest_layer(); + } + + /// Set the peer verification mode. + /** + * This function may be used to configure the peer verification mode used by + * the stream. The new mode will override the mode inherited from the context. + * + * @param v A bitmask of peer verification modes. See @ref verify_mode for + * available values. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_set_verify. + */ + void set_verify_mode(verify_mode v) + { + asio::error_code ec; + set_verify_mode(v, ec); + asio::detail::throw_error(ec, "set_verify_mode"); + } + + /// Set the peer verification mode. + /** + * This function may be used to configure the peer verification mode used by + * the stream. The new mode will override the mode inherited from the context. + * + * @param v A bitmask of peer verification modes. See @ref verify_mode for + * available values. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_set_verify. + */ + ASIO_SYNC_OP_VOID set_verify_mode( + verify_mode v, asio::error_code& ec) + { + core_.engine_.set_verify_mode(v, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Set the peer verification depth. + /** + * This function may be used to configure the maximum verification depth + * allowed by the stream. + * + * @param depth Maximum depth for the certificate chain verification that + * shall be allowed. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_set_verify_depth. + */ + void set_verify_depth(int depth) + { + asio::error_code ec; + set_verify_depth(depth, ec); + asio::detail::throw_error(ec, "set_verify_depth"); + } + + /// Set the peer verification depth. + /** + * This function may be used to configure the maximum verification depth + * allowed by the stream. + * + * @param depth Maximum depth for the certificate chain verification that + * shall be allowed. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_set_verify_depth. + */ + ASIO_SYNC_OP_VOID set_verify_depth( + int depth, asio::error_code& ec) + { + core_.engine_.set_verify_depth(depth, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Set the callback used to verify peer certificates. + /** + * This function is used to specify a callback function that will be called + * by the implementation when it needs to verify a peer certificate. + * + * @param callback The function object to be used for verifying a certificate. + * The function signature of the handler must be: + * @code bool verify_callback( + * bool preverified, // True if the certificate passed pre-verification. + * verify_context& ctx // The peer certificate and other context. + * ); @endcode + * The return value of the callback is true if the certificate has passed + * verification, false otherwise. + * + * @throws asio::system_error Thrown on failure. + * + * @note Calls @c SSL_set_verify. + */ + template + void set_verify_callback(VerifyCallback callback) + { + asio::error_code ec; + this->set_verify_callback(callback, ec); + asio::detail::throw_error(ec, "set_verify_callback"); + } + + /// Set the callback used to verify peer certificates. + /** + * This function is used to specify a callback function that will be called + * by the implementation when it needs to verify a peer certificate. + * + * @param callback The function object to be used for verifying a certificate. + * The function signature of the handler must be: + * @code bool verify_callback( + * bool preverified, // True if the certificate passed pre-verification. + * verify_context& ctx // The peer certificate and other context. + * ); @endcode + * The return value of the callback is true if the certificate has passed + * verification, false otherwise. + * + * @param ec Set to indicate what error occurred, if any. + * + * @note Calls @c SSL_set_verify. + */ + template + ASIO_SYNC_OP_VOID set_verify_callback(VerifyCallback callback, + asio::error_code& ec) + { + core_.engine_.set_verify_callback( + new detail::verify_callback(callback), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform SSL handshaking. + /** + * This function is used to perform SSL handshaking on the stream. The + * function call will block until handshaking is complete or an error occurs. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @throws asio::system_error Thrown on failure. + */ + void handshake(handshake_type type) + { + asio::error_code ec; + handshake(type, ec); + asio::detail::throw_error(ec, "handshake"); + } + + /// Perform SSL handshaking. + /** + * This function is used to perform SSL handshaking on the stream. The + * function call will block until handshaking is complete or an error occurs. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID handshake(handshake_type type, + asio::error_code& ec) + { + detail::io(next_layer_, core_, detail::handshake_op(type), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform SSL handshaking. + /** + * This function is used to perform SSL handshaking on the stream. The + * function call will block until handshaking is complete or an error occurs. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @param buffers The buffered data to be reused for the handshake. + * + * @throws asio::system_error Thrown on failure. + */ + template + void handshake(handshake_type type, const ConstBufferSequence& buffers) + { + asio::error_code ec; + handshake(type, buffers, ec); + asio::detail::throw_error(ec, "handshake"); + } + + /// Perform SSL handshaking. + /** + * This function is used to perform SSL handshaking on the stream. The + * function call will block until handshaking is complete or an error occurs. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @param buffers The buffered data to be reused for the handshake. + * + * @param ec Set to indicate what error occurred, if any. + */ + template + ASIO_SYNC_OP_VOID handshake(handshake_type type, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + detail::io(next_layer_, core_, + detail::buffered_handshake_op(type, buffers), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Start an asynchronous SSL handshake. + /** + * This function is used to asynchronously perform an SSL handshake on the + * stream. This function call always returns immediately. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @param handler The handler to be called when the handshake operation + * completes. Copies will be made of the handler as required. The equivalent + * function signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + HandshakeHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(HandshakeHandler, + void (asio::error_code)) + async_handshake(handshake_type type, + ASIO_MOVE_ARG(HandshakeHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_handshake(this), handler, type); + } + + /// Start an asynchronous SSL handshake. + /** + * This function is used to asynchronously perform an SSL handshake on the + * stream. This function call always returns immediately. + * + * @param type The type of handshaking to be performed, i.e. as a client or as + * a server. + * + * @param buffers The buffered data to be reused for the handshake. Although + * the buffers object may be copied as necessary, ownership of the underlying + * buffers is retained by the caller, which must guarantee that they remain + * valid until the handler is called. + * + * @param handler The handler to be called when the handshake operation + * completes. Copies will be made of the handler as required. The equivalent + * function signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Amount of buffers used in handshake. + * ); @endcode + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(BufferedHandshakeHandler, + void (asio::error_code, std::size_t)) + async_handshake(handshake_type type, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(BufferedHandshakeHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_buffered_handshake(this), handler, type, buffers); + } + + /// Shut down SSL on the stream. + /** + * This function is used to shut down SSL on the stream. The function call + * will block until SSL has been shut down or an error occurs. + * + * @throws asio::system_error Thrown on failure. + */ + void shutdown() + { + asio::error_code ec; + shutdown(ec); + asio::detail::throw_error(ec, "shutdown"); + } + + /// Shut down SSL on the stream. + /** + * This function is used to shut down SSL on the stream. The function call + * will block until SSL has been shut down or an error occurs. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID shutdown(asio::error_code& ec) + { + detail::io(next_layer_, core_, detail::shutdown_op(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Asynchronously shut down SSL on the stream. + /** + * This function is used to asynchronously shut down SSL on the stream. This + * function call always returns immediately. + * + * @param handler The handler to be called when the handshake operation + * completes. Copies will be made of the handler as required. The equivalent + * function signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + ShutdownHandler + ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(ShutdownHandler, + void (asio::error_code)) + async_shutdown( + ASIO_MOVE_ARG(ShutdownHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_shutdown(this), handler); + } + + /// Write some data to the stream. + /** + * This function is used to write data on the stream. The function call will + * block until one or more bytes of data has been written successfully, or + * until an error occurs. + * + * @param buffers The data to be written. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that all + * data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t n = write_some(buffers, ec); + asio::detail::throw_error(ec, "write_some"); + return n; + } + + /// Write some data to the stream. + /** + * This function is used to write data on the stream. The function call will + * block until one or more bytes of data has been written successfully, or + * until an error occurs. + * + * @param buffers The data to be written to the stream. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that all + * data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return detail::io(next_layer_, core_, + detail::write_op(buffers), ec); + } + + /// Start an asynchronous write. + /** + * This function is used to asynchronously write one or more bytes of data to + * the stream. The function call always returns immediately. + * + * @param buffers The data to be written to the stream. Although the buffers + * object may be copied as necessary, ownership of the underlying buffers is + * retained by the caller, which must guarantee that they remain valid until + * the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The equivalent function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * + * @note The async_write_some operation may not transmit all of the data to + * the peer. Consider using the @ref async_write function if you need to + * ensure that all data is written before the asynchronous operation + * completes. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_write_some(this), handler, buffers); + } + + /// Read some data from the stream. + /** + * This function is used to read data from the stream. The function call will + * block until one or more bytes of data has been read successfully, or until + * an error occurs. + * + * @param buffers The buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t n = read_some(buffers, ec); + asio::detail::throw_error(ec, "read_some"); + return n; + } + + /// Read some data from the stream. + /** + * This function is used to read data from the stream. The function call will + * block until one or more bytes of data has been read successfully, or until + * an error occurs. + * + * @param buffers The buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that the + * requested amount of data is read before the blocking operation completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return detail::io(next_layer_, core_, + detail::read_op(buffers), ec); + } + + /// Start an asynchronous read. + /** + * This function is used to asynchronously read one or more bytes of data from + * the stream. The function call always returns immediately. + * + * @param buffers The buffers into which the data will be read. Although the + * buffers object may be copied as necessary, ownership of the underlying + * buffers is retained by the caller, which must guarantee that they remain + * valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The equivalent function + * signature of the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * + * @note The async_read_some operation may not read all of the requested + * number of bytes. Consider using the @ref async_read function if you need to + * ensure that the requested amount of data is read before the asynchronous + * operation completes. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_read_some(this), handler, buffers); + } + +private: + class initiate_async_handshake + { + public: + typedef stream::executor_type executor_type; + + explicit initiate_async_handshake(stream* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(HandshakeHandler) handler, + handshake_type type) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a HandshakeHandler. + ASIO_HANDSHAKE_HANDLER_CHECK(HandshakeHandler, handler) type_check; + + asio::detail::non_const_lvalue handler2(handler); + detail::async_io(self_->next_layer_, self_->core_, + detail::handshake_op(type), handler2.value); + } + + private: + stream* self_; + }; + + class initiate_async_buffered_handshake + { + public: + typedef stream::executor_type executor_type; + + explicit initiate_async_buffered_handshake(stream* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(BufferedHandshakeHandler) handler, + handshake_type type, const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your + // handler does not meet the documented type requirements for a + // BufferedHandshakeHandler. + ASIO_BUFFERED_HANDSHAKE_HANDLER_CHECK( + BufferedHandshakeHandler, handler) type_check; + + asio::detail::non_const_lvalue< + BufferedHandshakeHandler> handler2(handler); + detail::async_io(self_->next_layer_, self_->core_, + detail::buffered_handshake_op(type, buffers), + handler2.value); + } + + private: + stream* self_; + }; + + class initiate_async_shutdown + { + public: + typedef typename stream::executor_type executor_type; + + explicit initiate_async_shutdown(stream* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ShutdownHandler) handler) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ShutdownHandler. + ASIO_HANDSHAKE_HANDLER_CHECK(ShutdownHandler, handler) type_check; + + asio::detail::non_const_lvalue handler2(handler); + detail::async_io(self_->next_layer_, self_->core_, + detail::shutdown_op(), handler2.value); + } + + private: + stream* self_; + }; + + class initiate_async_write_some + { + public: + typedef typename stream::executor_type executor_type; + + explicit initiate_async_write_some(stream* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + asio::detail::non_const_lvalue handler2(handler); + detail::async_io(self_->next_layer_, self_->core_, + detail::write_op(buffers), handler2.value); + } + + private: + stream* self_; + }; + + class initiate_async_read_some + { + public: + typedef typename stream::executor_type executor_type; + + explicit initiate_async_read_some(stream* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + asio::detail::non_const_lvalue handler2(handler); + detail::async_io(self_->next_layer_, self_->core_, + detail::read_op(buffers), handler2.value); + } + + private: + stream* self_; + }; + + Stream next_layer_; + detail::stream_core core_; +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_STREAM_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream_base.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream_base.hpp new file mode 100644 index 00000000..7960e99d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/stream_base.hpp @@ -0,0 +1,52 @@ +// +// ssl/stream_base.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_STREAM_BASE_HPP +#define ASIO_SSL_STREAM_BASE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// The stream_base class is used as a base for the asio::ssl::stream +/// class template so that we have a common place to define various enums. +class stream_base +{ +public: + /// Different handshake types. + enum handshake_type + { + /// Perform handshaking as a client. + client, + + /// Perform handshaking as a server. + server + }; + +protected: + /// Protected destructor to prevent deletion through this type. + ~stream_base() + { + } +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_STREAM_BASE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_context.hpp new file mode 100644 index 00000000..bfb608db --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_context.hpp @@ -0,0 +1,67 @@ +// +// ssl/verify_context.hpp +// ~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_VERIFY_CONTEXT_HPP +#define ASIO_SSL_VERIFY_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/noncopyable.hpp" +#include "asio/ssl/detail/openssl_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// A simple wrapper around the X509_STORE_CTX type, used during verification of +/// a peer certificate. +/** + * @note The verify_context does not own the underlying X509_STORE_CTX object. + */ +class verify_context + : private noncopyable +{ +public: + /// The native handle type of the verification context. + typedef X509_STORE_CTX* native_handle_type; + + /// Constructor. + explicit verify_context(native_handle_type handle) + : handle_(handle) + { + } + + /// Get the underlying implementation in the native type. + /** + * This function may be used to obtain the underlying implementation of the + * context. This is intended to allow access to context functionality that is + * not otherwise provided. + */ + native_handle_type native_handle() + { + return handle_; + } + +private: + // The underlying native implementation. + native_handle_type handle_; +}; + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_VERIFY_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_mode.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_mode.hpp new file mode 100644 index 00000000..bcd6f8ea --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ssl/verify_mode.hpp @@ -0,0 +1,63 @@ +// +// ssl/verify_mode.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SSL_VERIFY_MODE_HPP +#define ASIO_SSL_VERIFY_MODE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/ssl/detail/openssl_types.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace ssl { + +/// Bitmask type for peer verification. +/** + * Possible values are: + * + * @li @ref verify_none + * @li @ref verify_peer + * @li @ref verify_fail_if_no_peer_cert + * @li @ref verify_client_once + */ +typedef int verify_mode; + +#if defined(GENERATING_DOCUMENTATION) +/// No verification. +const int verify_none = implementation_defined; + +/// Verify the peer. +const int verify_peer = implementation_defined; + +/// Fail verification if the peer has no certificate. Ignored unless +/// @ref verify_peer is set. +const int verify_fail_if_no_peer_cert = implementation_defined; + +/// Do not request client certificate on renegotiation. Ignored unless +/// @ref verify_peer is set. +const int verify_client_once = implementation_defined; +#else +const int verify_none = SSL_VERIFY_NONE; +const int verify_peer = SSL_VERIFY_PEER; +const int verify_fail_if_no_peer_cert = SSL_VERIFY_FAIL_IF_NO_PEER_CERT; +const int verify_client_once = SSL_VERIFY_CLIENT_ONCE; +#endif + +} // namespace ssl +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SSL_VERIFY_MODE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/steady_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/steady_timer.hpp new file mode 100644 index 00000000..22317405 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/steady_timer.hpp @@ -0,0 +1,42 @@ +// +// steady_timer.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_STEADY_TIMER_HPP +#define ASIO_STEADY_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_waitable_timer.hpp" +#include "asio/detail/chrono.hpp" + +namespace asio { + +/// Typedef for a timer based on the steady clock. +/** + * This typedef uses the C++11 @c <chrono> standard library facility, if + * available. Otherwise, it may use the Boost.Chrono library. To explicitly + * utilise Boost.Chrono, use the basic_waitable_timer template directly: + * @code + * typedef basic_waitable_timer timer; + * @endcode + */ +typedef basic_waitable_timer steady_timer; + +} // namespace asio + +#endif // defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_STEADY_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/strand.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/strand.hpp new file mode 100644 index 00000000..b807e4bf --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/strand.hpp @@ -0,0 +1,313 @@ +// +// strand.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_STRAND_HPP +#define ASIO_STRAND_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/strand_executor_service.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Provides serialised function invocation for any executor type. +template +class strand +{ +public: + /// The type of the underlying executor. + typedef Executor inner_executor_type; + + /// Default constructor. + /** + * This constructor is only valid if the underlying executor type is default + * constructible. + */ + strand() + : executor_(), + impl_(use_service( + executor_.context()).create_implementation()) + { + } + + /// Construct a strand for the specified executor. + explicit strand(const Executor& e) + : executor_(e), + impl_(use_service( + executor_.context()).create_implementation()) + { + } + + /// Copy constructor. + strand(const strand& other) ASIO_NOEXCEPT + : executor_(other.executor_), + impl_(other.impl_) + { + } + + /// Converting constructor. + /** + * This constructor is only valid if the @c OtherExecutor type is convertible + * to @c Executor. + */ + template + strand( + const strand& other) ASIO_NOEXCEPT + : executor_(other.executor_), + impl_(other.impl_) + { + } + + /// Assignment operator. + strand& operator=(const strand& other) ASIO_NOEXCEPT + { + executor_ = other.executor_; + impl_ = other.impl_; + return *this; + } + + /// Converting assignment operator. + /** + * This assignment operator is only valid if the @c OtherExecutor type is + * convertible to @c Executor. + */ + template + strand& operator=( + const strand& other) ASIO_NOEXCEPT + { + executor_ = other.executor_; + impl_ = other.impl_; + return *this; + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move constructor. + strand(strand&& other) ASIO_NOEXCEPT + : executor_(ASIO_MOVE_CAST(Executor)(other.executor_)), + impl_(ASIO_MOVE_CAST(implementation_type)(other.impl_)) + { + } + + /// Converting move constructor. + /** + * This constructor is only valid if the @c OtherExecutor type is convertible + * to @c Executor. + */ + template + strand(strand&& other) ASIO_NOEXCEPT + : executor_(ASIO_MOVE_CAST(OtherExecutor)(other)), + impl_(ASIO_MOVE_CAST(implementation_type)(other.impl_)) + { + } + + /// Move assignment operator. + strand& operator=(strand&& other) ASIO_NOEXCEPT + { + executor_ = ASIO_MOVE_CAST(Executor)(other); + impl_ = ASIO_MOVE_CAST(implementation_type)(other.impl_); + return *this; + } + + /// Converting move assignment operator. + /** + * This assignment operator is only valid if the @c OtherExecutor type is + * convertible to @c Executor. + */ + template + strand& operator=( + const strand&& other) ASIO_NOEXCEPT + { + executor_ = ASIO_MOVE_CAST(OtherExecutor)(other); + impl_ = ASIO_MOVE_CAST(implementation_type)(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Destructor. + ~strand() + { + } + + /// Obtain the underlying executor. + inner_executor_type get_inner_executor() const ASIO_NOEXCEPT + { + return executor_; + } + + /// Obtain the underlying execution context. + execution_context& context() const ASIO_NOEXCEPT + { + return executor_.context(); + } + + /// Inform the strand that it has some outstanding work to do. + /** + * The strand delegates this call to its underlying executor. + */ + void on_work_started() const ASIO_NOEXCEPT + { + executor_.on_work_started(); + } + + /// Inform the strand that some work is no longer outstanding. + /** + * The strand delegates this call to its underlying executor. + */ + void on_work_finished() const ASIO_NOEXCEPT + { + executor_.on_work_finished(); + } + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the strand to execute the given function + * object on its underlying executor. The function object will be executed + * inside this function if the strand is not otherwise busy and if the + * underlying executor's @c dispatch() function is also able to execute the + * function before returning. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + detail::strand_executor_service::dispatch(impl_, + executor_, ASIO_MOVE_CAST(Function)(f), a); + } + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled by the underlying executor's defer function. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + detail::strand_executor_service::post(impl_, + executor_, ASIO_MOVE_CAST(Function)(f), a); + } + + /// Request the strand to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled by the underlying executor's defer function. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const + { + detail::strand_executor_service::defer(impl_, + executor_, ASIO_MOVE_CAST(Function)(f), a); + } + + /// Determine whether the strand is running in the current thread. + /** + * @return @c true if the current thread is executing a function that was + * submitted to the strand using post(), dispatch() or defer(). Otherwise + * returns @c false. + */ + bool running_in_this_thread() const ASIO_NOEXCEPT + { + return detail::strand_executor_service::running_in_this_thread(impl_); + } + + /// Compare two strands for equality. + /** + * Two strands are equal if they refer to the same ordered, non-concurrent + * state. + */ + friend bool operator==(const strand& a, const strand& b) ASIO_NOEXCEPT + { + return a.impl_ == b.impl_; + } + + /// Compare two strands for inequality. + /** + * Two strands are equal if they refer to the same ordered, non-concurrent + * state. + */ + friend bool operator!=(const strand& a, const strand& b) ASIO_NOEXCEPT + { + return a.impl_ != b.impl_; + } + +private: + Executor executor_; + typedef detail::strand_executor_service::implementation_type + implementation_type; + implementation_type impl_; +}; + +/** @defgroup make_strand asio::make_strand + * + * @brief The asio::make_strand function creates a @ref strand object for + * an executor or execution context. + */ +/*@{*/ + +/// Create a @ref strand object for an executor. +template +inline strand make_strand(const Executor& ex, + typename enable_if::value>::type* = 0) +{ + return strand(ex); +} + +/// Create a @ref strand object for an execution context. +template +inline strand +make_strand(ExecutionContext& ctx, + typename enable_if< + is_convertible::value>::type* = 0) +{ + return strand(ctx.get_executor()); +} + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +// If both io_context.hpp and strand.hpp have been included, automatically +// include the header file needed for the io_context::strand class. +#if !defined(ASIO_NO_EXTENSIONS) +# if defined(ASIO_IO_CONTEXT_HPP) +# include "asio/io_context_strand.hpp" +# endif // defined(ASIO_IO_CONTEXT_HPP) +#endif // !defined(ASIO_NO_EXTENSIONS) + +#endif // ASIO_STRAND_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/streambuf.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/streambuf.hpp new file mode 100644 index 00000000..0b9bbad3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/streambuf.hpp @@ -0,0 +1,33 @@ +// +// streambuf.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_STREAMBUF_HPP +#define ASIO_STREAMBUF_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if !defined(ASIO_NO_IOSTREAM) + +#include "asio/basic_streambuf.hpp" + +namespace asio { + +/// Typedef for the typical usage of basic_streambuf. +typedef basic_streambuf<> streambuf; + +} // namespace asio + +#endif // !defined(ASIO_NO_IOSTREAM) + +#endif // ASIO_STREAMBUF_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_context.hpp new file mode 100644 index 00000000..c6e2d61a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_context.hpp @@ -0,0 +1,81 @@ +// +// system_context.hpp +// ~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SYSTEM_CONTEXT_HPP +#define ASIO_SYSTEM_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/scheduler.hpp" +#include "asio/detail/thread_group.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class system_executor; + +/// The executor context for the system executor. +class system_context : public execution_context +{ +public: + /// The executor type associated with the context. + typedef system_executor executor_type; + + /// Destructor shuts down all threads in the system thread pool. + ASIO_DECL ~system_context(); + + /// Obtain an executor for the context. + executor_type get_executor() ASIO_NOEXCEPT; + + /// Signal all threads in the system thread pool to stop. + ASIO_DECL void stop(); + + /// Determine whether the system thread pool has been stopped. + ASIO_DECL bool stopped() const ASIO_NOEXCEPT; + + /// Join all threads in the system thread pool. + ASIO_DECL void join(); + +#if defined(GENERATING_DOCUMENTATION) +private: +#endif // defined(GENERATING_DOCUMENTATION) + // Constructor creates all threads in the system thread pool. + ASIO_DECL system_context(); + +private: + friend class system_executor; + + struct thread_function; + + // Helper function to create the underlying scheduler. + ASIO_DECL detail::scheduler& add_scheduler(detail::scheduler* s); + + // The underlying scheduler. + detail::scheduler& scheduler_; + + // The threads in the system thread pool. + detail::thread_group threads_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/system_context.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/system_context.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_SYSTEM_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_error.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_error.hpp new file mode 100644 index 00000000..272fc599 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_error.hpp @@ -0,0 +1,131 @@ +// +// system_error.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SYSTEM_ERROR_HPP +#define ASIO_SYSTEM_ERROR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) +# include +#else // defined(ASIO_HAS_STD_SYSTEM_ERROR) +# include +# include +# include +# include "asio/error_code.hpp" +# include "asio/detail/scoped_ptr.hpp" +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +#if defined(ASIO_HAS_STD_SYSTEM_ERROR) + +typedef std::system_error system_error; + +#else // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +/// The system_error class is used to represent system conditions that +/// prevent the library from operating correctly. +class system_error + : public std::exception +{ +public: + /// Construct with an error code. + system_error(const error_code& ec) + : code_(ec), + context_() + { + } + + /// Construct with an error code and context. + system_error(const error_code& ec, const std::string& context) + : code_(ec), + context_(context) + { + } + + /// Copy constructor. + system_error(const system_error& other) + : std::exception(other), + code_(other.code_), + context_(other.context_), + what_() + { + } + + /// Destructor. + virtual ~system_error() throw () + { + } + + /// Assignment operator. + system_error& operator=(const system_error& e) + { + context_ = e.context_; + code_ = e.code_; + what_.reset(); + return *this; + } + + /// Get a string representation of the exception. + virtual const char* what() const throw () + { +#if !defined(ASIO_NO_EXCEPTIONS) + try +#endif // !defined(ASIO_NO_EXCEPTIONS) + { + if (!what_.get()) + { + std::string tmp(context_); + if (tmp.length()) + tmp += ": "; + tmp += code_.message(); + what_.reset(new std::string(tmp)); + } + return what_->c_str(); + } +#if !defined(ASIO_NO_EXCEPTIONS) + catch (std::exception&) + { + return "system_error"; + } +#endif // !defined(ASIO_NO_EXCEPTIONS) + } + + /// Get the error code associated with the exception. + error_code code() const + { + return code_; + } + +private: + // The code associated with the error. + error_code code_; + + // The context associated with the error. + std::string context_; + + // The string representation of the error. + mutable asio::detail::scoped_ptr what_; +}; + +#endif // defined(ASIO_HAS_STD_SYSTEM_ERROR) + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_SYSTEM_ERROR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_executor.hpp new file mode 100644 index 00000000..51c61603 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_executor.hpp @@ -0,0 +1,129 @@ +// +// system_executor.hpp +// ~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SYSTEM_EXECUTOR_HPP +#define ASIO_SYSTEM_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class system_context; + +/// An executor that uses arbitrary threads. +/** + * The system executor represents an execution context where functions are + * permitted to run on arbitrary threads. The post() and defer() functions + * schedule the function to run on an unspecified system thread pool, and + * dispatch() invokes the function immediately. + */ +class system_executor +{ +public: + /// Obtain the underlying execution context. + system_context& context() const ASIO_NOEXCEPT; + + /// Inform the executor that it has some outstanding work to do. + /** + * For the system executor, this is a no-op. + */ + void on_work_started() const ASIO_NOEXCEPT + { + } + + /// Inform the executor that some work is no longer outstanding. + /** + * For the system executor, this is a no-op. + */ + void on_work_finished() const ASIO_NOEXCEPT + { + } + + /// Request the system executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will always be executed inside this function. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the system executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled to run on an unspecified system thread pool. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the system executor to invoke the given function object. + /** + * This function is used to ask the executor to execute the given function + * object. The function object will never be executed inside this function. + * Instead, it will be scheduled to run on an unspecified system thread pool. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Compare two executors for equality. + /** + * System executors always compare equal. + */ + friend bool operator==(const system_executor&, + const system_executor&) ASIO_NOEXCEPT + { + return true; + } + + /// Compare two executors for inequality. + /** + * System executors always compare equal. + */ + friend bool operator!=(const system_executor&, + const system_executor&) ASIO_NOEXCEPT + { + return false; + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/system_executor.hpp" + +#endif // ASIO_SYSTEM_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_timer.hpp new file mode 100644 index 00000000..5a79bf17 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/system_timer.hpp @@ -0,0 +1,42 @@ +// +// system_timer.hpp +// ~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_SYSTEM_TIMER_HPP +#define ASIO_SYSTEM_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#include "asio/basic_waitable_timer.hpp" +#include "asio/detail/chrono.hpp" + +namespace asio { + +/// Typedef for a timer based on the system clock. +/** + * This typedef uses the C++11 @c <chrono> standard library facility, if + * available. Otherwise, it may use the Boost.Chrono library. To explicitly + * utilise Boost.Chrono, use the basic_waitable_timer template directly: + * @code + * typedef basic_waitable_timer timer; + * @endcode + */ +typedef basic_waitable_timer system_timer; + +} // namespace asio + +#endif // defined(ASIO_HAS_CHRONO) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_SYSTEM_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/this_coro.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/this_coro.hpp new file mode 100644 index 00000000..02374e10 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/this_coro.hpp @@ -0,0 +1,45 @@ +// +// this_coro.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_THIS_CORO_HPP +#define ASIO_THIS_CORO_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace this_coro { + +/// Awaitable type that returns the executor of the current coroutine. +struct executor_t +{ + ASIO_CONSTEXPR executor_t() + { + } +}; + +/// Awaitable object that returns the executor of the current coroutine. +#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) +constexpr executor_t executor; +#elif defined(ASIO_MSVC) +__declspec(selectany) executor_t executor; +#endif + +} // namespace this_coro +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_THIS_CORO_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread.hpp new file mode 100644 index 00000000..f4df4129 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread.hpp @@ -0,0 +1,92 @@ +// +// thread.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_THREAD_HPP +#define ASIO_THREAD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/thread.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// A simple abstraction for starting threads. +/** + * The asio::thread class implements the smallest possible subset of the + * functionality of boost::thread. It is intended to be used only for starting + * a thread and waiting for it to exit. If more extensive threading + * capabilities are required, you are strongly advised to use something else. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Example + * A typical use of asio::thread would be to launch a thread to run an + * io_context's event processing loop: + * + * @par + * @code asio::io_context io_context; + * // ... + * asio::thread t(boost::bind(&asio::io_context::run, &io_context)); + * // ... + * t.join(); @endcode + */ +class thread + : private noncopyable +{ +public: + /// Start a new thread that executes the supplied function. + /** + * This constructor creates a new thread that will execute the given function + * or function object. + * + * @param f The function or function object to be run in the thread. The + * function signature must be: @code void f(); @endcode + */ + template + explicit thread(Function f) + : impl_(f) + { + } + + /// Destructor. + ~thread() + { + } + + /// Wait for the thread to exit. + /** + * This function will block until the thread has exited. + * + * If this function is not called before the thread object is destroyed, the + * thread itself will continue to run until completion. You will, however, + * no longer have the ability to wait for it to exit. + */ + void join() + { + impl_.join(); + } + +private: + detail::thread impl_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_THREAD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread_pool.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread_pool.hpp new file mode 100644 index 00000000..20abe678 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/thread_pool.hpp @@ -0,0 +1,235 @@ +// +// thread_pool.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_THREAD_POOL_HPP +#define ASIO_THREAD_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/scheduler.hpp" +#include "asio/detail/thread_group.hpp" +#include "asio/execution_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// A simple fixed-size thread pool. +/** + * The thread pool class is an execution context where functions are permitted + * to run on one of a fixed number of threads. + * + * @par Submitting tasks to the pool + * + * To submit functions to the thread_pool, use the @ref asio::dispatch, + * @ref asio::post or @ref asio::defer free functions. + * + * For example: + * + * @code void my_task() + * { + * ... + * } + * + * ... + * + * // Launch the pool with four threads. + * asio::thread_pool pool(4); + * + * // Submit a function to the pool. + * asio::post(pool, my_task); + * + * // Submit a lambda object to the pool. + * asio::post(pool, + * []() + * { + * ... + * }); + * + * // Wait for all tasks in the pool to complete. + * pool.join(); @endcode + */ +class thread_pool + : public execution_context +{ +public: + class executor_type; + + /// Constructs a pool with an automatically determined number of threads. + ASIO_DECL thread_pool(); + + /// Constructs a pool with a specified number of threads. + ASIO_DECL thread_pool(std::size_t num_threads); + + /// Destructor. + /** + * Automatically stops and joins the pool, if not explicitly done beforehand. + */ + ASIO_DECL ~thread_pool(); + + /// Obtains the executor associated with the pool. + executor_type get_executor() ASIO_NOEXCEPT; + + /// Stops the threads. + /** + * This function stops the threads as soon as possible. As a result of calling + * @c stop(), pending function objects may be never be invoked. + */ + ASIO_DECL void stop(); + + /// Joins the threads. + /** + * This function blocks until the threads in the pool have completed. If @c + * stop() is not called prior to @c join(), the @c join() call will wait + * until the pool has no more outstanding work. + */ + ASIO_DECL void join(); + +private: + friend class executor_type; + struct thread_function; + + // Helper function to create the underlying scheduler. + ASIO_DECL detail::scheduler& add_scheduler(detail::scheduler* s); + + // The underlying scheduler. + detail::scheduler& scheduler_; + + // The threads in the pool. + detail::thread_group threads_; +}; + +/// Executor used to submit functions to a thread pool. +class thread_pool::executor_type +{ +public: + /// Obtain the underlying execution context. + thread_pool& context() const ASIO_NOEXCEPT; + + /// Inform the thread pool that it has some outstanding work to do. + /** + * This function is used to inform the thread pool that some work has begun. + * This ensures that the thread pool's join() function will not return while + * the work is underway. + */ + void on_work_started() const ASIO_NOEXCEPT; + + /// Inform the thread pool that some work is no longer outstanding. + /** + * This function is used to inform the thread pool that some work has + * finished. Once the count of unfinished work reaches zero, the thread + * pool's join() function is permitted to exit. + */ + void on_work_finished() const ASIO_NOEXCEPT; + + /// Request the thread pool to invoke the given function object. + /** + * This function is used to ask the thread pool to execute the given function + * object. If the current thread belongs to the pool, @c dispatch() executes + * the function before returning. Otherwise, the function will be scheduled + * to run on the thread pool. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void dispatch(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the thread pool to invoke the given function object. + /** + * This function is used to ask the thread pool to execute the given function + * object. The function object will never be executed inside @c post(). + * Instead, it will be scheduled to run on the thread pool. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void post(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Request the thread pool to invoke the given function object. + /** + * This function is used to ask the thread pool to execute the given function + * object. The function object will never be executed inside @c defer(). + * Instead, it will be scheduled to run on the thread pool. + * + * If the current thread belongs to the thread pool, @c defer() will delay + * scheduling the function object until the current thread returns control to + * the pool. + * + * @param f The function object to be called. The executor will make + * a copy of the handler object as required. The function signature of the + * function object must be: @code void function(); @endcode + * + * @param a An allocator that may be used by the executor to allocate the + * internal storage needed for function invocation. + */ + template + void defer(ASIO_MOVE_ARG(Function) f, const Allocator& a) const; + + /// Determine whether the thread pool is running in the current thread. + /** + * @return @c true if the current thread belongs to the pool. Otherwise + * returns @c false. + */ + bool running_in_this_thread() const ASIO_NOEXCEPT; + + /// Compare two executors for equality. + /** + * Two executors are equal if they refer to the same underlying thread pool. + */ + friend bool operator==(const executor_type& a, + const executor_type& b) ASIO_NOEXCEPT + { + return &a.pool_ == &b.pool_; + } + + /// Compare two executors for inequality. + /** + * Two executors are equal if they refer to the same underlying thread pool. + */ + friend bool operator!=(const executor_type& a, + const executor_type& b) ASIO_NOEXCEPT + { + return &a.pool_ != &b.pool_; + } + +private: + friend class thread_pool; + + // Constructor. + explicit executor_type(thread_pool& p) : pool_(p) {} + + // The underlying thread pool. + thread_pool& pool_; +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/thread_pool.hpp" +#if defined(ASIO_HEADER_ONLY) +# include "asio/impl/thread_pool.ipp" +#endif // defined(ASIO_HEADER_ONLY) + +#endif // ASIO_THREAD_POOL_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/time_traits.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/time_traits.hpp new file mode 100644 index 00000000..8e475119 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/time_traits.hpp @@ -0,0 +1,86 @@ +// +// time_traits.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TIME_TRAITS_HPP +#define ASIO_TIME_TRAITS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/socket_types.hpp" // Must come before posix_time. + +#if defined(ASIO_HAS_BOOST_DATE_TIME) \ + || defined(GENERATING_DOCUMENTATION) + +#include + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Time traits suitable for use with the deadline timer. +template +struct time_traits; + +/// Time traits specialised for posix_time. +template <> +struct time_traits +{ + /// The time type. + typedef boost::posix_time::ptime time_type; + + /// The duration type. + typedef boost::posix_time::time_duration duration_type; + + /// Get the current time. + static time_type now() + { +#if defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) + return boost::posix_time::microsec_clock::universal_time(); +#else // defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) + return boost::posix_time::second_clock::universal_time(); +#endif // defined(BOOST_DATE_TIME_HAS_HIGH_PRECISION_CLOCK) + } + + /// Add a duration to a time. + static time_type add(const time_type& t, const duration_type& d) + { + return t + d; + } + + /// Subtract one time from another. + static duration_type subtract(const time_type& t1, const time_type& t2) + { + return t1 - t2; + } + + /// Test whether one time is less than another. + static bool less_than(const time_type& t1, const time_type& t2) + { + return t1 < t2; + } + + /// Convert to POSIX duration type. + static boost::posix_time::time_duration to_posix_duration( + const duration_type& d) + { + return d; + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_TIME_TRAITS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/buffer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/buffer.hpp new file mode 100644 index 00000000..465897f7 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/buffer.hpp @@ -0,0 +1,24 @@ +// +// ts/buffer.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_BUFFER_HPP +#define ASIO_TS_BUFFER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/buffer.hpp" +#include "asio/completion_condition.hpp" +#include "asio/read.hpp" +#include "asio/write.hpp" +#include "asio/read_until.hpp" + +#endif // ASIO_TS_BUFFER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/executor.hpp new file mode 100644 index 00000000..cb4fc715 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/executor.hpp @@ -0,0 +1,34 @@ +// +// ts/executor.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_EXECUTOR_HPP +#define ASIO_TS_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/async_result.hpp" +#include "asio/associated_allocator.hpp" +#include "asio/execution_context.hpp" +#include "asio/is_executor.hpp" +#include "asio/associated_executor.hpp" +#include "asio/bind_executor.hpp" +#include "asio/executor_work_guard.hpp" +#include "asio/system_executor.hpp" +#include "asio/executor.hpp" +#include "asio/dispatch.hpp" +#include "asio/post.hpp" +#include "asio/defer.hpp" +#include "asio/strand.hpp" +#include "asio/packaged_task.hpp" +#include "asio/use_future.hpp" + +#endif // ASIO_TS_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/internet.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/internet.hpp new file mode 100644 index 00000000..5b9e231c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/internet.hpp @@ -0,0 +1,40 @@ +// +// ts/internet.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_INTERNET_HPP +#define ASIO_TS_INTERNET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/ip/address.hpp" +#include "asio/ip/address_v4.hpp" +#include "asio/ip/address_v4_iterator.hpp" +#include "asio/ip/address_v4_range.hpp" +#include "asio/ip/address_v6.hpp" +#include "asio/ip/address_v6_iterator.hpp" +#include "asio/ip/address_v6_range.hpp" +#include "asio/ip/bad_address_cast.hpp" +#include "asio/ip/basic_endpoint.hpp" +#include "asio/ip/basic_resolver_query.hpp" +#include "asio/ip/basic_resolver_entry.hpp" +#include "asio/ip/basic_resolver_iterator.hpp" +#include "asio/ip/basic_resolver.hpp" +#include "asio/ip/host_name.hpp" +#include "asio/ip/network_v4.hpp" +#include "asio/ip/network_v6.hpp" +#include "asio/ip/tcp.hpp" +#include "asio/ip/udp.hpp" +#include "asio/ip/v6_only.hpp" +#include "asio/ip/unicast.hpp" +#include "asio/ip/multicast.hpp" + +#endif // ASIO_TS_INTERNET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/io_context.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/io_context.hpp new file mode 100644 index 00000000..f293b63e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/io_context.hpp @@ -0,0 +1,20 @@ +// +// ts/io_context.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_IO_CONTEXT_HPP +#define ASIO_TS_IO_CONTEXT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/io_context.hpp" + +#endif // ASIO_TS_IO_CONTEXT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/net.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/net.hpp new file mode 100644 index 00000000..1d0237bb --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/net.hpp @@ -0,0 +1,26 @@ +// +// ts/net.hpp +// ~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_NET_HPP +#define ASIO_TS_NET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/ts/netfwd.hpp" +#include "asio/ts/executor.hpp" +#include "asio/ts/io_context.hpp" +#include "asio/ts/timer.hpp" +#include "asio/ts/buffer.hpp" +#include "asio/ts/socket.hpp" +#include "asio/ts/internet.hpp" + +#endif // ASIO_TS_NET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/netfwd.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/netfwd.hpp new file mode 100644 index 00000000..b7482acd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/netfwd.hpp @@ -0,0 +1,203 @@ +// +// ts/netfwd.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_NETFWD_HPP +#define ASIO_TS_NETFWD_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CHRONO) +# include "asio/detail/chrono.hpp" +#endif // defined(ASIO_HAS_CHRONO) + +#if defined(ASIO_HAS_BOOST_DATE_TIME) +# include "asio/detail/date_time_fwd.hpp" +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + +#if !defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +class execution_context; + +template +class executor_binder; + +template +class executor_work_guard; + +class system_executor; + +class executor; + +template +class strand; + +class io_context; + +template +struct wait_traits; + +#if defined(ASIO_HAS_BOOST_DATE_TIME) + +template +struct time_traits; + +#endif // defined(ASIO_HAS_BOOST_DATE_TIME) + +#if !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) +#define ASIO_BASIC_WAITABLE_TIMER_FWD_DECL + +template , + typename Executor = executor> +class basic_waitable_timer; + +#endif // !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) + +#if defined(ASIO_HAS_CHRONO) + +typedef basic_waitable_timer system_timer; + +typedef basic_waitable_timer steady_timer; + +typedef basic_waitable_timer + high_resolution_timer; + +#endif // defined(ASIO_HAS_CHRONO) + +#if !defined(ASIO_BASIC_SOCKET_FWD_DECL) +#define ASIO_BASIC_SOCKET_FWD_DECL + +template +class basic_socket; + +#endif // !defined(ASIO_BASIC_SOCKET_FWD_DECL) + +#if !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) +#define ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL + +template +class basic_datagram_socket; + +#endif // !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) + +#if !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) +#define ASIO_BASIC_STREAM_SOCKET_FWD_DECL + +// Forward declaration with defaulted arguments. +template +class basic_stream_socket; + +#endif // !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) + +#if !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) +#define ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL + +template +class basic_socket_acceptor; + +#endif // !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) + +#if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) +#define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL + +// Forward declaration with defaulted arguments. +template > +#else + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits > +#endif +class basic_socket_streambuf; + +#endif // !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) + +#if !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) +#define ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL + +// Forward declaration with defaulted arguments. +template > +#else + typename Clock = chrono::steady_clock, + typename WaitTraits = wait_traits > +#endif +class basic_socket_iostream; + +#endif // !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) + +namespace ip { + +class address; + +class address_v4; + +class address_v6; + +template +class basic_address_iterator; + +typedef basic_address_iterator address_v4_iterator; + +typedef basic_address_iterator address_v6_iterator; + +template +class basic_address_range; + +typedef basic_address_range address_v4_range; + +typedef basic_address_range address_v6_range; + +class network_v4; + +class network_v6; + +template +class basic_endpoint; + +template +class basic_resolver_entry; + +template +class basic_resolver_results; + +#if !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) +#define ASIO_IP_BASIC_RESOLVER_FWD_DECL + +template +class basic_resolver; + +#endif // !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) + +class tcp; + +class udp; + +} // namespace ip +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // !defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_TS_NETFWD_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/socket.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/socket.hpp new file mode 100644 index 00000000..5084eb56 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/socket.hpp @@ -0,0 +1,27 @@ +// +// ts/socket.hpp +// ~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_SOCKET_HPP +#define ASIO_TS_SOCKET_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/socket_base.hpp" +#include "asio/basic_socket.hpp" +#include "asio/basic_datagram_socket.hpp" +#include "asio/basic_stream_socket.hpp" +#include "asio/basic_socket_acceptor.hpp" +#include "asio/basic_socket_streambuf.hpp" +#include "asio/basic_socket_iostream.hpp" +#include "asio/connect.hpp" + +#endif // ASIO_TS_SOCKET_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/timer.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/timer.hpp new file mode 100644 index 00000000..4567dbf3 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/ts/timer.hpp @@ -0,0 +1,26 @@ +// +// ts/timer.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_TS_TIMER_HPP +#define ASIO_TS_TIMER_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/chrono.hpp" + +#include "asio/wait_traits.hpp" +#include "asio/basic_waitable_timer.hpp" +#include "asio/system_timer.hpp" +#include "asio/steady_timer.hpp" +#include "asio/high_resolution_timer.hpp" + +#endif // ASIO_TS_TIMER_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/unyield.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/unyield.hpp new file mode 100644 index 00000000..c6874d5c --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/unyield.hpp @@ -0,0 +1,21 @@ +// +// unyield.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifdef reenter +# undef reenter +#endif + +#ifdef yield +# undef yield +#endif + +#ifdef fork +# undef fork +#endif diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_awaitable.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_awaitable.hpp new file mode 100644 index 00000000..c76913cd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_awaitable.hpp @@ -0,0 +1,109 @@ +// +// use_awaitable.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_USE_AWAITABLE_HPP +#define ASIO_USE_AWAITABLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#include "asio/awaitable.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// A completion token that represents the currently executing coroutine. +/** + * The @c use_awaitable_t class, with its value @c use_awaitable, is used to + * represent the currently executing coroutine. This completion token may be + * passed as a handler to an asynchronous operation. For example: + * + * @code awaitable my_coroutine() + * { + * std::size_t n = co_await my_socket.async_read_some(buffer, use_awaitable); + * ... + * } @endcode + * + * When used with co_await, the initiating function (@c async_read_some in the + * above example) suspends the current coroutine. The coroutine is resumed when + * the asynchronous operation completes, and the result of the operation is + * returned. + */ +template +struct use_awaitable_t +{ + /// Default constructor. + ASIO_CONSTEXPR use_awaitable_t() + { + } + + /// Adapts an executor to add the @c use_awaitable_t completion token as the + /// default. + template + struct executor_with_default : InnerExecutor + { + /// Specify @c use_awaitable_t as the default completion token type. + typedef use_awaitable_t default_completion_token_type; + + /// Construct the adapted executor from the inner executor type. + executor_with_default(const InnerExecutor& ex) ASIO_NOEXCEPT + : InnerExecutor(ex) + { + } + }; + + /// Type alias to adapt an I/O object to use @c use_awaitable_t as its + /// default completion token type. +#if defined(ASIO_HAS_ALIAS_TEMPLATES) \ + || defined(GENERATING_DOCUMENTATION) + template + using as_default_on_t = typename T::template rebind_executor< + executor_with_default >::other; +#endif // defined(ASIO_HAS_ALIAS_TEMPLATES) + // || defined(GENERATING_DOCUMENTATION) + + /// Function helper to adapt an I/O object to use @c use_awaitable_t as its + /// default completion token type. + template + static typename T::template rebind_executor< + executor_with_default + >::other + as_default_on(ASIO_MOVE_ARG(T) object) + { + return typename as_default_on_t::type>::type( + ASIO_MOVE_CAST(T)(object)); + } +}; + +/// A completion token object that represents the currently executing coroutine. +/** + * See the documentation for asio::use_awaitable_t for a usage example. + */ +#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) +constexpr use_awaitable_t<> use_awaitable; +#elif defined(ASIO_MSVC) +__declspec(selectany) use_awaitable_t<> use_awaitable; +#endif + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/use_awaitable.hpp" + +#endif // defined(ASIO_HAS_CO_AWAIT) || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_USE_AWAITABLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_future.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_future.hpp new file mode 100644 index 00000000..79d9c566 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/use_future.hpp @@ -0,0 +1,160 @@ +// +// use_future.hpp +// ~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_USE_FUTURE_HPP +#define ASIO_USE_FUTURE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/future.hpp" + +#if defined(ASIO_HAS_STD_FUTURE_CLASS) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace detail { + +template +class packaged_token; + +template +class packaged_handler; + +} // namespace detail + +/// Class used to specify that an asynchronous operation should return a future. +/** + * The use_future_t class is used to indicate that an asynchronous operation + * should return a std::future object. A use_future_t object may be passed as a + * handler to an asynchronous operation, typically using the special value @c + * asio::use_future. For example: + * + * @code std::future my_future + * = my_socket.async_read_some(my_buffer, asio::use_future); @endcode + * + * The initiating function (async_read_some in the above example) returns a + * future that will receive the result of the operation. If the operation + * completes with an error_code indicating failure, it is converted into a + * system_error and passed back to the caller via the future. + */ +template > +class use_future_t +{ +public: + /// The allocator type. The allocator is used when constructing the + /// @c std::promise object for a given asynchronous operation. + typedef Allocator allocator_type; + + /// Construct using default-constructed allocator. + ASIO_CONSTEXPR use_future_t() + { + } + + /// Construct using specified allocator. + explicit use_future_t(const Allocator& allocator) + : allocator_(allocator) + { + } + +#if !defined(ASIO_NO_DEPRECATED) + /// (Deprecated: Use rebind().) Specify an alternate allocator. + template + use_future_t operator[](const OtherAllocator& allocator) const + { + return use_future_t(allocator); + } +#endif // !defined(ASIO_NO_DEPRECATED) + + /// Specify an alternate allocator. + template + use_future_t rebind(const OtherAllocator& allocator) const + { + return use_future_t(allocator); + } + + /// Obtain allocator. + allocator_type get_allocator() const + { + return allocator_; + } + + /// Wrap a function object in a packaged task. + /** + * The @c package function is used to adapt a function object as a packaged + * task. When this adapter is passed as a completion token to an asynchronous + * operation, the result of the function object is retuned via a std::future. + * + * @par Example + * + * @code std::future fut = + * my_socket.async_read_some(buffer, + * use_future([](asio::error_code ec, std::size_t n) + * { + * return ec ? 0 : n; + * })); + * ... + * std::size_t n = fut.get(); @endcode + */ + template +#if defined(GENERATING_DOCUMENTATION) + unspecified +#else // defined(GENERATING_DOCUMENTATION) + detail::packaged_token::type, Allocator> +#endif // defined(GENERATING_DOCUMENTATION) + operator()(ASIO_MOVE_ARG(Function) f) const; + +private: + // Helper type to ensure that use_future can be constexpr default-constructed + // even when std::allocator can't be. + struct std_allocator_void + { + ASIO_CONSTEXPR std_allocator_void() + { + } + + operator std::allocator() const + { + return std::allocator(); + } + }; + + typename conditional< + is_same, Allocator>::value, + std_allocator_void, Allocator>::type allocator_; +}; + +/// A special value, similar to std::nothrow. +/** + * See the documentation for asio::use_future_t for a usage example. + */ +#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) +constexpr use_future_t<> use_future; +#elif defined(ASIO_MSVC) +__declspec(selectany) use_future_t<> use_future; +#endif + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/use_future.hpp" + +#endif // defined(ASIO_HAS_STD_FUTURE_CLASS) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_USE_FUTURE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/uses_executor.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/uses_executor.hpp new file mode 100644 index 00000000..9a23a1a4 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/uses_executor.hpp @@ -0,0 +1,71 @@ +// +// uses_executor.hpp +// ~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_USES_EXECUTOR_HPP +#define ASIO_USES_EXECUTOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/detail/type_traits.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// A special type, similar to std::nothrow_t, used to disambiguate +/// constructors that accept executor arguments. +/** + * The executor_arg_t struct is an empty structure type used as a unique type + * to disambiguate constructor and function overloading. Specifically, some + * types have constructors with executor_arg_t as the first argument, + * immediately followed by an argument of a type that satisfies the Executor + * type requirements. + */ +struct executor_arg_t +{ + /// Constructor. + ASIO_CONSTEXPR executor_arg_t() ASIO_NOEXCEPT + { + } +}; + +/// A special value, similar to std::nothrow, used to disambiguate constructors +/// that accept executor arguments. +/** + * See asio::executor_arg_t and asio::uses_executor + * for more information. + */ +#if defined(ASIO_HAS_CONSTEXPR) || defined(GENERATING_DOCUMENTATION) +constexpr executor_arg_t executor_arg; +#elif defined(ASIO_MSVC) +__declspec(selectany) executor_arg_t executor_arg; +#endif + +/// The uses_executor trait detects whether a type T has an associated executor +/// that is convertible from type Executor. +/** + * Meets the BinaryTypeTrait requirements. The Asio library provides a + * definition that is derived from false_type. A program may specialize this + * template to derive from true_type for a user-defined type T that can be + * constructed with an executor, where the first argument of a constructor has + * type executor_arg_t and the second argument is convertible from type + * Executor. + */ +template +struct uses_executor : false_type {}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_USES_EXECUTOR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/version.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/version.hpp new file mode 100644 index 00000000..f7c25309 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/version.hpp @@ -0,0 +1,23 @@ +// +// version.hpp +// ~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_VERSION_HPP +#define ASIO_VERSION_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +// ASIO_VERSION % 100 is the sub-minor version +// ASIO_VERSION / 100 % 1000 is the minor version +// ASIO_VERSION / 100000 is the major version +#define ASIO_VERSION 101401 // 1.14.1 + +#endif // ASIO_VERSION_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/wait_traits.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/wait_traits.hpp new file mode 100644 index 00000000..5e64abfa --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/wait_traits.hpp @@ -0,0 +1,56 @@ +// +// wait_traits.hpp +// ~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WAIT_TRAITS_HPP +#define ASIO_WAIT_TRAITS_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/// Wait traits suitable for use with the basic_waitable_timer class template. +template +struct wait_traits +{ + /// Convert a clock duration into a duration used for waiting. + /** + * @returns @c d. + */ + static typename Clock::duration to_wait_duration( + const typename Clock::duration& d) + { + return d; + } + + /// Convert a clock duration into a duration used for waiting. + /** + * @returns @c d. + */ + static typename Clock::duration to_wait_duration( + const typename Clock::time_point& t) + { + typename Clock::time_point now = Clock::now(); + if (now + (Clock::duration::max)() < t) + return (Clock::duration::max)(); + if (now + (Clock::duration::min)() > t) + return (Clock::duration::min)(); + return t - now; + } +}; + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // ASIO_WAIT_TRAITS_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_object_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_object_handle.hpp new file mode 100644 index 00000000..26a03e92 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_object_handle.hpp @@ -0,0 +1,435 @@ +// +// windows/basic_object_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2011 Boris Schaeling (boris@highscore.de) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP +#define ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/async_result.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/win_object_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides object-oriented handle functionality. +/** + * The windows::basic_object_handle class provides asynchronous and blocking + * object-oriented handle functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_object_handle +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the handle type to another executor. + template + struct rebind_executor + { + /// The handle type when rebound to the specified executor. + typedef basic_object_handle other; + }; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef asio::detail::win_object_handle_service::native_handle_type + native_handle_type; +#endif + + /// An object handle is always the lowest layer. + typedef basic_object_handle lowest_layer_type; + + /// Construct an object handle without opening it. + /** + * This constructor creates an object handle without opening it. + * + * @param ex The I/O executor that the object handle will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * object handle. + */ + explicit basic_object_handle(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct an object handle without opening it. + /** + * This constructor creates an object handle without opening it. + * + * @param context An execution context which provides the I/O executor that + * the object handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the object handle. + */ + template + explicit basic_object_handle(ExecutionContext& context, + typename enable_if< + is_convertible::value, + basic_object_handle + >::type* = 0) + : impl_(context) + { + } + + /// Construct an object handle on an existing native handle. + /** + * This constructor creates an object handle object to hold an existing native + * handle. + * + * @param ex The I/O executor that the object handle will use, by default, to + * dispatch handlers for any asynchronous operations performed on the + * object handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_object_handle(const executor_type& ex, + const native_handle_type& native_handle) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct an object handle on an existing native handle. + /** + * This constructor creates an object handle object to hold an existing native + * handle. + * + * @param context An execution context which provides the I/O executor that + * the object handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the object handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_object_handle(ExecutionContext& context, + const native_handle_type& native_handle, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct an object handle from another. + /** + * This constructor moves an object handle from one object to another. + * + * @param other The other object handle object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_object_handle(const executor_type&) + * constructor. + */ + basic_object_handle(basic_object_handle&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign an object handle from another. + /** + * This assignment operator moves an object handle from one object to another. + * + * @param other The other object handle object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_object_handle(const executor_type&) + * constructor. + */ + basic_object_handle& operator=(basic_object_handle&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since an object handle cannot contain any further layers, it simply + * returns a reference to itself. + * + * @return A reference to the lowest layer in the stack of layers. Ownership + * is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return *this; + } + + /// Get a const reference to the lowest layer. + /** + * This function returns a const reference to the lowest layer in a stack of + * layers. Since an object handle cannot contain any further layers, it simply + * returns a reference to itself. + * + * @return A const reference to the lowest layer in the stack of layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return *this; + } + + /// Assign an existing native handle to the handle. + /* + * This function opens the handle to hold an existing native handle. + * + * @param handle A native handle. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const native_handle_type& handle) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), handle, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assign an existing native handle to the handle. + /* + * This function opens the handle to hold an existing native handle. + * + * @param handle A native handle. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const native_handle_type& handle, + asio::error_code& ec) + { + impl_.get_service().assign(impl_.get_implementation(), handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Close the handle. + /** + * This function is used to close the handle. Any asynchronous read or write + * operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the handle. + /** + * This function is used to close the handle. Any asynchronous read or write + * operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle representation. + /** + * This function may be used to obtain the underlying representation of the + * handle. This is intended to allow access to native handle functionality + * that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the handle. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the handle. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Perform a blocking wait on the object handle. + /** + * This function is used to wait for the object handle to be set to the + * signalled state. This function blocks and does not return until the object + * handle has been set to the signalled state. + * + * @throws asio::system_error Thrown on failure. + */ + void wait() + { + asio::error_code ec; + impl_.get_service().wait(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "wait"); + } + + /// Perform a blocking wait on the object handle. + /** + * This function is used to wait for the object handle to be set to the + * signalled state. This function blocks and does not return until the object + * handle has been set to the signalled state. + * + * @param ec Set to indicate what error occurred, if any. + */ + void wait(asio::error_code& ec) + { + impl_.get_service().wait(impl_.get_implementation(), ec); + } + + /// Start an asynchronous wait on the object handle. + /** + * This function is be used to initiate an asynchronous wait against the + * object handle. It always returns immediately. + * + * @param handler The handler to be called when the object handle is set to + * the signalled state. Copies will be made of the handler as required. The + * function signature of the handler must be: + * @code void handler( + * const asio::error_code& error // Result of operation. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ + template < + ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) + WaitHandler ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)> + ASIO_INITFN_AUTO_RESULT_TYPE(WaitHandler, + void (asio::error_code)) + async_wait( + ASIO_MOVE_ARG(WaitHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_wait(this), handler); + } + +private: + // Disallow copying and assignment. + basic_object_handle(const basic_object_handle&) ASIO_DELETED; + basic_object_handle& operator=(const basic_object_handle&) ASIO_DELETED; + + class initiate_async_wait + { + public: + typedef Executor executor_type; + + explicit initiate_async_wait(basic_object_handle* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WaitHandler) handler) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WaitHandler. + ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_wait( + self_->impl_.get_implementation(), handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_object_handle* self_; + }; + + asio::detail::io_object_impl< + asio::detail::win_object_handle_service, Executor> impl_; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_overlapped_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_overlapped_handle.hpp new file mode 100644 index 00000000..69966e97 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_overlapped_handle.hpp @@ -0,0 +1,361 @@ +// +// windows/basic_overlapped_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP +#define ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include +#include "asio/async_result.hpp" +#include "asio/detail/io_object_impl.hpp" +#include "asio/detail/throw_error.hpp" +#include "asio/detail/win_iocp_handle_service.hpp" +#include "asio/error.hpp" +#include "asio/execution_context.hpp" +#include "asio/executor.hpp" + +#if defined(ASIO_HAS_MOVE) +# include +#endif // defined(ASIO_HAS_MOVE) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides Windows handle functionality for objects that support +/// overlapped I/O. +/** + * The windows::overlapped_handle class provides the ability to wrap a Windows + * handle. The underlying object referred to by the handle must support + * overlapped I/O. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_overlapped_handle +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the handle type to another executor. + template + struct rebind_executor + { + /// The handle type when rebound to the specified executor. + typedef basic_overlapped_handle other; + }; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef asio::detail::win_iocp_handle_service::native_handle_type + native_handle_type; +#endif + + /// An overlapped_handle is always the lowest layer. + typedef basic_overlapped_handle lowest_layer_type; + + /// Construct an overlapped handle without opening it. + /** + * This constructor creates an overlapped handle without opening it. + * + * @param ex The I/O executor that the overlapped handle will use, by default, + * to dispatch handlers for any asynchronous operations performed on the + * overlapped handle. + */ + explicit basic_overlapped_handle(const executor_type& ex) + : impl_(ex) + { + } + + /// Construct an overlapped handle without opening it. + /** + * This constructor creates an overlapped handle without opening it. + * + * @param context An execution context which provides the I/O executor that + * the overlapped handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the overlapped handle. + */ + template + explicit basic_overlapped_handle(ExecutionContext& context, + typename enable_if< + is_convertible::value, + basic_overlapped_handle + >::type* = 0) + : impl_(context) + { + } + + /// Construct an overlapped handle on an existing native handle. + /** + * This constructor creates an overlapped handle object to hold an existing + * native handle. + * + * @param ex The I/O executor that the overlapped handle will use, by default, + * to dispatch handlers for any asynchronous operations performed on the + * overlapped handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_overlapped_handle(const executor_type& ex, + const native_handle_type& native_handle) + : impl_(ex) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Construct an overlapped handle on an existing native handle. + /** + * This constructor creates an overlapped handle object to hold an existing + * native handle. + * + * @param context An execution context which provides the I/O executor that + * the overlapped handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the overlapped handle. + * + * @param native_handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_overlapped_handle(ExecutionContext& context, + const native_handle_type& native_handle, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); + asio::detail::throw_error(ec, "assign"); + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct an overlapped handle from another. + /** + * This constructor moves a handle from one object to another. + * + * @param other The other overlapped handle object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c overlapped_handle(const executor_type&) + * constructor. + */ + basic_overlapped_handle(basic_overlapped_handle&& other) + : impl_(std::move(other.impl_)) + { + } + + /// Move-assign an overlapped handle from another. + /** + * This assignment operator moves a handle from one object to another. + * + * @param other The other overlapped handle object from which the move will + * occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c overlapped_handle(const executor_type&) + * constructor. + */ + basic_overlapped_handle& operator=(basic_overlapped_handle&& other) + { + impl_ = std::move(other.impl_); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Get the executor associated with the object. + executor_type get_executor() ASIO_NOEXCEPT + { + return impl_.get_executor(); + } + + /// Get a reference to the lowest layer. + /** + * This function returns a reference to the lowest layer in a stack of + * layers. Since an overlapped_handle cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A reference to the lowest layer in the stack of layers. Ownership + * is not transferred to the caller. + */ + lowest_layer_type& lowest_layer() + { + return *this; + } + + /// Get a const reference to the lowest layer. + /** + * This function returns a const reference to the lowest layer in a stack of + * layers. Since an overlapped_handle cannot contain any further layers, it + * simply returns a reference to itself. + * + * @return A const reference to the lowest layer in the stack of layers. + * Ownership is not transferred to the caller. + */ + const lowest_layer_type& lowest_layer() const + { + return *this; + } + + /// Assign an existing native handle to the handle. + /* + * This function opens the handle to hold an existing native handle. + * + * @param handle A native handle. + * + * @throws asio::system_error Thrown on failure. + */ + void assign(const native_handle_type& handle) + { + asio::error_code ec; + impl_.get_service().assign(impl_.get_implementation(), handle, ec); + asio::detail::throw_error(ec, "assign"); + } + + /// Assign an existing native handle to the handle. + /* + * This function opens the handle to hold an existing native handle. + * + * @param handle A native handle. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID assign(const native_handle_type& handle, + asio::error_code& ec) + { + impl_.get_service().assign(impl_.get_implementation(), handle, ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Determine whether the handle is open. + bool is_open() const + { + return impl_.get_service().is_open(impl_.get_implementation()); + } + + /// Close the handle. + /** + * This function is used to close the handle. Any asynchronous read or write + * operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void close() + { + asio::error_code ec; + impl_.get_service().close(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "close"); + } + + /// Close the handle. + /** + * This function is used to close the handle. Any asynchronous read or write + * operations will be cancelled immediately, and will complete with the + * asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID close(asio::error_code& ec) + { + impl_.get_service().close(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + + /// Get the native handle representation. + /** + * This function may be used to obtain the underlying representation of the + * handle. This is intended to allow access to native handle functionality + * that is not otherwise provided. + */ + native_handle_type native_handle() + { + return impl_.get_service().native_handle(impl_.get_implementation()); + } + + /// Cancel all asynchronous operations associated with the handle. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @throws asio::system_error Thrown on failure. + */ + void cancel() + { + asio::error_code ec; + impl_.get_service().cancel(impl_.get_implementation(), ec); + asio::detail::throw_error(ec, "cancel"); + } + + /// Cancel all asynchronous operations associated with the handle. + /** + * This function causes all outstanding asynchronous read or write operations + * to finish immediately, and the handlers for cancelled operations will be + * passed the asio::error::operation_aborted error. + * + * @param ec Set to indicate what error occurred, if any. + */ + ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) + { + impl_.get_service().cancel(impl_.get_implementation(), ec); + ASIO_SYNC_OP_VOID_RETURN(ec); + } + +protected: + /// Protected destructor to prevent deletion through this type. + /** + * This function destroys the handle, cancelling any outstanding asynchronous + * wait operations associated with the handle as if by calling @c cancel. + */ + ~basic_overlapped_handle() + { + } + + asio::detail::io_object_impl< + asio::detail::win_iocp_handle_service, Executor> impl_; + +private: + // Disallow copying and assignment. + basic_overlapped_handle(const basic_overlapped_handle&) ASIO_DELETED; + basic_overlapped_handle& operator=( + const basic_overlapped_handle&) ASIO_DELETED; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_random_access_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_random_access_handle.hpp new file mode 100644 index 00000000..ca2d7414 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_random_access_handle.hpp @@ -0,0 +1,490 @@ +// +// windows/basic_random_access_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP +#define ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/windows/basic_overlapped_handle.hpp" + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides random-access handle functionality. +/** + * The windows::basic_random_access_handle class provides asynchronous and + * blocking random-access handle functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +template +class basic_random_access_handle + : public basic_overlapped_handle +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the handle type to another executor. + template + struct rebind_executor + { + /// The handle type when rebound to the specified executor. + typedef basic_random_access_handle other; + }; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef asio::detail::win_iocp_handle_service::native_handle_type + native_handle_type; +#endif + + /// Construct a random-access handle without opening it. + /** + * This constructor creates a random-access handle without opening it. + * + * @param ex The I/O executor that the random-access handle will use, by + * default, to dispatch handlers for any asynchronous operations performed on + * the random-access handle. + */ + explicit basic_random_access_handle(const executor_type& ex) + : basic_overlapped_handle(ex) + { + } + + /// Construct a random-access handle without opening it. + /** + * This constructor creates a random-access handle without opening it. The + * handle needs to be opened or assigned before data can be sent or received + * on it. + * + * @param context An execution context which provides the I/O executor that + * the random-access handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the random-access handle. + */ + template + explicit basic_random_access_handle(ExecutionContext& context, + typename enable_if< + is_convertible::value, + basic_random_access_handle + >::type* = 0) + : basic_overlapped_handle(context) + { + } + + /// Construct a random-access handle on an existing native handle. + /** + * This constructor creates a random-access handle object to hold an existing + * native handle. + * + * @param ex The I/O executor that the random-access handle will use, by + * default, to dispatch handlers for any asynchronous operations performed on + * the random-access handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_random_access_handle(const executor_type& ex, + const native_handle_type& handle) + : basic_overlapped_handle(ex, handle) + { + } + + /// Construct a random-access handle on an existing native handle. + /** + * This constructor creates a random-access handle object to hold an existing + * native handle. + * + * @param context An execution context which provides the I/O executor that + * the random-access handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the random-access handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_random_access_handle(ExecutionContext& context, + const native_handle_type& handle, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_overlapped_handle(context, handle) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a random-access handle from another. + /** + * This constructor moves a random-access handle from one object to another. + * + * @param other The other random-access handle object from which the + * move will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_random_access_handle(const executor_type&) + * constructor. + */ + basic_random_access_handle(basic_random_access_handle&& other) + : basic_overlapped_handle(std::move(other)) + { + } + + /// Move-assign a random-access handle from another. + /** + * This assignment operator moves a random-access handle from one object to + * another. + * + * @param other The other random-access handle object from which the + * move will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_random_access_handle(const executor_type&) + * constructor. + */ + basic_random_access_handle& operator=(basic_random_access_handle&& other) + { + basic_overlapped_handle::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Write some data to the handle at the specified offset. + /** + * This function is used to write data to the random-access handle. The + * function call will block until one or more bytes of the data has been + * written successfully, or until an error occurs. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more data buffers to be written to the handle. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The write_some_at operation may not write all of the data. Consider + * using the @ref write_at function if you need to ensure that all data is + * written before the blocking operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * handle.write_some_at(42, asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t write_some_at(uint64_t offset, + const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().write_some_at( + this->impl_.get_implementation(), offset, buffers, ec); + asio::detail::throw_error(ec, "write_some_at"); + return s; + } + + /// Write some data to the handle at the specified offset. + /** + * This function is used to write data to the random-access handle. The + * function call will block until one or more bytes of the data has been + * written successfully, or until an error occurs. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more data buffers to be written to the handle. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write_at function if you need to ensure that + * all data is written before the blocking operation completes. + */ + template + std::size_t write_some_at(uint64_t offset, + const ConstBufferSequence& buffers, asio::error_code& ec) + { + return this->impl_.get_service().write_some_at( + this->impl_.get_implementation(), offset, buffers, ec); + } + + /// Start an asynchronous write at the specified offset. + /** + * This function is used to asynchronously write data to the random-access + * handle. The function call always returns immediately. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more data buffers to be written to the handle. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The write operation may not transmit all of the data to the peer. + * Consider using the @ref async_write_at function if you need to ensure that + * all data is written before the asynchronous operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * handle.async_write_some_at(42, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some_at(uint64_t offset, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_write_some_at(this), handler, offset, buffers); + } + + /// Read some data from the handle at the specified offset. + /** + * This function is used to read data from the random-access handle. The + * function call will block until one or more bytes of data has been read + * successfully, or until an error occurs. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read_at function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * handle.read_some_at(42, asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t read_some_at(uint64_t offset, + const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().read_some_at( + this->impl_.get_implementation(), offset, buffers, ec); + asio::detail::throw_error(ec, "read_some_at"); + return s; + } + + /// Read some data from the handle at the specified offset. + /** + * This function is used to read data from the random-access handle. The + * function call will block until one or more bytes of data has been read + * successfully, or until an error occurs. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read_at function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + */ + template + std::size_t read_some_at(uint64_t offset, + const MutableBufferSequence& buffers, asio::error_code& ec) + { + return this->impl_.get_service().read_some_at( + this->impl_.get_implementation(), offset, buffers, ec); + } + + /// Start an asynchronous read at the specified offset. + /** + * This function is used to asynchronously read data from the random-access + * handle. The function call always returns immediately. + * + * @param offset The offset at which the data will be read. + * + * @param buffers One or more buffers into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The read operation may not read all of the requested number of bytes. + * Consider using the @ref async_read_at function if you need to ensure that + * the requested amount of data is read before the asynchronous operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * handle.async_read_some_at(42, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some_at(uint64_t offset, + const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_read_some_at(this), handler, offset, buffers); + } + +private: + class initiate_async_write_some_at + { + public: + typedef Executor executor_type; + + explicit initiate_async_write_some_at(basic_random_access_handle* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + uint64_t offset, const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_write_some_at( + self_->impl_.get_implementation(), offset, buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_random_access_handle* self_; + }; + + class initiate_async_read_some_at + { + public: + typedef Executor executor_type; + + explicit initiate_async_read_some_at(basic_random_access_handle* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + uint64_t offset, const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_read_some_at( + self_->impl_.get_implementation(), offset, buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_random_access_handle* self_; + }; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_stream_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_stream_handle.hpp new file mode 100644 index 00000000..a335b5b2 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/basic_stream_handle.hpp @@ -0,0 +1,474 @@ +// +// windows/basic_stream_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP +#define ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include "asio/windows/basic_overlapped_handle.hpp" + +#if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Provides stream-oriented handle functionality. +/** + * The windows::basic_stream_handle class provides asynchronous and blocking + * stream-oriented handle functionality. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + * + * @par Concepts: + * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. + */ +template +class basic_stream_handle + : public basic_overlapped_handle +{ +public: + /// The type of the executor associated with the object. + typedef Executor executor_type; + + /// Rebinds the handle type to another executor. + template + struct rebind_executor + { + /// The handle type when rebound to the specified executor. + typedef basic_stream_handle other; + }; + + /// The native representation of a handle. +#if defined(GENERATING_DOCUMENTATION) + typedef implementation_defined native_handle_type; +#else + typedef asio::detail::win_iocp_handle_service::native_handle_type + native_handle_type; +#endif + + /// Construct a stream handle without opening it. + /** + * This constructor creates a stream handle without opening it. + * + * @param ex The I/O executor that the stream handle will use, by default, to + * dispatch handlers for any asynchronous operations performed on the stream + * handle. + */ + explicit basic_stream_handle(const executor_type& ex) + : basic_overlapped_handle(ex) + { + } + + /// Construct a stream handle without opening it. + /** + * This constructor creates a stream handle without opening it. The handle + * needs to be opened or assigned before data can be sent or received on it. + * + * @param context An execution context which provides the I/O executor that + * the stream handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the stream handle. + */ + template + explicit basic_stream_handle(ExecutionContext& context, + typename enable_if< + is_convertible::value, + basic_stream_handle + >::type* = 0) + : basic_overlapped_handle(context) + { + } + + /// Construct a stream handle on an existing native handle. + /** + * This constructor creates a stream handle object to hold an existing native + * handle. + * + * @param ex The I/O executor that the stream handle will use, by default, to + * dispatch handlers for any asynchronous operations performed on the stream + * handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + basic_stream_handle(const executor_type& ex, const native_handle_type& handle) + : basic_overlapped_handle(ex, handle) + { + } + + /// Construct a stream handle on an existing native handle. + /** + * This constructor creates a stream handle object to hold an existing native + * handle. + * + * @param context An execution context which provides the I/O executor that + * the stream handle will use, by default, to dispatch handlers for any + * asynchronous operations performed on the stream handle. + * + * @param handle The new underlying handle implementation. + * + * @throws asio::system_error Thrown on failure. + */ + template + basic_stream_handle(ExecutionContext& context, + const native_handle_type& handle, + typename enable_if< + is_convertible::value + >::type* = 0) + : basic_overlapped_handle(context, handle) + { + } + +#if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + /// Move-construct a stream handle from another. + /** + * This constructor moves a stream handle from one object to another. + * + * @param other The other stream handle object from which the move + * will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_handle(const executor_type&) + * constructor. + */ + basic_stream_handle(basic_stream_handle&& other) + : basic_overlapped_handle(std::move(other)) + { + } + + /// Move-assign a stream handle from another. + /** + * This assignment operator moves a stream handle from one object to + * another. + * + * @param other The other stream handle object from which the move will occur. + * + * @note Following the move, the moved-from object is in the same state as if + * constructed using the @c basic_stream_handle(const executor_type&) + * constructor. + */ + basic_stream_handle& operator=(basic_stream_handle&& other) + { + basic_overlapped_handle::operator=(std::move(other)); + return *this; + } +#endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) + + /// Write some data to the handle. + /** + * This function is used to write data to the stream handle. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the handle. + * + * @returns The number of bytes written. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * handle.write_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().write_some( + this->impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "write_some"); + return s; + } + + /// Write some data to the handle. + /** + * This function is used to write data to the stream handle. The function call + * will block until one or more bytes of the data has been written + * successfully, or until an error occurs. + * + * @param buffers One or more data buffers to be written to the handle. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. Returns 0 if an error occurred. + * + * @note The write_some operation may not transmit all of the data to the + * peer. Consider using the @ref write function if you need to ensure that + * all data is written before the blocking operation completes. + */ + template + std::size_t write_some(const ConstBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().write_some( + this->impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous write. + /** + * This function is used to asynchronously write data to the stream handle. + * The function call always returns immediately. + * + * @param buffers One or more data buffers to be written to the handle. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes written. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The write operation may not transmit all of the data to the peer. + * Consider using the @ref async_write function if you need to ensure that all + * data is written before the asynchronous operation completes. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * handle.async_write_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) + async_write_some(const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_write_some(this), handler, buffers); + } + + /// Read some data from the handle. + /** + * This function is used to read data from the stream handle. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @returns The number of bytes read. + * + * @throws asio::system_error Thrown on failure. An error code of + * asio::error::eof indicates that the connection was closed by the + * peer. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * handle.read_some(asio::buffer(data, size)); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers) + { + asio::error_code ec; + std::size_t s = this->impl_.get_service().read_some( + this->impl_.get_implementation(), buffers, ec); + asio::detail::throw_error(ec, "read_some"); + return s; + } + + /// Read some data from the handle. + /** + * This function is used to read data from the stream handle. The function + * call will block until one or more bytes of data has been read successfully, + * or until an error occurs. + * + * @param buffers One or more buffers into which the data will be read. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes read. Returns 0 if an error occurred. + * + * @note The read_some operation may not read all of the requested number of + * bytes. Consider using the @ref read function if you need to ensure that + * the requested amount of data is read before the blocking operation + * completes. + */ + template + std::size_t read_some(const MutableBufferSequence& buffers, + asio::error_code& ec) + { + return this->impl_.get_service().read_some( + this->impl_.get_implementation(), buffers, ec); + } + + /// Start an asynchronous read. + /** + * This function is used to asynchronously read data from the stream handle. + * The function call always returns immediately. + * + * @param buffers One or more buffers into which the data will be read. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the read operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * std::size_t bytes_transferred // Number of bytes read. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @note The read operation may not read all of the requested number of bytes. + * Consider using the @ref async_read function if you need to ensure that the + * requested amount of data is read before the asynchronous operation + * completes. + * + * @par Example + * To read into a single data buffer use the @ref buffer function as follows: + * @code + * handle.async_read_some(asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on reading into multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ + template + ASIO_INITFN_AUTO_RESULT_TYPE(ReadHandler, + void (asio::error_code, std::size_t)) + async_read_some(const MutableBufferSequence& buffers, + ASIO_MOVE_ARG(ReadHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN(executor_type)) + { + return async_initiate( + initiate_async_read_some(this), handler, buffers); + } + +private: + class initiate_async_write_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_write_some(basic_stream_handle* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(WriteHandler) handler, + const ConstBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a WriteHandler. + ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_write_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_handle* self_; + }; + + class initiate_async_read_some + { + public: + typedef Executor executor_type; + + explicit initiate_async_read_some(basic_stream_handle* self) + : self_(self) + { + } + + executor_type get_executor() const ASIO_NOEXCEPT + { + return self_->get_executor(); + } + + template + void operator()(ASIO_MOVE_ARG(ReadHandler) handler, + const MutableBufferSequence& buffers) const + { + // If you get an error on the following line it means that your handler + // does not meet the documented type requirements for a ReadHandler. + ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; + + detail::non_const_lvalue handler2(handler); + self_->impl_.get_service().async_read_some( + self_->impl_.get_implementation(), buffers, handler2.value, + self_->impl_.get_implementation_executor()); + } + + private: + basic_stream_handle* self_; + }; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/object_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/object_handle.hpp new file mode 100644 index 00000000..9403ed66 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/object_handle.hpp @@ -0,0 +1,38 @@ +// +// windows/object_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// Copyright (c) 2011 Boris Schaeling (boris@highscore.de) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_OBJECT_HANDLE_HPP +#define ASIO_WINDOWS_OBJECT_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/windows/basic_object_handle.hpp" + +namespace asio { +namespace windows { + +/// Typedef for the typical usage of an object handle. +typedef basic_object_handle<> object_handle; + +} // namespace windows +} // namespace asio + +#endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_OBJECT_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_handle.hpp new file mode 100644 index 00000000..4819fa2f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_handle.hpp @@ -0,0 +1,39 @@ +// +// windows/overlapped_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP +#define ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/windows/basic_overlapped_handle.hpp" + +namespace asio { +namespace windows { + +/// Typedef for the typical usage of an overlapped handle. +typedef basic_overlapped_handle<> overlapped_handle; + +} // namespace windows +} // namespace asio + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_ptr.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_ptr.hpp new file mode 100644 index 00000000..5dd6f14e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/overlapped_ptr.hpp @@ -0,0 +1,143 @@ +// +// windows/overlapped_ptr.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_OVERLAPPED_PTR_HPP +#define ASIO_WINDOWS_OVERLAPPED_PTR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/detail/noncopyable.hpp" +#include "asio/detail/win_iocp_overlapped_ptr.hpp" +#include "asio/io_context.hpp" + +#include "asio/detail/push_options.hpp" + +namespace asio { +namespace windows { + +/// Wraps a handler to create an OVERLAPPED object for use with overlapped I/O. +/** + * A special-purpose smart pointer used to wrap an application handler so that + * it can be passed as the LPOVERLAPPED argument to overlapped I/O functions. + * + * @par Thread Safety + * @e Distinct @e objects: Safe.@n + * @e Shared @e objects: Unsafe. + */ +class overlapped_ptr + : private noncopyable +{ +public: + /// Construct an empty overlapped_ptr. + overlapped_ptr() + : impl_() + { + } + + /// Construct an overlapped_ptr to contain the specified handler. + template + explicit overlapped_ptr(ExecutionContext& context, + ASIO_MOVE_ARG(Handler) handler, + typename enable_if< + is_convertible::value + >::type* = 0) + : impl_(context.get_executor(), ASIO_MOVE_CAST(Handler)(handler)) + { + } + + /// Construct an overlapped_ptr to contain the specified handler. + template + explicit overlapped_ptr(const Executor& ex, + ASIO_MOVE_ARG(Handler) handler, + typename enable_if< + is_executor::value + >::type* = 0) + : impl_(ex, ASIO_MOVE_CAST(Handler)(handler)) + { + } + + /// Destructor automatically frees the OVERLAPPED object unless released. + ~overlapped_ptr() + { + } + + /// Reset to empty. + void reset() + { + impl_.reset(); + } + + /// Reset to contain the specified handler, freeing any current OVERLAPPED + /// object. + template + void reset(ExecutionContext& context, ASIO_MOVE_ARG(Handler) handler, + typename enable_if< + is_convertible::value + >::type* = 0) + { + impl_.reset(context.get_executor(), ASIO_MOVE_CAST(Handler)(handler)); + } + + /// Reset to contain the specified handler, freeing any current OVERLAPPED + /// object. + template + void reset(const Executor& ex, ASIO_MOVE_ARG(Handler) handler, + typename enable_if< + is_executor::value + >::type* = 0) + { + impl_.reset(ex, ASIO_MOVE_CAST(Handler)(handler)); + } + + /// Get the contained OVERLAPPED object. + OVERLAPPED* get() + { + return impl_.get(); + } + + /// Get the contained OVERLAPPED object. + const OVERLAPPED* get() const + { + return impl_.get(); + } + + /// Release ownership of the OVERLAPPED object. + OVERLAPPED* release() + { + return impl_.release(); + } + + /// Post completion notification for overlapped operation. Releases ownership. + void complete(const asio::error_code& ec, + std::size_t bytes_transferred) + { + impl_.complete(ec, bytes_transferred); + } + +private: + detail::win_iocp_overlapped_ptr impl_; +}; + +} // namespace windows +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#endif // defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_OVERLAPPED_PTR_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/random_access_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/random_access_handle.hpp new file mode 100644 index 00000000..dbfa91fe --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/random_access_handle.hpp @@ -0,0 +1,37 @@ +// +// windows/random_access_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP +#define ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/windows/basic_random_access_handle.hpp" + +namespace asio { +namespace windows { + +/// Typedef for the typical usage of a random-access handle. +typedef basic_random_access_handle<> random_access_handle; + +} // namespace windows +} // namespace asio + +#endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/stream_handle.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/stream_handle.hpp new file mode 100644 index 00000000..c597aadd --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/windows/stream_handle.hpp @@ -0,0 +1,37 @@ +// +// windows/stream_handle.hpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WINDOWS_STREAM_HANDLE_HPP +#define ASIO_WINDOWS_STREAM_HANDLE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" + +#if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ + || defined(GENERATING_DOCUMENTATION) + +#include "asio/windows/basic_stream_handle.hpp" + +namespace asio { +namespace windows { + +/// Typedef for the typical usage of a stream-oriented handle. +typedef basic_stream_handle<> stream_handle; + +} // namespace windows +} // namespace asio + +#endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) + // || defined(GENERATING_DOCUMENTATION) + +#endif // ASIO_WINDOWS_STREAM_HANDLE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write.hpp new file mode 100644 index 00000000..86cf2a2a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write.hpp @@ -0,0 +1,1262 @@ +// +// write.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WRITE_HPP +#define ASIO_WRITE_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/buffer.hpp" +#include "asio/error.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) +# include "asio/basic_streambuf_fwd.hpp" +#endif // !defined(ASIO_NO_EXTENSIONS) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/** + * @defgroup write asio::write + * + * @brief The @c write function is a composed operation that writes a certain + * amount of data to a stream before returning. + */ +/*@{*/ + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * stream. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write(s, asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * stream. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write(s, asio::buffer(data, size), ec); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + asio::error_code& ec, + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * stream. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write(s, asio::buffer(data, size), + * asio::transfer_at_least(32)); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * stream. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write(SyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write(SyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param b The basic_streambuf object from which data will be written. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, b, + * asio::transfer_all()); @endcode + */ +template +std::size_t write(SyncWriteStream& s, basic_streambuf& b); + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, b, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write(SyncWriteStream& s, basic_streambuf& b, + asio::error_code& ec); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t write(SyncWriteStream& s, basic_streambuf& b, + CompletionCondition completion_condition); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write(SyncWriteStream& s, basic_streambuf& b, + CompletionCondition completion_condition, asio::error_code& ec); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Write all of the supplied data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::write( + * s, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Write a certain amount of data to a stream before returning. +/** + * This function is used to write a certain number of bytes of data to a stream. + * The call will block until one of the following conditions is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * write_some function. + * + * @param s The stream to which the data is to be written. The type must support + * the SyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Successfully written data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's write_some function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write(SyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, asio::error_code& ec, + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/*@}*/ +/** + * @defgroup async_write asio::async_write + * + * @brief The @c async_write function is a composed asynchronous operation that + * writes a certain amount of data to a stream before completion. + */ +/*@{*/ + +/// Start an asynchronous operation to write all of the supplied data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * asio::async_write(s, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +/// Start an asynchronous operation to write a certain amount of data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers One or more buffers containing the data to be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's async_write_some function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::async_write(s, + * asio::buffer(data, size), + * asio::transfer_at_least(32), + * handler); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_const_buffer_sequence::value + >::type* = 0); + +#if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to write all of the supplied data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. Successfully written + * data is automatically consumed from the buffers. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +/// Start an asynchronous operation to write a certain amount of data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. Successfully written + * data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's async_write_some function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, + ASIO_MOVE_ARG(DynamicBuffer_v1) buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_dynamic_buffer_v1::type>::value + && !is_dynamic_buffer_v2::type>::value + >::type* = 0); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Start an asynchronous operation to write all of the supplied data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param b A basic_streambuf object from which data will be written. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, basic_streambuf& b, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type)); + +/// Start an asynchronous operation to write a certain amount of data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param b A basic_streambuf object from which data will be written. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's async_write_some function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, basic_streambuf& b, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type)); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) +#endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) + +/// Start an asynchronous operation to write all of the supplied data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. Successfully written + * data is automatically consumed from the buffers. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/// Start an asynchronous operation to write a certain amount of data to a +/// stream. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a stream. The function call always returns immediately. The + * asynchronous operation will continue until one of the following conditions + * is true: + * + * @li All of the data in the supplied dynamic buffer sequence has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the stream's + * async_write_some function, and is known as a composed operation. The + * program must ensure that the stream performs no other write operations (such + * as async_write, the stream's async_write_some function, or any other composed + * operations that perform writes) until this operation completes. + * + * @param s The stream to which the data is to be written. The type must support + * the AsyncWriteStream concept. + * + * @param buffers The dynamic buffer sequence from which data will be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. Successfully written + * data is automatically consumed from the buffers. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the stream's async_write_some function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * const asio::error_code& error, // Result of operation. + * + * std::size_t bytes_transferred // Number of bytes written from the + * // buffers. If an error occurred, + * // this will be less than the sum + * // of the buffer sizes. + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write(AsyncWriteStream& s, DynamicBuffer_v2 buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncWriteStream::executor_type), + typename enable_if< + is_dynamic_buffer_v2::value + >::type* = 0); + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/write.hpp" + +#endif // ASIO_WRITE_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write_at.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write_at.hpp new file mode 100644 index 00000000..d7b1858f --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/write_at.hpp @@ -0,0 +1,702 @@ +// +// write_at.hpp +// ~~~~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#ifndef ASIO_WRITE_AT_HPP +#define ASIO_WRITE_AT_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif // defined(_MSC_VER) && (_MSC_VER >= 1200) + +#include "asio/detail/config.hpp" +#include +#include "asio/async_result.hpp" +#include "asio/detail/cstdint.hpp" +#include "asio/error.hpp" + +#if !defined(ASIO_NO_EXTENSIONS) +# include "asio/basic_streambuf_fwd.hpp" +#endif // !defined(ASIO_NO_EXTENSIONS) + +#include "asio/detail/push_options.hpp" + +namespace asio { + +/** + * @defgroup write_at asio::write_at + * + * @brief The @c write_at function is a composed operation that writes a + * certain amount of data at a specified offset before returning. + */ +/*@{*/ + +/// Write all of the supplied data at the specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * device. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write_at(d, 42, asio::buffer(data, size)); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::write_at( + * d, offset, buffers, + * asio::transfer_all()); @endcode + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers); + +/// Write all of the supplied data at the specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * device. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write_at(d, 42, + * asio::buffer(data, size), ec); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + * + * @note This overload is equivalent to calling: + * @code asio::write_at( + * d, offset, buffers, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + asio::error_code& ec); + +/// Write a certain amount of data at a specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * device. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's write_some_at function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::write_at(d, 42, asio::buffer(data, size), + * asio::transfer_at_least(32)); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition); + +/// Write a certain amount of data at a specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. The sum + * of the buffer sizes indicates the maximum number of bytes to write to the + * device. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's write_some_at function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, asio::error_code& ec); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Write all of the supplied data at the specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b The basic_streambuf object from which data will be written. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + * + * @note This overload is equivalent to calling: + * @code asio::write_at( + * d, 42, b, + * asio::transfer_all()); @endcode + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, basic_streambuf& b); + +/// Write all of the supplied data at the specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes transferred. + * + * @note This overload is equivalent to calling: + * @code asio::write_at( + * d, 42, b, + * asio::transfer_all(), ec); @endcode + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, + uint64_t offset, basic_streambuf& b, + asio::error_code& ec); + +/// Write a certain amount of data at a specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's write_some_at function. + * + * @returns The number of bytes transferred. + * + * @throws asio::system_error Thrown on failure. + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, + basic_streambuf& b, CompletionCondition completion_condition); + +/// Write a certain amount of data at a specified offset before returning. +/** + * This function is used to write a certain number of bytes of data to a random + * access device at a specified offset. The call will block until one of the + * following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * write_some_at function. + * + * @param d The device to which the data is to be written. The type must support + * the SyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b The basic_streambuf object from which data will be written. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's write_some_at function. + * + * @param ec Set to indicate what error occurred, if any. + * + * @returns The number of bytes written. If an error occurs, returns the total + * number of bytes successfully transferred prior to the error. + */ +template +std::size_t write_at(SyncRandomAccessWriteDevice& d, uint64_t offset, + basic_streambuf& b, CompletionCondition completion_condition, + asio::error_code& ec); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ +/** + * @defgroup async_write_at asio::async_write_at + * + * @brief The @c async_write_at function is a composed asynchronous operation + * that writes a certain amount of data at the specified offset before + * completion. + */ +/*@{*/ + +/// Start an asynchronous operation to write all of the supplied data at the +/// specified offset. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a random access device at a specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_write_some_at function, and is known as a composed operation. + * The program must ensure that the device performs no overlapping + * write operations (such as async_write_at, the device's async_write_some_at + * function, or any other composed operations that perform writes) until this + * operation completes. Operations are overlapping if the regions defined by + * their offsets, and the numbers of bytes to write, intersect. + * + * @param d The device to which the data is to be written. The type must support + * the AsyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of + * the handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes written from the buffers. If an error + * // occurred, this will be less than the sum of the buffer sizes. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code + * asio::async_write_at(d, 42, asio::buffer(data, size), handler); + * @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, + const ConstBufferSequence& buffers, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessWriteDevice::executor_type)); + +/// Start an asynchronous operation to write a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a random access device at a specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li All of the data in the supplied buffers has been written. That is, the + * bytes transferred is equal to the sum of the buffer sizes. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_write_some_at function, and is known as a composed operation. + * The program must ensure that the device performs no overlapping + * write operations (such as async_write_at, the device's async_write_some_at + * function, or any other composed operations that perform writes) until this + * operation completes. Operations are overlapping if the regions defined by + * their offsets, and the numbers of bytes to write, intersect. + * + * @param d The device to which the data is to be written. The type must support + * the AsyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param buffers One or more buffers containing the data to be written. + * Although the buffers object may be copied as necessary, ownership of the + * underlying memory blocks is retained by the caller, which must guarantee + * that they remain valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's async_write_some_at function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes written from the buffers. If an error + * // occurred, this will be less than the sum of the buffer sizes. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + * + * @par Example + * To write a single data buffer use the @ref buffer function as follows: + * @code asio::async_write_at(d, 42, + * asio::buffer(data, size), + * asio::transfer_at_least(32), + * handler); @endcode + * See the @ref buffer documentation for information on writing multiple + * buffers in one go, and how to use it with arrays, boost::array or + * std::vector. + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, const ConstBufferSequence& buffers, + CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessWriteDevice::executor_type)); + +#if !defined(ASIO_NO_EXTENSIONS) +#if !defined(ASIO_NO_IOSTREAM) + +/// Start an asynchronous operation to write all of the supplied data at the +/// specified offset. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a random access device at a specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li An error occurred. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_write_some_at function, and is known as a composed operation. + * The program must ensure that the device performs no overlapping + * write operations (such as async_write_at, the device's async_write_some_at + * function, or any other composed operations that perform writes) until this + * operation completes. Operations are overlapping if the regions defined by + * their offsets, and the numbers of bytes to write, intersect. + * + * @param d The device to which the data is to be written. The type must support + * the AsyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b A basic_streambuf object from which data will be written. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes written from the buffers. If an error + * // occurred, this will be less than the sum of the buffer sizes. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, + uint64_t offset, basic_streambuf& b, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessWriteDevice::executor_type)); + +/// Start an asynchronous operation to write a certain amount of data at the +/// specified offset. +/** + * This function is used to asynchronously write a certain number of bytes of + * data to a random access device at a specified offset. The function call + * always returns immediately. The asynchronous operation will continue until + * one of the following conditions is true: + * + * @li All of the data in the supplied basic_streambuf has been written. + * + * @li The completion_condition function object returns 0. + * + * This operation is implemented in terms of zero or more calls to the device's + * async_write_some_at function, and is known as a composed operation. + * The program must ensure that the device performs no overlapping + * write operations (such as async_write_at, the device's async_write_some_at + * function, or any other composed operations that perform writes) until this + * operation completes. Operations are overlapping if the regions defined by + * their offsets, and the numbers of bytes to write, intersect. + * + * @param d The device to which the data is to be written. The type must support + * the AsyncRandomAccessWriteDevice concept. + * + * @param offset The offset at which the data will be written. + * + * @param b A basic_streambuf object from which data will be written. Ownership + * of the streambuf is retained by the caller, which must guarantee that it + * remains valid until the handler is called. + * + * @param completion_condition The function object to be called to determine + * whether the write operation is complete. The signature of the function object + * must be: + * @code std::size_t completion_condition( + * // Result of latest async_write_some_at operation. + * const asio::error_code& error, + * + * // Number of bytes transferred so far. + * std::size_t bytes_transferred + * ); @endcode + * A return value of 0 indicates that the write operation is complete. A + * non-zero return value indicates the maximum number of bytes to be written on + * the next call to the device's async_write_some_at function. + * + * @param handler The handler to be called when the write operation completes. + * Copies will be made of the handler as required. The function signature of the + * handler must be: + * @code void handler( + * // Result of operation. + * const asio::error_code& error, + * + * // Number of bytes written from the buffers. If an error + * // occurred, this will be less than the sum of the buffer sizes. + * std::size_t bytes_transferred + * ); @endcode + * Regardless of whether the asynchronous operation completes immediately or + * not, the handler will not be invoked from within this function. On + * immediate completion, invocation of the handler will be performed in a + * manner equivalent to using asio::post(). + */ +template +ASIO_INITFN_AUTO_RESULT_TYPE(WriteHandler, + void (asio::error_code, std::size_t)) +async_write_at(AsyncRandomAccessWriteDevice& d, uint64_t offset, + basic_streambuf& b, CompletionCondition completion_condition, + ASIO_MOVE_ARG(WriteHandler) handler + ASIO_DEFAULT_COMPLETION_TOKEN( + typename AsyncRandomAccessWriteDevice::executor_type)); + +#endif // !defined(ASIO_NO_IOSTREAM) +#endif // !defined(ASIO_NO_EXTENSIONS) + +/*@}*/ + +} // namespace asio + +#include "asio/detail/pop_options.hpp" + +#include "asio/impl/write_at.hpp" + +#endif // ASIO_WRITE_AT_HPP diff --git a/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/yield.hpp b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/yield.hpp new file mode 100644 index 00000000..d37d146e --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/asio/asio/include/asio/yield.hpp @@ -0,0 +1,23 @@ +// +// yield.hpp +// ~~~~~~~~~ +// +// Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// + +#include "coroutine.hpp" + +#ifndef reenter +# define reenter(c) ASIO_CORO_REENTER(c) +#endif + +#ifndef yield +# define yield ASIO_CORO_YIELD +#endif + +#ifndef fork +# define fork ASIO_CORO_FORK +#endif diff --git a/tools/sdk/esp32c3/include/asio/port/include/esp_asio_config.h b/tools/sdk/esp32c3/include/asio/port/include/esp_asio_config.h new file mode 100644 index 00000000..bcf8c38d --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/esp_asio_config.h @@ -0,0 +1,50 @@ +// Copyright 2018 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. +#ifndef _ESP_ASIO_CONFIG_H_ +#define _ESP_ASIO_CONFIG_H_ + +// +// Enabling exceptions only when they are enabled in menuconfig +// +# include +# ifndef CONFIG_COMPILER_CXX_EXCEPTIONS +# define ASIO_NO_EXCEPTIONS +# endif // CONFIG_COMPILER_CXX_EXCEPTIONS + +# ifndef CONFIG_COMPILER_RTTI +# define ASIO_NO_TYPEID +# endif // CONFIG_COMPILER_RTTI + +// +// LWIP compatibility inet and address macros/functions +// +# define LWIP_COMPAT_SOCKET_INET 1 +# define LWIP_COMPAT_SOCKET_ADDR 1 + +// +// Specific ASIO feature flags +// +# define ASIO_DISABLE_SERIAL_PORT +# define ASIO_SEPARATE_COMPILATION +# define ASIO_STANDALONE +# define ASIO_HAS_PTHREADS + +# ifdef CONFIG_ASIO_USE_ESP_OPENSSL +# define ASIO_USE_ESP_OPENSSL +# define OPENSSL_NO_ENGINE +# elif CONFIG_ASIO_USE_ESP_WOLFSSL +# define ASIO_USE_WOLFSSL +# endif // CONFIG_ASIO_USE_ESP_OPENSSL + +#endif // _ESP_ASIO_CONFIG_H_ diff --git a/tools/sdk/esp32c3/include/asio/port/include/esp_exception.h b/tools/sdk/esp32c3/include/asio/port/include/esp_exception.h new file mode 100644 index 00000000..cbf20d7a --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/esp_exception.h @@ -0,0 +1,39 @@ + +// Copyright 2018 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. +#ifndef _ESP_EXCEPTION_H_ +#define _ESP_EXCEPTION_H_ + +// +// This exception stub is enabled only if exceptions are disabled in menuconfig +// +#if !defined(CONFIG_COMPILER_CXX_EXCEPTIONS) && defined (ASIO_NO_EXCEPTIONS) + +#include "esp_log.h" + +// +// asio exception stub +// +namespace asio { +namespace detail { +template +void throw_exception(const Exception& e) +{ + ESP_LOGE("esp32_asio_exception", "Caught exception: %s!", e.what()); + abort(); +} +}} +#endif // CONFIG_COMPILER_CXX_EXCEPTIONS==1 && defined (ASIO_NO_EXCEPTIONS) + +#endif // _ESP_EXCEPTION_H_ diff --git a/tools/sdk/esp32c3/include/asio/port/include/openssl/conf.h b/tools/sdk/esp32c3/include/asio/port/include/openssl/conf.h new file mode 100644 index 00000000..f125c3e6 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/openssl/conf.h @@ -0,0 +1,26 @@ +// Copyright 2020 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. + +#ifndef _ESP_ASIO_OPENSSL_CONF_H +#define _ESP_ASIO_OPENSSL_CONF_H +#include "esp_asio_config.h" +#include "openssl/esp_asio_openssl_stubs.h" + +#if defined(ASIO_USE_WOLFSSL) +// SSLv3 Methods not present in current wolfSSL library +#define OPENSSL_NO_SSL3 +#include_next "openssl/conf.h" +#endif // ASIO_USE_WOLFSSL + +#endif // _ESP_ASIO_OPENSSL_CONF_H diff --git a/tools/sdk/esp32c3/include/asio/port/include/openssl/dh.h b/tools/sdk/esp32c3/include/asio/port/include/openssl/dh.h new file mode 100644 index 00000000..def713cf --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/openssl/dh.h @@ -0,0 +1,23 @@ +// Copyright 2020 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. + +#ifndef _ESP_ASIO_OPENSSL_DH_STUB_H +#define _ESP_ASIO_OPENSSL_DH_STUB_H +// Dummy header needed for ASIO compilation with esp-openssl + +#if defined(ASIO_USE_WOLFSSL) +#include_next "openssl/dh.h" +#endif // ASIO_USE_WOLFSSL + +#endif // _ESP_ASIO_OPENSSL_DH_STUB_H diff --git a/tools/sdk/esp32c3/include/asio/port/include/openssl/esp_asio_openssl_stubs.h b/tools/sdk/esp32c3/include/asio/port/include/openssl/esp_asio_openssl_stubs.h new file mode 100644 index 00000000..fde52317 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/openssl/esp_asio_openssl_stubs.h @@ -0,0 +1,209 @@ +// Copyright 2020 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. + +#ifndef _ESP_ASIO_OPENSSL_STUBS_H +#define _ESP_ASIO_OPENSSL_STUBS_H + +/** + * @note This header contains openssl API which are NOT implemented, and are only provided + * as stubs or no-operations to get the ASIO library compiled and working with most + * practical use cases as an embedded application on ESP platform + */ + +#if defined(ASIO_USE_WOLFSSL) + +#include "wolfssl/ssl.h" +// esp-wolfssl disables filesystem by default, but the ssl filesystem functions are needed for the ASIO to compile +// - so we could either configure wolfSSL to use filesystem +// - or use the default wolfSSL and declare the filesystem functions -- preferred option, as whenever +// the filesystem functions are used from app code (potential security impact if private keys in a filesystem) +// compilation fails with linking errors. + +#if defined(NO_FILESYSTEM) +// WolfSSL methods that are not included in standard esp-wolfssl config, must be defined here +// as function stubs, so ASIO compiles, but would get link errors, if these functions were used. + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct WOLFSSL_CTX WOLFSSL_CTX; + +void wolfSSL_CTX_set_verify_depth(WOLFSSL_CTX *ctx,int depth); +int SSL_CTX_load_verify_locations(WOLFSSL_CTX*, const char*, const char*); +int SSL_CTX_use_certificate_file(WOLFSSL_CTX*, const char*, int); +int SSL_CTX_use_certificate_chain_file(WOLFSSL_CTX*, const char*); +int SSL_CTX_use_PrivateKey_file(WOLFSSL_CTX*, const char*, int); +int SSL_CTX_use_RSAPrivateKey_file(WOLFSSL_CTX*, const char*, int); + +#if defined(__cplusplus) +} /* extern C */ +#endif + +#endif // NO_FILESYSTEM + +#elif defined(ASIO_USE_ESP_OPENSSL) + +#include "internal/ssl_x509.h" +#include "internal/ssl_pkey.h" +#include "mbedtls/pem.h" +#include + + +#ifdef __cplusplus +extern "C" { +#endif + + +// The most applicable OpenSSL version wrtt ASIO usage +#define OPENSSL_VERSION_NUMBER 0x10100001L +// SSLv2 methods not supported +// OpenSSL port supports: TLS_ANY, TLS_1, TLS_1_1, TLS_1_2, SSL_3 +#define OPENSSL_NO_SSL2 +#define SSL2_VERSION 0x0002 + +#define SSL_R_SHORT_READ 219 +#define SSL_OP_ALL 0 +#define SSL_OP_SINGLE_DH_USE 0 +#define SSL_OP_NO_COMPRESSION 0 +// Translates mbedTLS PEM parse error, used by ASIO +#define PEM_R_NO_START_LINE -MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT + +#define SSL_OP_NO_SSLv2 0x01000000L +#define SSL_OP_NO_SSLv3 0x02000000L +#define SSL_OP_NO_TLSv1 0x04000000L + +#define X509_FILETYPE_PEM 1 +#define X509_FILETYPE_ASN1 2 +#define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1 +#define SSL_FILETYPE_PEM X509_FILETYPE_PEM + +#define NID_subject_alt_name 85 + + +#define GEN_DNS 2 +#define GEN_IPADD 7 +#define V_ASN1_OCTET_STRING 4 +#define V_ASN1_IA5STRING 22 +#define NID_commonName 13 + +#define SSL_CTX_get_app_data(ctx) ((void*)SSL_CTX_get_ex_data(ctx, 0)) + +/** +* @brief Frees DH object -- not implemented +* +* Current implementation calls SSL_ASSERT +* +* @param r DH object +*/ +void DH_free(DH *r); + +/** + * @brief Frees GENERAL_NAMES -- not implemented + * + * Current implementation calls SSL_ASSERT + * + * @param r GENERAL_NAMES object + */ +void GENERAL_NAMES_free(GENERAL_NAMES * gens); + +/** + * @brief Returns subject name from X509 -- not implemented + * + * Current implementation calls SSL_ASSERT + * + * @param r X509 object + */ +X509_NAME *X509_get_subject_name(X509 *a); + +/** + * @brief API provaded as declaration only + * + */ +int X509_STORE_CTX_get_error_depth(X509_STORE_CTX *ctx); + +/** + * @brief API provaded as declaration only + * + */ +int X509_NAME_get_index_by_NID(X509_NAME *name, int nid, int lastpos); + +/** + * @brief API provaded as declaration only + * + */ +X509_NAME_ENTRY *X509_NAME_get_entry(X509_NAME *name, int loc); + +/** + * @brief API provaded as declaration only + * + */ +ASN1_STRING *X509_NAME_ENTRY_get_data(X509_NAME_ENTRY *ne); + +/** + * @brief API provaded as declaration only + * + */ +void *X509_get_ext_d2i(X509 *x, int nid, int *crit, int *idx); + +/** + * @brief API provaded as declaration only + * + */ +X509 * X509_STORE_CTX_get_current_cert(X509_STORE_CTX *ctx); + +/** + * @brief Reads DH params from a bio object -- not implemented + * + * Current implementation calls SSL_ASSERT + */ +DH *PEM_read_bio_DHparams(BIO *bp, DH **x, pem_password_cb *cb, void *u); + +/** + * @brief API provaded as declaration only + * + */ +void * X509_STORE_CTX_get_ex_data(X509_STORE_CTX *ctx,int idx); + +/** + * @brief Sets DH params to ssl ctx -- not implemented + * + * Current implementation calls SSL_ASSERT + */ +int SSL_CTX_set_tmp_dh(SSL_CTX *ctx, const DH *dh); + +/** + * @brief API provaded as declaration only + * + */ +void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *data); + +/** + * @brief API provaded as declaration only + * + */ +void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb); + +/** + * @brief Clears any existing chain associated with the current certificate of ctx. + * + */ +int SSL_CTX_clear_chain_certs(SSL_CTX *ctx); + +#if defined(__cplusplus) +} /* extern C */ +#endif + +#endif /* ASIO_USE_ESP_OPENSSL, ASIO_USE_WOLFSSL */ +#endif /* _ESP_ASIO_OPENSSL_STUBS_H */ diff --git a/tools/sdk/esp32c3/include/asio/port/include/openssl/rsa.h b/tools/sdk/esp32c3/include/asio/port/include/openssl/rsa.h new file mode 100644 index 00000000..5d9d10e8 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/openssl/rsa.h @@ -0,0 +1,23 @@ +// Copyright 2020 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. + +#ifndef _ESP_ASIO_OPENSSL_RSA_STUB_H +#define _ESP_ASIO_OPENSSL_RSA_STUB_H +// Dummy header needed for ASIO compilation with esp-openssl + +#if defined(ASIO_USE_WOLFSSL) +#include_next "openssl/rsa.h" +#endif // ASIO_USE_WOLFSSL + +#endif // _ESP_ASIO_OPENSSL_RSA_STUB_H diff --git a/tools/sdk/esp32c3/include/asio/port/include/openssl/x509v3.h b/tools/sdk/esp32c3/include/asio/port/include/openssl/x509v3.h new file mode 100644 index 00000000..5ae8e784 --- /dev/null +++ b/tools/sdk/esp32c3/include/asio/port/include/openssl/x509v3.h @@ -0,0 +1,23 @@ +// Copyright 2020 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. + +#ifndef _ESP_ASIO_OPENSSL_X509V3_STUB_H +#define _ESP_ASIO_OPENSSL_X509V3_STUB_H +// Dummy header needed for ASIO compilation with esp-openssl + +#if defined(ASIO_USE_WOLFSSL) +#include_next "openssl/x509v3.h" +#endif // ASIO_USE_WOLFSSL + +#endif // _ESP_ASIO_OPENSSL_X509V3_STUB_H diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_clock.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_clock.h new file mode 100644 index 00000000..98546e82 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_clock.h @@ -0,0 +1,33 @@ +// Copyright 2017 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Configure clocks for early boot + * + * Called by bootloader, or by the app if the bootloader version is old (pre v2.1). + */ +void bootloader_clock_configure(void); + +/** @brief Return the rated maximum frequency of this chip + */ +int bootloader_clock_get_rated_freq_mhz(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_common.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_common.h new file mode 100644 index 00000000..0723d195 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_common.h @@ -0,0 +1,269 @@ +// Copyright 2018 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. + +#pragma once +#include "esp_flash_partitions.h" +#include "esp_image_format.h" +#include "esp_app_format.h" +// RESET_REASON is declared in rom/rtc.h +#if CONFIG_IDF_TARGET_ESP32 +#include "esp32/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/rom/rtc.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/rtc.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/// Type of hold a GPIO in low state +typedef enum { + GPIO_LONG_HOLD = 1, /*!< The long hold GPIO */ + GPIO_SHORT_HOLD = -1, /*!< The short hold GPIO */ + GPIO_NOT_HOLD = 0 /*!< If the GPIO input is not low */ +} esp_comm_gpio_hold_t; + +typedef enum { + ESP_IMAGE_BOOTLOADER, + ESP_IMAGE_APPLICATION +} esp_image_type; + +/** + * @brief Calculate crc for the OTA data select. + * + * @param[in] s The OTA data select. + * @return Returns crc value. + */ +uint32_t bootloader_common_ota_select_crc(const esp_ota_select_entry_t *s); + +/** + * @brief Verifies the validity of the OTA data select + * + * @param[in] s The OTA data select. + * @return Returns true on valid, false otherwise. + */ +bool bootloader_common_ota_select_valid(const esp_ota_select_entry_t *s); + +/** + * @brief Returns true if OTADATA is not marked as bootable partition. + * + * @param[in] s The OTA data select. + * @return Returns true if OTADATA invalid, false otherwise. + */ +bool bootloader_common_ota_select_invalid(const esp_ota_select_entry_t *s); + +/** + * @brief Check if the GPIO input is a long hold or a short hold. + * + * Number of the GPIO input will be configured as an input with internal pull-up enabled. + * If the GPIO input is held low continuously for delay_sec period then it is a long hold. + * If the GPIO input is held low for less period then it is a short hold. + * + * @param[in] num_pin Number of the GPIO input. + * @param[in] delay_sec Input must be driven low for at least this long, continuously. + * @return esp_comm_gpio_hold_t Defines type of hold a GPIO in low state. + */ +esp_comm_gpio_hold_t bootloader_common_check_long_hold_gpio(uint32_t num_pin, uint32_t delay_sec); + +/** + * @brief Erase the partition data that is specified in the transferred list. + * + * @param[in] list_erase String containing a list of cleared partitions. Like this "nvs, phy". The string must be null-terminal. + * @param[in] ota_data_erase If true then the OTA data partition will be cleared (if there is it in partition table). + * @return Returns true on success, false otherwise. + */ +bool bootloader_common_erase_part_type_data(const char *list_erase, bool ota_data_erase); + +/** + * @brief Determines if the list contains the label + * + * @param[in] list A string of names delimited by commas or spaces. Like this "nvs, phy, data". The string must be null-terminated. + * @param[in] label The substring that will be searched in the list. + * @return Returns true if the list contains the label, false otherwise. + */ +bool bootloader_common_label_search(const char *list, char *label); + +/** + * @brief Configure default SPI pin modes and drive strengths + * + * @param drv GPIO drive level (determined by clock frequency) + */ +void bootloader_configure_spi_pins(int drv); + +/** + * @brief Calculates a sha-256 for a given partition or returns a appended digest. + * + * This function can be used to return the SHA-256 digest of application, bootloader and data partitions. + * For apps with SHA-256 appended to the app image, the result is the appended SHA-256 value for the app image content. + * The hash is verified before returning, if app content is invalid then the function returns ESP_ERR_IMAGE_INVALID. + * For apps without SHA-256 appended to the image, the result is the SHA-256 of all bytes in the app image. + * For other partition types, the result is the SHA-256 of the entire partition. + * + * @param[in] address Address of partition. + * @param[in] size Size of partition. + * @param[in] type Type of partition. For applications the type is 0, otherwise type is data. + * @param[out] out_sha_256 Returned SHA-256 digest for a given partition. + * + * @return + * - ESP_OK: In case of successful operation. + * - ESP_ERR_INVALID_ARG: The size was 0 or the sha_256 was NULL. + * - ESP_ERR_NO_MEM: Cannot allocate memory for sha256 operation. + * - ESP_ERR_IMAGE_INVALID: App partition doesn't contain a valid app image. + * - ESP_FAIL: An allocation error occurred. + */ +esp_err_t bootloader_common_get_sha256_of_partition(uint32_t address, uint32_t size, int type, uint8_t *out_sha_256); + +/** + * @brief Returns the number of active otadata. + * + * @param[in] two_otadata Pointer on array from two otadata structures. + * + * @return The number of active otadata (0 or 1). + * - -1: If it does not have active otadata. + */ +int bootloader_common_get_active_otadata(esp_ota_select_entry_t *two_otadata); + +/** + * @brief Returns the number of active otadata. + * + * @param[in] two_otadata Pointer on array from two otadata structures. + * @param[in] valid_two_otadata Pointer on array from two bools. True means select. + * @param[in] max True - will select the maximum ota_seq number, otherwise the minimum. + * + * @return The number of active otadata (0 or 1). + * - -1: If it does not have active otadata. + */ +int bootloader_common_select_otadata(const esp_ota_select_entry_t *two_otadata, bool *valid_two_otadata, bool max); + +/** + * @brief Returns esp_app_desc structure for app partition. This structure includes app version. + * + * Returns a description for the requested app partition. + * @param[in] partition App partition description. + * @param[out] app_desc Structure of info about app. + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: The arguments passed are not valid. + * - ESP_ERR_NOT_FOUND: app_desc structure is not found. Magic word is incorrect. + * - ESP_FAIL: mapping is fail. + */ +esp_err_t bootloader_common_get_partition_description(const esp_partition_pos_t *partition, esp_app_desc_t *app_desc); + +/** + * @brief Get chip revision + * + * @return Chip revision number + */ +uint8_t bootloader_common_get_chip_revision(void); + +/** + * @brief Get chip package + * + * @return Chip package number + */ +uint32_t bootloader_common_get_chip_ver_pkg(void); + +/** + * @brief Query reset reason + * + * @param cpu_no CPU number + * @return reset reason enumeration + */ +RESET_REASON bootloader_common_get_reset_reason(int cpu_no); + +/** + * @brief Check if the image (bootloader and application) has valid chip ID and revision + * + * @param[in] img_hdr: image header + * @param[in] type: image type, bootloader or application + * @return + * - ESP_OK: image and chip are matched well + * - ESP_FAIL: image doesn't match to the chip + */ +esp_err_t bootloader_common_check_chip_validity(const esp_image_header_t* img_hdr, esp_image_type type); + +/** + * @brief Configure VDDSDIO, call this API to rise VDDSDIO to 1.9V when VDDSDIO regulator is enabled as 1.8V mode. + */ +void bootloader_common_vddsdio_configure(void); + +#if defined( CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP ) || defined( CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC ) +/** + * @brief Returns partition from rtc_retain_mem + * + * Uses to get the partition of application which was worked before to go to the deep sleep. + * This partition was stored in rtc_retain_mem. + * Note: This function operates the RTC FAST memory which available only for PRO_CPU. + * Make sure that this function is used only PRO_CPU. + * + * @return partition: If rtc_retain_mem is valid. + * - NULL: If it is not valid. + */ +esp_partition_pos_t* bootloader_common_get_rtc_retain_mem_partition(void); + +/** + * @brief Update the partition and reboot_counter in rtc_retain_mem. + * + * This function saves the partition of application for fast booting from the deep sleep. + * An algorithm uses this partition to avoid reading the otadata and does not validate an image. + * Note: This function operates the RTC FAST memory which available only for PRO_CPU. + * Make sure that this function is used only PRO_CPU. + * + * @param[in] partition App partition description. Can be NULL, in this case rtc_retain_mem.partition is not updated. + * @param[in] reboot_counter If true then update reboot_counter. + * + */ +void bootloader_common_update_rtc_retain_mem(esp_partition_pos_t* partition, bool reboot_counter); + +/** + * @brief Reset entire rtc_retain_mem. + * + * Note: This function operates the RTC FAST memory which available only for PRO_CPU. + * Make sure that this function is used only PRO_CPU. + */ +void bootloader_common_reset_rtc_retain_mem(void); + +/** + * @brief Returns reboot_counter from rtc_retain_mem + * + * The reboot_counter counts the number of reboots. Reset only when power is off. + * The very first launch of the application will be from 1. + * Overflow is not possible, it will stop at the value UINT16_MAX. + * Note: This function operates the RTC FAST memory which available only for PRO_CPU. + * Make sure that this function is used only PRO_CPU. + * + * @return reboot_counter: 1..65535 + * - 0: If rtc_retain_mem is not valid. + */ +uint16_t bootloader_common_get_rtc_retain_mem_reboot_counter(void); + +/** + * @brief Returns rtc_retain_mem + * + * Note: This function operates the RTC FAST memory which available only for PRO_CPU. + * Make sure that this function is used only PRO_CPU. + * + * @return rtc_retain_mem + */ +rtc_retain_mem_t* bootloader_common_get_rtc_retain_mem(void); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash.h new file mode 100644 index 00000000..8bf74852 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash.h @@ -0,0 +1,29 @@ +// Copyright 2020 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. +#pragma once + +#include +#include /* including in bootloader for error values */ +#include "sdkconfig.h" +#include "soc/soc_caps.h" + +#if SOC_CACHE_SUPPORT_WRAP +/** + * @brief Set the burst mode setting command for specified wrap mode. + * + * @param mode The specified warp mode. + * @return always ESP_OK + */ +esp_err_t bootloader_flash_wrap_set(spi_flash_wrap_mode_t mode); +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash_config.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash_config.h new file mode 100644 index 00000000..6074faca --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_flash_config.h @@ -0,0 +1,96 @@ +// Copyright 2018 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. + +#pragma once + +#include "sdkconfig.h" +#include "esp_image_format.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Update the flash id in g_rom_flashchip(global esp_rom_spiflash_chip_t structure). + * + * @return None + */ +void bootloader_flash_update_id(void); + +/** + * @brief Update the flash size in g_rom_flashchip (global esp_rom_spiflash_chip_t structure). + * + * @param size The size to store, in bytes. + * @return None + */ +void bootloader_flash_update_size(uint32_t size); + +/** + * @brief Set the flash CS setup and hold time. + * + * @note CS setup time is recomemded to be 1.5T, and CS hold time is recommended to be 2.5T. + * cs_setup = 1, cs_setup_time = 0; cs_hold = 1, cs_hold_time = 1. + * + * @return None + */ +void bootloader_flash_cs_timing_config(void); + +/** + * @brief Configure SPI flash clock. + * + * @note This function only set clock frequency for SPI0. + * + * @param pfhdr Pointer to App image header, from where to fetch flash settings. + * + * @return None + */ +void bootloader_flash_clock_config(const esp_image_header_t* pfhdr); + +/** + * @brief Configure SPI flash gpio, include the IO matrix and drive strength configuration. + * + * @param pfhdr Pointer to App image header, from where to fetch flash settings. + * + * @return None + */ +void bootloader_flash_gpio_config(const esp_image_header_t* pfhdr); + +/** + * @brief Configure SPI flash read dummy based on different mode and frequency. + * + * @param pfhdr Pointer to App image header, from where to fetch flash settings. + * + * @return None + */ +void bootloader_flash_dummy_config(const esp_image_header_t* pfhdr); + +#ifdef CONFIG_IDF_TARGET_ESP32 +/** + * @brief Return the pin number used for custom SPI flash and/or SPIRAM WP pin + * + * Can be determined by eFuse values in most cases, or overriden in configuration + * + * This value is only meaningful if the other SPI flash pins are overriden via eFuse. + * + * This value is only meaningful if flash is set to QIO or QOUT mode, or if + * SPIRAM is enabled. + * + * @return Pin number to use, or -1 if the default should be kept + */ +int bootloader_flash_get_wp_pin(void); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_mem.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_mem.h new file mode 100644 index 00000000..bc54833f --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_mem.h @@ -0,0 +1,24 @@ +// Copyright 2020 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. +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void bootloader_init_mem(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_random.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_random.h new file mode 100644 index 00000000..98a7712f --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_random.h @@ -0,0 +1,57 @@ +// Copyright 2010-2016 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Enable early entropy source for RNG + * + * Uses the SAR ADC to feed entropy into the HWRNG. The ADC is put + * into a test mode that reads the 1.1V internal reference source and + * feeds the LSB of data into the HWRNG. + * + * Can also be used from app code early during operation, if entropy + * is required before WiFi stack is initialised. Call this function + * from app code only if WiFi/BT are not yet enabled and I2S and SAR + * ADC are not in use. + * + * Call bootloader_random_disable() when done. + */ +void bootloader_random_enable(void); + +/** + * @brief Disable early entropy source for RNG + * + * Disables SAR ADC source and resets the I2S hardware. + * + */ +void bootloader_random_disable(void); + +/** + * @brief Fill buffer with 'length' random bytes + * + * @param buffer Pointer to buffer + * @param length This many bytes of random data will be copied to buffer + */ +void bootloader_fill_random(void *buffer, size_t length); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_util.h b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_util.h new file mode 100644 index 00000000..a1b8d89c --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/bootloader_util.h @@ -0,0 +1,43 @@ +// Copyright 2018 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Check if half-open intervals overlap + * + * @param start1 interval 1 start + * @param end1 interval 1 end + * @param start2 interval 2 start + * @param end2 interval 2 end + * @return true iff [start1; end1) overlaps [start2; end2) + */ +static inline bool bootloader_util_regions_overlap( + const intptr_t start1, const intptr_t end1, + const intptr_t start2, const intptr_t end2) +{ + assert(end1>start1); + assert(end2>start2); + return (end1 > start2 && end2 > start1); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_app_format.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_app_format.h new file mode 100644 index 00000000..20237728 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_app_format.h @@ -0,0 +1,129 @@ +// Copyright 2015-2019 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. +#pragma once + +#include + +/** + * @brief ESP chip ID + * + */ +typedef enum { + ESP_CHIP_ID_ESP32 = 0x0000, /*!< chip ID: ESP32 */ + ESP_CHIP_ID_ESP32S2 = 0x0002, /*!< chip ID: ESP32-S2 */ + ESP_CHIP_ID_ESP32C3 = 0x0005, /*!< chip ID: ESP32-C3 */ + ESP_CHIP_ID_ESP32S3 = 0x0006, /*!< chip ID: ESP32-S3 */ + ESP_CHIP_ID_INVALID = 0xFFFF /*!< Invalid chip ID (we defined it to make sure the esp_chip_id_t is 2 bytes size) */ +} __attribute__((packed)) esp_chip_id_t; + +/** @cond */ +_Static_assert(sizeof(esp_chip_id_t) == 2, "esp_chip_id_t should be 16 bit"); +/** @endcond */ + +/** + * @brief SPI flash mode, used in esp_image_header_t + */ +typedef enum { + ESP_IMAGE_SPI_MODE_QIO, /*!< SPI mode QIO */ + ESP_IMAGE_SPI_MODE_QOUT, /*!< SPI mode QOUT */ + ESP_IMAGE_SPI_MODE_DIO, /*!< SPI mode DIO */ + ESP_IMAGE_SPI_MODE_DOUT, /*!< SPI mode DOUT */ + ESP_IMAGE_SPI_MODE_FAST_READ, /*!< SPI mode FAST_READ */ + ESP_IMAGE_SPI_MODE_SLOW_READ /*!< SPI mode SLOW_READ */ +} esp_image_spi_mode_t; + +/** + * @brief SPI flash clock frequency + */ +typedef enum { + ESP_IMAGE_SPI_SPEED_40M, /*!< SPI clock frequency 40 MHz */ + ESP_IMAGE_SPI_SPEED_26M, /*!< SPI clock frequency 26 MHz */ + ESP_IMAGE_SPI_SPEED_20M, /*!< SPI clock frequency 20 MHz */ + ESP_IMAGE_SPI_SPEED_80M = 0xF /*!< SPI clock frequency 80 MHz */ +} esp_image_spi_freq_t; + +/** + * @brief Supported SPI flash sizes + */ +typedef enum { + ESP_IMAGE_FLASH_SIZE_1MB = 0, /*!< SPI flash size 1 MB */ + ESP_IMAGE_FLASH_SIZE_2MB, /*!< SPI flash size 2 MB */ + ESP_IMAGE_FLASH_SIZE_4MB, /*!< SPI flash size 4 MB */ + ESP_IMAGE_FLASH_SIZE_8MB, /*!< SPI flash size 8 MB */ + ESP_IMAGE_FLASH_SIZE_16MB, /*!< SPI flash size 16 MB */ + ESP_IMAGE_FLASH_SIZE_MAX /*!< SPI flash size MAX */ +} esp_image_flash_size_t; + +#define ESP_IMAGE_HEADER_MAGIC 0xE9 /*!< The magic word for the esp_image_header_t structure. */ + +/** + * @brief Main header of binary image + */ +typedef struct { + uint8_t magic; /*!< Magic word ESP_IMAGE_HEADER_MAGIC */ + uint8_t segment_count; /*!< Count of memory segments */ + uint8_t spi_mode; /*!< flash read mode (esp_image_spi_mode_t as uint8_t) */ + uint8_t spi_speed: 4; /*!< flash frequency (esp_image_spi_freq_t as uint8_t) */ + uint8_t spi_size: 4; /*!< flash chip size (esp_image_flash_size_t as uint8_t) */ + uint32_t entry_addr; /*!< Entry address */ + uint8_t wp_pin; /*!< WP pin when SPI pins set via efuse (read by ROM bootloader, + * the IDF bootloader uses software to configure the WP + * pin and sets this field to 0xEE=disabled) */ + uint8_t spi_pin_drv[3]; /*!< Drive settings for the SPI flash pins (read by ROM bootloader) */ + esp_chip_id_t chip_id; /*!< Chip identification number */ + uint8_t min_chip_rev; /*!< Minimum chip revision supported by image */ + uint8_t reserved[8]; /*!< Reserved bytes in additional header space, currently unused */ + uint8_t hash_appended; /*!< If 1, a SHA256 digest "simple hash" (of the entire image) is appended after the checksum. + * Included in image length. This digest + * is separate to secure boot and only used for detecting corruption. + * For secure boot signed images, the signature + * is appended after this (and the simple hash is included in the signed data). */ +} __attribute__((packed)) esp_image_header_t; + +/** @cond */ +_Static_assert(sizeof(esp_image_header_t) == 24, "binary image header should be 24 bytes"); +/** @endcond */ + + +/** + * @brief Header of binary image segment + */ +typedef struct { + uint32_t load_addr; /*!< Address of segment */ + uint32_t data_len; /*!< Length of data */ +} esp_image_segment_header_t; + +#define ESP_IMAGE_MAX_SEGMENTS 16 /*!< Max count of segments in the image. */ + +#define ESP_APP_DESC_MAGIC_WORD 0xABCD5432 /*!< The magic word for the esp_app_desc structure that is in DROM. */ + +/** + * @brief Description about application. + */ +typedef struct { + uint32_t magic_word; /*!< Magic word ESP_APP_DESC_MAGIC_WORD */ + uint32_t secure_version; /*!< Secure version */ + uint32_t reserv1[2]; /*!< reserv1 */ + char version[32]; /*!< Application version */ + char project_name[32]; /*!< Project name */ + char time[16]; /*!< Compile time */ + char date[16]; /*!< Compile date*/ + char idf_ver[32]; /*!< Version IDF */ + uint8_t app_elf_sha256[32]; /*!< sha256 of elf file */ + uint32_t reserv2[20]; /*!< reserv2 */ +} esp_app_desc_t; + +/** @cond */ +_Static_assert(sizeof(esp_app_desc_t) == 256, "esp_app_desc_t should be 256 bytes"); +/** @endcond */ diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_data_types.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_data_types.h new file mode 100644 index 00000000..fda6d5c6 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_data_types.h @@ -0,0 +1,2 @@ +#warning esp_flash_data_types.h has been merged into esp_flash_partitions.h, please include esp_flash_partitions.h instead +#include "esp_flash_partitions.h" diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_encrypt.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_encrypt.h new file mode 100644 index 00000000..33e6aabe --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_encrypt.h @@ -0,0 +1,164 @@ +// Copyright 2015-2016 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. +#pragma once + +#include +#include "esp_attr.h" +#include "esp_err.h" +#ifndef BOOTLOADER_BUILD +#include "esp_spi_flash.h" +#endif +#include "soc/efuse_periph.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* @brief Flash encryption mode based on efuse values +*/ +typedef enum { + ESP_FLASH_ENC_MODE_DISABLED, // flash encryption is not enabled (flash crypt cnt=0) + ESP_FLASH_ENC_MODE_DEVELOPMENT, // flash encryption is enabled but for Development (reflash over UART allowed) + ESP_FLASH_ENC_MODE_RELEASE // flash encryption is enabled for Release (reflash over UART disabled) +} esp_flash_enc_mode_t; + +/** + * @file esp_partition.h + * @brief Support functions for flash encryption features + * + * Can be compiled as part of app or bootloader code. + */ + +/** @brief Is flash encryption currently enabled in hardware? + * + * Flash encryption is enabled if the FLASH_CRYPT_CNT efuse has an odd number of bits set. + * + * @return true if flash encryption is enabled. + */ +static inline /** @cond */ IRAM_ATTR /** @endcond */ bool esp_flash_encryption_enabled(void) +{ + uint32_t flash_crypt_cnt = 0; +#if CONFIG_IDF_TARGET_ESP32 + flash_crypt_cnt = REG_GET_FIELD(EFUSE_BLK0_RDATA0_REG, EFUSE_RD_FLASH_CRYPT_CNT); +#else + flash_crypt_cnt = REG_GET_FIELD(EFUSE_RD_REPEAT_DATA1_REG, EFUSE_SPI_BOOT_CRYPT_CNT); +#endif + /* __builtin_parity is in flash, so we calculate parity inline */ + bool enabled = false; + while (flash_crypt_cnt) { + if (flash_crypt_cnt & 1) { + enabled = !enabled; + } + flash_crypt_cnt >>= 1; + } + return enabled; +} + +/* @brief Update on-device flash encryption + * + * Intended to be called as part of the bootloader process if flash + * encryption is enabled in device menuconfig. + * + * If FLASH_CRYPT_CNT efuse parity is 1 (ie odd number of bits set), + * then return ESP_OK immediately (indicating flash encryption is enabled + * and functional). + * + * If FLASH_CRYPT_CNT efuse parity is 0 (ie even number of bits set), + * assume the flash has just been written with plaintext that needs encrypting. + * + * The following regions of flash are encrypted in place: + * + * - The bootloader image, if a valid plaintext image is found.[*] + * - The partition table, if a valid plaintext table is found. + * - Any app partition that contains a valid plaintext app image. + * - Any other partitions with the "encrypt" flag set. [**] + * + * After the re-encryption process completes, a '1' bit is added to the + * FLASH_CRYPT_CNT value (setting the parity to 1) and the EFUSE is re-burned. + * + * [*] If reflashing bootloader with secure boot enabled, pre-encrypt + * the bootloader before writing it to flash or secure boot will fail. + * + * [**] For this reason, if serial re-flashing a previous flashed + * device with secure boot enabled and using FLASH_CRYPT_CNT to + * trigger re-encryption, you must simultaneously re-flash plaintext + * content to all partitions with the "encrypt" flag set or this + * data will be corrupted (encrypted twice). + * + * @note The post-condition of this function is that all + * partitions that should be encrypted are encrypted. + * + * @note Take care not to power off the device while this function + * is running, or the partition currently being encrypted will be lost. + * + * @note RTC_WDT will reset while encryption operations will be performed (if RTC_WDT is configured). + * + * @return ESP_OK if all operations succeeded, ESP_ERR_INVALID_STATE + * if a fatal error occured during encryption of all partitions. + */ +esp_err_t esp_flash_encrypt_check_and_update(void); + + +/** @brief Encrypt-in-place a block of flash sectors + * + * @note This function resets RTC_WDT between operations with sectors. + * @param src_addr Source offset in flash. Should be multiple of 4096 bytes. + * @param data_length Length of data to encrypt in bytes. Will be rounded up to next multiple of 4096 bytes. + * + * @return ESP_OK if all operations succeeded, ESP_ERR_FLASH_OP_FAIL + * if SPI flash fails, ESP_ERR_FLASH_OP_TIMEOUT if flash times out. + */ +esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length); + +/** @brief Write protect FLASH_CRYPT_CNT + * + * Intended to be called as a part of boot process if flash encryption + * is enabled but secure boot is not used. This should protect against + * serial re-flashing of an unauthorised code in absence of secure boot. + * + * @note On ESP32 V3 only, write protecting FLASH_CRYPT_CNT will also prevent + * disabling UART Download Mode. If both are wanted, call + * esp_efuse_disable_rom_download_mode() before calling this function. + * + */ +void esp_flash_write_protect_crypt_cnt(void); + +/** @brief Return the flash encryption mode + * + * The API is called during boot process but can also be called by + * application to check the current flash encryption mode of ESP32 + * + * @return + */ +esp_flash_enc_mode_t esp_get_flash_encryption_mode(void); + + +/** @brief Check the flash encryption mode during startup + * + * @note This function is called automatically during app startup, + * it doesn't need to be called from the app. + * + * Verifies the flash encryption config during startup: + * + * - Correct any insecure flash encryption settings if hardware + * Secure Boot is enabled. + * - Log warnings if the efuse config doesn't match the project + * config in any way + */ +void esp_flash_encryption_init_checks(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_partitions.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_partitions.h new file mode 100644 index 00000000..1fc9d4f6 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_flash_partitions.h @@ -0,0 +1,113 @@ +// Copyright 2015-2016 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. +#pragma once + +#include "esp_err.h" +#include "esp_types.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_PARTITION_MAGIC 0x50AA +#define ESP_PARTITION_MAGIC_MD5 0xEBEB + +#define PART_TYPE_APP 0x00 +#define PART_SUBTYPE_FACTORY 0x00 +#define PART_SUBTYPE_OTA_FLAG 0x10 +#define PART_SUBTYPE_OTA_MASK 0x0f +#define PART_SUBTYPE_TEST 0x20 + +#define PART_TYPE_DATA 0x01 +#define PART_SUBTYPE_DATA_OTA 0x00 +#define PART_SUBTYPE_DATA_RF 0x01 +#define PART_SUBTYPE_DATA_WIFI 0x02 +#define PART_SUBTYPE_DATA_NVS_KEYS 0x04 +#define PART_SUBTYPE_DATA_EFUSE_EM 0x05 + +#define PART_TYPE_END 0xff +#define PART_SUBTYPE_END 0xff + +#define PART_FLAG_ENCRYPTED (1<<0) + +/* Pre-partition table fixed flash offsets */ +#define ESP_BOOTLOADER_DIGEST_OFFSET 0x0 +#define ESP_BOOTLOADER_OFFSET CONFIG_BOOTLOADER_OFFSET_IN_FLASH /* Offset of bootloader image. Has matching value in bootloader KConfig.projbuild file. */ +#define ESP_PARTITION_TABLE_OFFSET CONFIG_PARTITION_TABLE_OFFSET /* Offset of partition table. Backwards-compatible name.*/ + +#define ESP_PARTITION_TABLE_MAX_LEN 0xC00 /* Maximum length of partition table data */ +#define ESP_PARTITION_TABLE_MAX_ENTRIES (ESP_PARTITION_TABLE_MAX_LEN / sizeof(esp_partition_info_t)) /* Maximum length of partition table data, including terminating entry */ + +/// OTA_DATA states for checking operability of the app. +typedef enum { + ESP_OTA_IMG_NEW = 0x0U, /*!< Monitor the first boot. In bootloader this state is changed to ESP_OTA_IMG_PENDING_VERIFY. */ + ESP_OTA_IMG_PENDING_VERIFY = 0x1U, /*!< First boot for this app was. If while the second boot this state is then it will be changed to ABORTED. */ + ESP_OTA_IMG_VALID = 0x2U, /*!< App was confirmed as workable. App can boot and work without limits. */ + ESP_OTA_IMG_INVALID = 0x3U, /*!< App was confirmed as non-workable. This app will not selected to boot at all. */ + ESP_OTA_IMG_ABORTED = 0x4U, /*!< App could not confirm the workable or non-workable. In bootloader IMG_PENDING_VERIFY state will be changed to IMG_ABORTED. This app will not selected to boot at all. */ + ESP_OTA_IMG_UNDEFINED = 0xFFFFFFFFU, /*!< Undefined. App can boot and work without limits. */ +} esp_ota_img_states_t; + +/* OTA selection structure (two copies in the OTA data partition.) + Size of 32 bytes is friendly to flash encryption */ +typedef struct { + uint32_t ota_seq; + uint8_t seq_label[20]; + uint32_t ota_state; + uint32_t crc; /* CRC32 of ota_seq field only */ +} esp_ota_select_entry_t; + + +typedef struct { + uint32_t offset; + uint32_t size; +} esp_partition_pos_t; + +/* Structure which describes the layout of partition table entry. + * See docs/partition_tables.rst for more information about individual fields. + */ +typedef struct { + uint16_t magic; + uint8_t type; + uint8_t subtype; + esp_partition_pos_t pos; + uint8_t label[16]; + uint32_t flags; +} esp_partition_info_t; + +/* @brief Verify the partition table + * + * @param partition_table Pointer to at least ESP_PARTITION_TABLE_MAX_ENTRIES of potential partition table data. (ESP_PARTITION_TABLE_MAX_LEN bytes.) + * @param log_errors Log errors if the partition table is invalid. + * @param num_partitions If result is ESP_OK, num_partitions is updated with total number of partitions (not including terminating entry). + * + * @return ESP_OK on success, ESP_ERR_INVALID_STATE if partition table is not valid. + */ +esp_err_t esp_partition_table_verify(const esp_partition_info_t *partition_table, bool log_errors, int *num_partitions); + + +/** + * Check whether the region on the main flash is safe to write. + * + * @param addr Start address of the region + * @param size Size of the region + * + * @return true if the region is safe to write, otherwise false. + */ +bool esp_partition_main_flash_region_safe(size_t addr, size_t size); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_image_format.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_image_format.h new file mode 100644 index 00000000..7e7e6a28 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_image_format.h @@ -0,0 +1,206 @@ +// Copyright 2015-2016 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. +#pragma once + +#include +#include +#include "esp_flash_partitions.h" +#include "esp_app_format.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_ERR_IMAGE_BASE 0x2000 +#define ESP_ERR_IMAGE_FLASH_FAIL (ESP_ERR_IMAGE_BASE + 1) +#define ESP_ERR_IMAGE_INVALID (ESP_ERR_IMAGE_BASE + 2) + +/* Support for app/bootloader image parsing + Can be compiled as part of app or bootloader code. +*/ + +#define ESP_IMAGE_HASH_LEN 32 /* Length of the appended SHA-256 digest */ + +/* Structure to hold on-flash image metadata */ +typedef struct { + uint32_t start_addr; /* Start address of image */ + esp_image_header_t image; /* Header for entire image */ + esp_image_segment_header_t segments[ESP_IMAGE_MAX_SEGMENTS]; /* Per-segment header data */ + uint32_t segment_data[ESP_IMAGE_MAX_SEGMENTS]; /* Data offsets for each segment */ + uint32_t image_len; /* Length of image on flash, in bytes */ + uint8_t image_digest[32]; /* appended SHA-256 digest */ +} esp_image_metadata_t; + +typedef enum { + ESP_IMAGE_VERIFY, /* Verify image contents, not load to memory, load metadata. Print errors. */ + ESP_IMAGE_VERIFY_SILENT, /* Verify image contents, not load to memory, load metadata. Don't print errors. */ +#ifdef BOOTLOADER_BUILD + ESP_IMAGE_LOAD, /* Verify image contents, load to memory, load metadata. Print errors. */ + ESP_IMAGE_LOAD_NO_VALIDATE, /* Not verify image contents, load to memory, load metadata. Print errors. */ +#endif +} esp_image_load_mode_t; + +typedef struct { + esp_partition_pos_t partition; /*!< Partition of application which worked before goes to the deep sleep. */ + uint16_t reboot_counter; /*!< Reboot counter. Reset only when power is off. */ + uint16_t reserve; /*!< Reserve */ +#ifdef CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC + uint8_t custom[CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE]; /*!< Reserve for custom propose */ +#endif + uint32_t crc; /*!< Check sum crc32 */ +} rtc_retain_mem_t; + +#ifdef CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC +_Static_assert(CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE % 4 == 0, "CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE must be a multiple of 4 bytes"); +#endif + +#if defined(CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP) || defined(CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC) +_Static_assert(CONFIG_BOOTLOADER_RESERVE_RTC_SIZE % 4 == 0, "CONFIG_BOOTLOADER_RESERVE_RTC_SIZE must be a multiple of 4 bytes"); +#endif + +#ifdef CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC +#define ESP_BOOTLOADER_RESERVE_RTC (CONFIG_BOOTLOADER_RESERVE_RTC_SIZE + CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC_SIZE) +#elif defined(CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP) +#define ESP_BOOTLOADER_RESERVE_RTC (CONFIG_BOOTLOADER_RESERVE_RTC_SIZE) +#endif + +#if defined(CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP) || defined(CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC) +_Static_assert(sizeof(rtc_retain_mem_t) <= ESP_BOOTLOADER_RESERVE_RTC, "Reserved RTC area must exceed size of rtc_retain_mem_t"); +#endif + +/** + * @brief Verify an app image. + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param mode Mode of operation (verify, silent verify, or load). + * @param part Partition to load the app from. + * @param[inout] data Pointer to the image metadata structure which is be filled in by this function. + * 'start_addr' member should be set (to the start address of the image.) + * Other fields will all be initialised by this function. + * + * Image validation checks: + * - Magic byte. + * - Partition smaller than 16MB. + * - All segments & image fit in partition. + * - 8 bit image checksum is valid. + * - SHA-256 of image is valid (if image has this appended). + * - (Signature) if signature verification is enabled. + * + * @return + * - ESP_OK if verify or load was successful + * - ESP_ERR_IMAGE_FLASH_FAIL if a SPI flash error occurs + * - ESP_ERR_IMAGE_INVALID if the image appears invalid. + * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. + */ +esp_err_t esp_image_verify(esp_image_load_mode_t mode, const esp_partition_pos_t *part, esp_image_metadata_t *data); + +/** + * @brief Get metadata of app + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param part Partition to load the app from. + * @param[out] metadata Pointer to the image metadata structure which is be filled in by this function. + * Fields will all be initialised by this function. + * + * @return + * - ESP_OK if filling of metadata was successful + */ +esp_err_t esp_image_get_metadata(const esp_partition_pos_t *part, esp_image_metadata_t *metadata); + +/** + * @brief Verify and load an app image (available only in space of bootloader). + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param part Partition to load the app from. + * @param[inout] data Pointer to the image metadata structure which is be filled in by this function. + * 'start_addr' member should be set (to the start address of the image.) + * Other fields will all be initialised by this function. + * + * Image validation checks: + * - Magic byte. + * - Partition smaller than 16MB. + * - All segments & image fit in partition. + * - 8 bit image checksum is valid. + * - SHA-256 of image is valid (if image has this appended). + * - (Signature) if signature verification is enabled. + * + * @return + * - ESP_OK if verify or load was successful + * - ESP_ERR_IMAGE_FLASH_FAIL if a SPI flash error occurs + * - ESP_ERR_IMAGE_INVALID if the image appears invalid. + * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. + */ +esp_err_t bootloader_load_image(const esp_partition_pos_t *part, esp_image_metadata_t *data); + +/** + * @brief Load an app image without verification (available only in space of bootloader). + * + * If encryption is enabled, data will be transparently decrypted. + * + * @param part Partition to load the app from. + * @param[inout] data Pointer to the image metadata structure which is be filled in by this function. + * 'start_addr' member should be set (to the start address of the image.) + * Other fields will all be initialised by this function. + * + * @return + * - ESP_OK if verify or load was successful + * - ESP_ERR_IMAGE_FLASH_FAIL if a SPI flash error occurs + * - ESP_ERR_IMAGE_INVALID if the image appears invalid. + * - ESP_ERR_INVALID_ARG if the partition or data pointers are invalid. + */ +esp_err_t bootloader_load_image_no_verify(const esp_partition_pos_t *part, esp_image_metadata_t *data); + +/** + * @brief Verify the bootloader image. + * + * @param[out] If result is ESP_OK and this pointer is non-NULL, it + * will be set to the length of the bootloader image. + * + * @return As per esp_image_load_metadata(). + */ +esp_err_t esp_image_verify_bootloader(uint32_t *length); + +/** + * @brief Verify the bootloader image. + * + * @param[out] Metadata for the image. Only valid if result is ESP_OK. + * + * @return As per esp_image_load_metadata(). + */ +esp_err_t esp_image_verify_bootloader_data(esp_image_metadata_t *data); + +/** + * @brief Get the flash size of the image + * + * @param app_flash_size The value configured in the image header + * @return Actual size, in bytes. + */ +int esp_image_get_flash_size(esp_image_flash_size_t app_flash_size); + + +typedef struct { + uint32_t drom_addr; + uint32_t drom_load_addr; + uint32_t drom_size; + uint32_t irom_addr; + uint32_t irom_load_addr; + uint32_t irom_size; +} esp_image_flash_mapping_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bootloader_support/include/esp_secure_boot.h b/tools/sdk/esp32c3/include/bootloader_support/include/esp_secure_boot.h new file mode 100644 index 00000000..94118c32 --- /dev/null +++ b/tools/sdk/esp32c3/include/bootloader_support/include/esp_secure_boot.h @@ -0,0 +1,276 @@ +// Copyright 2015-2016 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. +#pragma once + +#include +#include +#include "soc/efuse_periph.h" +#include "esp_image_format.h" +#include "esp_rom_efuse.h" +#include "sdkconfig.h" +#include "esp_rom_crc.h" + +#if CONFIG_IDF_TARGET_ESP32 +#include "esp32/rom/efuse.h" +#include "esp32/rom/secure_boot.h" +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/rom/efuse.h" +#include "esp32s2/rom/secure_boot.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/efuse.h" +#include "esp32c3/rom/secure_boot.h" +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/rom/efuse.h" +#include "esp32s3/rom/secure_boot.h" +#endif + +#ifdef CONFIG_SECURE_BOOT_V1_ENABLED +#if !defined(CONFIG_SECURE_SIGNED_ON_BOOT) || !defined(CONFIG_SECURE_SIGNED_ON_UPDATE) || !defined(CONFIG_SECURE_SIGNED_APPS) +#error "internal sdkconfig error, secure boot should always enable all signature options" +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* Support functions for secure boot features. + + Can be compiled as part of app or bootloader code. +*/ + +#define ESP_SECURE_BOOT_DIGEST_LEN 32 + +/** @brief Is secure boot currently enabled in hardware? + * + * This means that the ROM bootloader code will only boot + * a verified secure bootloader from now on. + * + * @return true if secure boot is enabled. + */ +static inline bool esp_secure_boot_enabled(void) +{ +#if CONFIG_IDF_TARGET_ESP32 + #ifdef CONFIG_SECURE_BOOT_V1_ENABLED + return REG_READ(EFUSE_BLK0_RDATA6_REG) & EFUSE_RD_ABS_DONE_0; + #elif CONFIG_SECURE_BOOT_V2_ENABLED + return ets_use_secure_boot_v2(); + #endif +#else + return esp_rom_efuse_is_secure_boot_enabled(); +#endif + return false; /* Secure Boot not enabled in menuconfig */ +} + +/** @brief Generate secure digest from bootloader image + * + * @important This function is intended to be called from bootloader code only. + * + * This function is only used in the context of the Secure Boot V1 scheme. + * + * If secure boot is not yet enabled for bootloader, this will: + * 1) generate the secure boot key and burn it on EFUSE + * (without enabling R/W protection) + * 2) generate the digest from bootloader and save it + * to flash address 0x0 + * + * If first boot gets interrupted after calling this function + * but before esp_secure_boot_permanently_enable() is called, then + * the key burned on EFUSE will not be regenerated, unless manually + * done using espefuse.py tool + * + * @return ESP_OK if secure boot digest is generated + * successfully or found to be already present + */ +esp_err_t esp_secure_boot_generate_digest(void); + +/** @brief Enable secure boot V1 if it is not already enabled. + * + * @important If this function succeeds, secure boot V1 is permanently + * enabled on the chip via efuse. + * + * @important This function is intended to be called from bootloader code only. + * + * @important In case of Secure Boot V1, this will enable r/w protection + * of secure boot key on EFUSE, therefore it is to be ensured that + * esp_secure_boot_generate_digest() is called before this .If secure boot is not + * yet enabled for bootloader, this will + * 1) enable R/W protection of secure boot key on EFUSE + * 2) enable secure boot by blowing the EFUSE_RD_ABS_DONE_0 efuse. + * + * This function does not verify secure boot of the bootloader (the + * ROM bootloader does this.) + * + * Will fail if efuses have been part-burned in a way that indicates + * secure boot should not or could not be correctly enabled. + * + * @return ESP_ERR_INVALID_STATE if efuse state doesn't allow + * secure boot to be enabled cleanly. ESP_OK if secure boot + * is enabled on this chip from now on. + */ +esp_err_t esp_secure_boot_permanently_enable(void); + +/** @brief Enables secure boot V2 if it is not already enabled. + * + * @important If this function succeeds, secure boot V2 is permanently + * enabled on the chip via efuse. + * + * @important This function is intended to be called from bootloader code only. + * + * @important In case of Secure Boot V2, this will enable write protection + * of secure boot key on EFUSE in BLK2. .If secure boot is not + * yet enabled for bootloader, this will + * 1) enable W protection of secure boot key on EFUSE + * 2) enable secure boot by blowing the EFUSE_RD_ABS_DONE_1 efuse. + * + * This function does not verify secure boot of the bootloader (the + * ROM bootloader does this.) + * + * @param image_data Image metadata of the application to be loaded. + * + * Will fail if efuses have been part-burned in a way that indicates + * secure boot should not or could not be correctly enabled. + * + * @return ESP_ERR_INVALID_STATE if efuse state doesn't allow + * secure boot to be enabled cleanly. ESP_OK if secure boot + * is enabled on this chip from now on. + */ +esp_err_t esp_secure_boot_v2_permanently_enable(const esp_image_metadata_t *image_data); + +/** @brief Verify the secure boot signature appended to some binary data in flash. + * + * For ECDSA Scheme (Secure Boot V1) - deterministic ECDSA w/ SHA256 image + * For RSA Scheme (Secure Boot V2) - RSA-PSS Verification of the SHA-256 image + * + * Public key is compiled into the calling program in the ECDSA Scheme. + * See the apt docs/security/secure-boot-v1.rst or docs/security/secure-boot-v2.rst for details. + * + * @param src_addr Starting offset of the data in flash. + * @param length Length of data in bytes. Signature is appended -after- length bytes. + * + * If flash encryption is enabled, the image will be transparently decrypted while being verified. + * + * @note This function doesn't have any fault injection resistance so should not be called + * during a secure boot itself (but can be called when verifying an update, etc.) + * + * @return ESP_OK if signature is valid, ESP_ERR_INVALID_STATE if + * signature fails, ESP_FAIL for other failures (ie can't read flash). + */ +esp_err_t esp_secure_boot_verify_signature(uint32_t src_addr, uint32_t length); + +/** @brief Secure boot verification block, on-flash data format. */ +typedef struct { + uint32_t version; + uint8_t signature[64]; +} esp_secure_boot_sig_block_t; + +/** @brief Verify the ECDSA secure boot signature block for Secure Boot V1. + * + * Calculates Deterministic ECDSA w/ SHA256 based on the SHA256 hash of the image. ECDSA signature + * verification must be enabled in project configuration to use this function. + * + * Similar to esp_secure_boot_verify_signature(), but can be used when the digest is precalculated. + * @param sig_block Pointer to ECDSA signature block data + * @param image_digest Pointer to 32 byte buffer holding SHA-256 hash. + * @param verified_digest Pointer to 32 byte buffer that will receive verified digest if verification completes. (Used during bootloader implementation only, result is invalid otherwise.) + * + */ +esp_err_t esp_secure_boot_verify_ecdsa_signature_block(const esp_secure_boot_sig_block_t *sig_block, const uint8_t *image_digest, uint8_t *verified_digest); + +#if !CONFIG_IDF_TARGET_ESP32 || CONFIG_ESP32_REV_MIN_3 +/** + * @brief Structure to hold public key digests calculated from the signature blocks of a single image. + * + * Each image can have one or more signature blocks (up to SECURE_BOOT_NUM_BLOCKS). Each signature block includes a public key. + */ +typedef struct { + uint8_t key_digests[SECURE_BOOT_NUM_BLOCKS][ESP_SECURE_BOOT_DIGEST_LEN]; /* SHA of the public key components in the signature block */ + unsigned num_digests; /* Number of valid digests, starting at index 0 */ +} esp_image_sig_public_key_digests_t; + +/** @brief Verify the RSA secure boot signature block for Secure Boot V2. + * + * Performs RSA-PSS Verification of the SHA-256 image based on the public key + * in the signature block, compared against the public key digest stored in efuse. + * + * Similar to esp_secure_boot_verify_signature(), but can be used when the digest is precalculated. + * @param sig_block Pointer to RSA signature block data + * @param image_digest Pointer to 32 byte buffer holding SHA-256 hash. + * @param verified_digest Pointer to 32 byte buffer that will receive verified digest if verification completes. (Used during bootloader implementation only, result is invalid otherwise.) + * + */ +esp_err_t esp_secure_boot_verify_rsa_signature_block(const ets_secure_boot_signature_t *sig_block, const uint8_t *image_digest, uint8_t *verified_digest); +#endif // !CONFIG_IDF_TARGET_ESP32 || CONFIG_ESP32_REV_MIN_3 + +/** @brief Legacy ECDSA verification function + * + * @note Deprecated, call either esp_secure_boot_verify_ecdsa_signature_block() or esp_secure_boot_verify_rsa_signature_block() instead. + * + * @param sig_block Pointer to ECDSA signature block data + * @param image_digest Pointer to 32 byte buffer holding SHA-256 hash. + */ +esp_err_t esp_secure_boot_verify_signature_block(const esp_secure_boot_sig_block_t *sig_block, const uint8_t *image_digest) + __attribute__((deprecated("use esp_secure_boot_verify_ecdsa_signature_block instead"))); + + +#define FLASH_OFFS_SECURE_BOOT_IV_DIGEST 0 + +/** @brief Secure boot IV+digest header */ +typedef struct { + uint8_t iv[128]; + uint8_t digest[64]; +} esp_secure_boot_iv_digest_t; + +/** @brief Check the secure boot V2 during startup + * + * @note This function is called automatically during app startup, + * it doesn't need to be called from the app. + * + * Verifies the secure boot config during startup: + * + * - Correct any insecure secure boot settings + */ +void esp_secure_boot_init_checks(void); + +#if !BOOTLOADER_BUILD && CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME + +/** @brief Scan the current running app for signature blocks + * + * @note This function doesn't verify that the signatures are valid or the + * corresponding public keys are trusted, it only reads the number of signature + * blocks present and optionally calculates the digests of the public keys + * provided in the signature blocks. + * + * @param digest_public_keys If true, the key_digests fields in the + * public_key_digests structure will be filled with the digests of the public + * key provided in each signature block. Note that if Secure Boot V2 is enabled, + * each public key will only be trusted if the same digest is also present in + * eFuse (but this is not checked by this function). + * + * @param public_key_digests[out] Structure is initialized with the num_digests + * field set to the number of signatures found. If digest_public_keys is set, + * the public key digests are also calculated and stored here. + * + * @return + * - ESP_OK - At least one signature was found + * - ESP_ERR_NOT_FOUND - No signatures were found, num_digests value will be zero + * - ESP_FAIL - An error occured trying to read the signature blocks from flash + */ +esp_err_t esp_secure_boot_get_signature_blocks_for_running_app(bool digest_public_keys, esp_image_sig_public_key_digests_t *public_key_digests); + +#endif // !BOOTLOADER_BUILD && CONFIG_SECURE_SIGNED_APPS_RSA_SCHEME + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/alarm.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/alarm.h new file mode 100644 index 00000000..a1d3fa89 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/alarm.h @@ -0,0 +1,80 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _ALARM_H_ +#define _ALARM_H_ + +#include +#include "esp_timer.h" + +typedef struct alarm_t osi_alarm_t; +typedef uint64_t period_ms_t; +typedef esp_timer_cb_t osi_alarm_callback_t; + +typedef enum { + OSI_ALARM_ERR_PASS = 0, + OSI_ALARM_ERR_FAIL = -1, + OSI_ALARM_ERR_INVALID_ARG = -2, + OSI_ALARM_ERR_INVALID_STATE = -3, +} osi_alarm_err_t; + +#define ALARM_CBS_NUM 50 +#define ALARM_ID_BASE 1000 + +int osi_alarm_create_mux(void); +int osi_alarm_delete_mux(void); +void osi_alarm_init(void); +void osi_alarm_deinit(void); + +// Creates a new alarm object. The returned object must be freed by calling +// |alarm_free|. Returns NULL on failure. +osi_alarm_t *osi_alarm_new(const char *alarm_name, osi_alarm_callback_t callback, void *data, period_ms_t timer_expire); + +// Frees an alarm object created by |alarm_new|. |alarm| may be NULL. If the +// alarm is pending, it will be cancelled. It is not safe to call |alarm_free| +// from inside the callback of |alarm|. +void osi_alarm_free(osi_alarm_t *alarm); + +// Sets an alarm to fire |cb| after the given |deadline|. Note that |deadline| is the +// number of milliseconds relative to the current time. |data| is a context variable +// for the callback and may be NULL. |cb| will be called back in the context of an +// unspecified thread (i.e. it will not be called back in the same thread as the caller). +// |alarm| and |cb| may not be NULL. +osi_alarm_err_t osi_alarm_set(osi_alarm_t *alarm, period_ms_t timeout); + +// Sets an periodic alarm to fire |cb| each given |period|. +osi_alarm_err_t osi_alarm_set_periodic(osi_alarm_t *alarm, period_ms_t period); + +// This function cancels the |alarm| if it was previously set. When this call +// returns, the caller has a guarantee that the callback is not in progress and +// will not be called if it hasn't already been called. This function is idempotent. +// |alarm| may not be NULL. +osi_alarm_err_t osi_alarm_cancel(osi_alarm_t *alarm); + +// Figure out how much time until next expiration. +// Returns 0 if not armed. |alarm| may not be NULL. +// only for oneshot alarm, not for periodic alarm +// TODO: Remove this function once PM timers can be re-factored +period_ms_t osi_alarm_get_remaining_ms(const osi_alarm_t *alarm); + +// Alarm-related state cleanup +//void alarm_cleanup(void); + +uint32_t osi_time_get_os_boottime_ms(void); + +#endif /*_ALARM_H_*/ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/allocator.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/allocator.h new file mode 100644 index 00000000..579f2b2b --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/allocator.h @@ -0,0 +1,145 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _ALLOCATOR_H_ +#define _ALLOCATOR_H_ + +#include +#include +#include "esp_heap_caps.h" + +char *osi_strdup(const char *str); + +void *osi_malloc_func(size_t size); +void *osi_calloc_func(size_t size); +void osi_free_func(void *ptr); + +#if HEAP_MEMORY_DEBUG + +void osi_mem_dbg_init(void); +void osi_mem_dbg_record(void *p, int size, const char *func, int line); +void osi_mem_dbg_clean(void *p, const char *func, int line); +void osi_mem_dbg_show(void); +uint32_t osi_mem_dbg_get_max_size(void); +uint32_t osi_mem_dbg_get_current_size(void); +void osi_men_dbg_set_section_start(uint8_t index); +void osi_men_dbg_set_section_end(uint8_t index); +uint32_t osi_mem_dbg_get_max_size_section(uint8_t index); + +#if HEAP_ALLOCATION_FROM_SPIRAM_FIRST +#define osi_malloc(size) \ +({ \ + void *p; \ + p = heap_caps_malloc_prefer(size, 2, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL); \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +}) + +#define osi_calloc(size) \ +({ \ + void *p; \ + p = heap_caps_calloc_prefer(1, size, 2, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL); \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +}) + +#else + +#define osi_malloc(size) \ +({ \ + void *p; \ + p = malloc((size)); \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +}) + +#define osi_calloc(size) \ +({ \ + void *p; \ + p = calloc(1, (size)); \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +}) + +#endif /* #if HEAP_ALLOCATION_FROM_SPIRAM_FIRST */ + + +#if 0 +#define osi_malloc(size) \ +do { \ + void *p; \ + \ +#if HEAP_ALLOCATION_FROM_SPIRAM_FIRST \ + p = heap_caps_malloc_prefer(size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL); \ +#else \ + p = malloc((size)); \ +#endif /* #if HEAP_ALLOCATION_FROM_SPIRAM_FIRST */ \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +}while(0) + +#define osi_calloc(size) \ +do { \ + void *p; \ + \ +#if HEAP_ALLOCATION_FROM_SPIRAM_FIRST \ + p = heap_caps_calloc_prefer(1, size, 2, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, \ + MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL); \ +#else \ + p = calloc(1, (size)); \ +#endif /* #if HEAP_ALLOCATION_FROM_SPIRAM_FIRST */ \ + osi_mem_dbg_record(p, size, __func__, __LINE__); \ + (void *)p; \ +} while(0) +#endif + +#define osi_free(ptr) \ +do { \ + void *tmp_point = (void *)(ptr); \ + osi_mem_dbg_clean(tmp_point, __func__, __LINE__); \ + free(tmp_point); \ +} while (0) + +#else + +#if HEAP_ALLOCATION_FROM_SPIRAM_FIRST +#define osi_malloc(size) heap_caps_malloc_prefer(size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL) +#define osi_calloc(size) heap_caps_calloc_prefer(1, size, 2, MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM, MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL) +#else +#define osi_malloc(size) malloc((size)) +#define osi_calloc(size) calloc(1, (size)) +#endif /* #if HEAP_ALLOCATION_FROM_SPIRAM_FIRST */ +#define osi_free(p) free((p)) + +#endif /* HEAP_MEMORY_DEBUG */ + +#define FREE_AND_RESET(a) \ +do { \ + if (a) { \ + osi_free(a); \ + a = NULL; \ + } \ +}while (0) + + +#endif /* _ALLOCATOR_H_ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/buffer.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/buffer.h new file mode 100644 index 00000000..fd1b2fa3 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/buffer.h @@ -0,0 +1,59 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _BUFFER_H_ +#define _BUFFER_H_ + +#include +#include + +typedef struct buffer_t buffer_t; + +// Returns a new buffer of |size| bytes. Returns NULL if a buffer could not be +// allocated. |size| must be non-zero. The caller must release this buffer with +// |buffer_free|. +buffer_t *buffer_new(size_t size); + +// Creates a new reference to the buffer |buf|. A reference is indistinguishable +// from the original: writes to the original will be reflected in the reference +// and vice versa. In other words, this function creates an alias to |buf|. The +// caller must release the returned buffer with |buffer_free|. Note that releasing +// the returned buffer does not release |buf|. |buf| must not be NULL. +buffer_t *buffer_new_ref(const buffer_t *buf); + +// Creates a new reference to the last |slice_size| bytes of |buf|. See +// |buffer_new_ref| for a description of references. |slice_size| must be +// greater than 0 and may be at most |buffer_length| +// (0 < slice_size <= buffer_length). |buf| must not be NULL. +buffer_t *buffer_new_slice(const buffer_t *buf, size_t slice_size); + +// Frees a buffer object. |buf| may be NULL. +void buffer_free(buffer_t *buf); + +// Returns a pointer to a writeable memory region for |buf|. All references +// and slices that share overlapping bytes will also be written to when +// writing to the returned pointer. The caller may safely write up to +// |buffer_length| consecutive bytes starting at the address returned by +// this function. |buf| must not be NULL. +void *buffer_ptr(const buffer_t *buf); + +// Returns the length of the writeable memory region referred to by |buf|. +// |buf| must not be NULL. +size_t buffer_length(const buffer_t *buf); + +#endif /*_BUFFER_H_*/ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/config.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/config.h new file mode 100644 index 00000000..c1a2f3d5 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/config.h @@ -0,0 +1,148 @@ +// Copyright 2015-2016 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. + +#ifndef __CONFIG_H__ +#define __CONFIG_H__ + +// This module implements a configuration parser. Clients can query the +// contents of a configuration file through the interface provided here. +// The current implementation is read-only; mutations are only kept in +// memory. This parser supports the INI file format. + +// Implementation notes: +// - Key/value pairs that are not within a section are assumed to be under +// the |CONFIG_DEFAULT_SECTION| section. +// - Multiple sections with the same name will be merged as if they were in +// a single section. +// - Empty sections with no key/value pairs will be treated as if they do +// not exist. In other words, |config_has_section| will return false for +// empty sections. +// - Duplicate keys in a section will overwrite previous values. +// - All strings are case sensitive. + +#include + +// The default section name to use if a key/value pair is not defined within +// a section. +#define CONFIG_DEFAULT_SECTION "Global" + +typedef struct config_t config_t; +typedef struct config_section_node_t config_section_node_t; + +// Creates a new config object with no entries (i.e. not backed by a file). +// This function returns a config object or NULL on error. Clients must call +// |config_free| on the returned handle when it is no longer required. +config_t *config_new_empty(void); + +// Loads the specified file and returns a handle to the config file. If there +// was a problem loading the file or allocating memory, this function returns +// NULL. Clients must call |config_free| on the returned handle when it is no +// longer required. |filename| must not be NULL and must point to a readable +// file on the filesystem. +config_t *config_new(const char *filename); + +// Frees resources associated with the config file. No further operations may +// be performed on the |config| object after calling this function. |config| +// may be NULL. +void config_free(config_t *config); + +// Returns true if the config file contains a section named |section|. If +// the section has no key/value pairs in it, this function will return false. +// |config| and |section| must not be NULL. +bool config_has_section(const config_t *config, const char *section); + +// Returns true if the config file has a key named |key| under |section|. +// Returns false otherwise. |config|, |section|, and |key| must not be NULL. +bool config_has_key(const config_t *config, const char *section, const char *key); + +// Returns true if the config file has a key named |key| and the key_value. +// Returns false otherwise. |config|, |key|, and |key_value| must not be NULL. +bool config_has_key_in_section(config_t *config, const char *key, char *key_value); + +// Returns the integral value for a given |key| in |section|. If |section| +// or |key| do not exist, or the value cannot be fully converted to an integer, +// this function returns |def_value|. |config|, |section|, and |key| must not +// be NULL. +int config_get_int(const config_t *config, const char *section, const char *key, int def_value); + +// Returns the boolean value for a given |key| in |section|. If |section| +// or |key| do not exist, or the value cannot be converted to a boolean, this +// function returns |def_value|. |config|, |section|, and |key| must not be NULL. +bool config_get_bool(const config_t *config, const char *section, const char *key, bool def_value); + +// Returns the string value for a given |key| in |section|. If |section| or +// |key| do not exist, this function returns |def_value|. The returned string +// is owned by the config module and must not be freed. |config|, |section|, +// and |key| must not be NULL. |def_value| may be NULL. +const char *config_get_string(const config_t *config, const char *section, const char *key, const char *def_value); + +// Sets an integral value for the |key| in |section|. If |key| or |section| do +// not already exist, this function creates them. |config|, |section|, and |key| +// must not be NULL. +void config_set_int(config_t *config, const char *section, const char *key, int value); + +// Sets a boolean value for the |key| in |section|. If |key| or |section| do +// not already exist, this function creates them. |config|, |section|, and |key| +// must not be NULL. +void config_set_bool(config_t *config, const char *section, const char *key, bool value); + +// Sets a string value for the |key| in |section|. If |key| or |section| do +// not already exist, this function creates them. |config|, |section|, |key|, and +// |value| must not be NULL. +void config_set_string(config_t *config, const char *section, const char *key, const char *value, bool insert_back); + +// Removes |section| from the |config| (and, as a result, all keys in the section). +// Returns true if |section| was found and removed from |config|, false otherwise. +// Neither |config| nor |section| may be NULL. +bool config_remove_section(config_t *config, const char *section); + +// Removes one specific |key| residing in |section| of the |config|. Returns true +// if the section and key were found and the key was removed, false otherwise. +// None of |config|, |section|, or |key| may be NULL. +bool config_remove_key(config_t *config, const char *section, const char *key); + +// Returns an iterator to the first section in the config file. If there are no +// sections, the iterator will equal the return value of |config_section_end|. +// The returned pointer must be treated as an opaque handle and must not be freed. +// The iterator is invalidated on any config mutating operation. |config| may not +// be NULL. +const config_section_node_t *config_section_begin(const config_t *config); + +// Returns an iterator to one past the last section in the config file. It does not +// represent a valid section, but can be used to determine if all sections have been +// iterated over. The returned pointer must be treated as an opaque handle and must +// not be freed and must not be iterated on (must not call |config_section_next| on +// it). |config| may not be NULL. +const config_section_node_t *config_section_end(const config_t *config); + +// Moves |iter| to the next section. If there are no more sections, |iter| will +// equal the value of |config_section_end|. |iter| may not be NULL and must be +// a pointer returned by either |config_section_begin| or |config_section_next|. +const config_section_node_t *config_section_next(const config_section_node_t *iter); + +// Returns the name of the section referred to by |iter|. The returned pointer is +// owned by the config module and must not be freed by the caller. The pointer will +// remain valid until |config_free| is called. |iter| may not be NULL and must not +// equal the value returned by |config_section_end|. +const char *config_section_name(const config_section_node_t *iter); + +// Saves |config| to a file given by |filename|. Note that this could be a destructive +// operation: if |filename| already exists, it will be overwritten. The config +// module does not preserve comments or formatting so if a config file was opened +// with |config_new| and subsequently overwritten with |config_save|, all comments +// and special formatting in the original file will be lost. Neither |config| nor +// |filename| may be NULL. +bool config_save(const config_t *config, const char *filename); + +#endif /* #ifndef __CONFIG_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/fixed_queue.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/fixed_queue.h new file mode 100644 index 00000000..a25e6039 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/fixed_queue.h @@ -0,0 +1,125 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _FIXED_QUEUE_H_ +#define _FIXED_QUEUE_H_ + +#include +#include "osi/list.h" +#include "osi/semaphore.h" + +#ifndef QUEUE_SIZE_MAX +#define QUEUE_SIZE_MAX 254 +#endif + +#define FIXED_QUEUE_MAX_TIMEOUT OSI_SEM_MAX_TIMEOUT + +struct fixed_queue_t; + +typedef struct fixed_queue_t fixed_queue_t; +//typedef struct reactor_t reactor_t; + +typedef void (*fixed_queue_free_cb)(void *data); +typedef void (*fixed_queue_cb)(fixed_queue_t *queue); + +// Creates a new fixed queue with the given |capacity|. If more elements than +// |capacity| are added to the queue, the caller is blocked until space is +// made available in the queue. Returns NULL on failure. The caller must free +// the returned queue with |fixed_queue_free|. +fixed_queue_t *fixed_queue_new(size_t capacity); + +// Freeing a queue that is currently in use (i.e. has waiters +// blocked on it) results in undefined behaviour. +void fixed_queue_free(fixed_queue_t *queue, fixed_queue_free_cb free_cb); + +// Returns a value indicating whether the given |queue| is empty. If |queue| +// is NULL, the return value is true. +bool fixed_queue_is_empty(fixed_queue_t *queue); + +// Returns the length of the |queue|. If |queue| is NULL, the return value +// is 0. +size_t fixed_queue_length(fixed_queue_t *queue); + +// Returns the maximum number of elements this queue may hold. |queue| may +// not be NULL. +size_t fixed_queue_capacity(fixed_queue_t *queue); + +// Enqueues the given |data| into the |queue|. The caller will be blocked or immediately return or wait for timeout according to the parameter timeout. +// If enqueue failed, it will return false, otherwise return true +bool fixed_queue_enqueue(fixed_queue_t *queue, void *data, uint32_t timeout); + +// Dequeues the next element from |queue|. If the queue is currently empty, +// this function will block the caller until an item is enqueued or immediately return or wait for timeout according to the parameter timeout. +// If dequeue failed, it will return NULL, otherwise return a point. +void *fixed_queue_dequeue(fixed_queue_t *queue, uint32_t timeout); + +// Returns the first element from |queue|, if present, without dequeuing it. +// This function will never block the caller. Returns NULL if there are no +// elements in the queue or |queue| is NULL. +void *fixed_queue_try_peek_first(fixed_queue_t *queue); + +// Returns the last element from |queue|, if present, without dequeuing it. +// This function will never block the caller. Returns NULL if there are no +// elements in the queue or |queue| is NULL. +void *fixed_queue_try_peek_last(fixed_queue_t *queue); + +// Tries to remove a |data| element from the middle of the |queue|. This +// function will never block the caller. If the queue is empty or NULL, this +// function returns NULL immediately. |data| may not be NULL. If the |data| +// element is found in the queue, a pointer to the removed data is returned, +// otherwise NULL. +void *fixed_queue_try_remove_from_queue(fixed_queue_t *queue, void *data); + +// Returns the iterateable list with all entries in the |queue|. This function +// will never block the caller. |queue| may not be NULL. +// +// NOTE: The return result of this function is not thread safe: the list could +// be modified by another thread, and the result would be unpredictable. +// TODO: The usage of this function should be refactored, and the function +// itself should be removed. +list_t *fixed_queue_get_list(fixed_queue_t *queue); + +// This function returns a valid file descriptor. Callers may perform one +// operation on the fd: select(2). If |select| indicates that the file +// descriptor is readable, the caller may call |fixed_queue_enqueue| without +// blocking. The caller must not close the returned file descriptor. |queue| +// may not be NULL. +//int fixed_queue_get_enqueue_fd(const fixed_queue_t *queue); + +// This function returns a valid file descriptor. Callers may perform one +// operation on the fd: select(2). If |select| indicates that the file +// descriptor is readable, the caller may call |fixed_queue_dequeue| without +// blocking. The caller must not close the returned file descriptor. |queue| +// may not be NULL. +//int fixed_queue_get_dequeue_fd(const fixed_queue_t *queue); + +// Registers |queue| with |reactor| for dequeue operations. When there is an element +// in the queue, ready_cb will be called. The |context| parameter is passed, untouched, +// to the callback routine. Neither |queue|, nor |reactor|, nor |read_cb| may be NULL. +// |context| may be NULL. +void fixed_queue_register_dequeue(fixed_queue_t *queue, fixed_queue_cb ready_cb); + +// Unregisters the dequeue ready callback for |queue| from whichever reactor +// it is registered with, if any. This function is idempotent. +void fixed_queue_unregister_dequeue(fixed_queue_t *queue); + +void fixed_queue_process(fixed_queue_t *queue); + +list_t *fixed_queue_get_list(fixed_queue_t *queue); + +#endif diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/future.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/future.h new file mode 100644 index 00000000..9d1cb521 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/future.h @@ -0,0 +1,53 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef __FUTURE_H__ +#define __FUTURE_H__ + +#include "osi/semaphore.h" + +struct future { + bool ready_can_be_called; + osi_sem_t semaphore; // NULL semaphore means immediate future + void *result; +}; +typedef struct future future_t; + +#define FUTURE_SUCCESS ((void *)1) +#define FUTURE_FAIL ((void *)0) + +// Constructs a new future_t object. Returns NULL on failure. +future_t *future_new(void); + +// Constructs a new future_t object with an immediate |value|. No waiting will +// occur in the call to |future_await| because the value is already present. +// Returns NULL on failure. +future_t *future_new_immediate(void *value); + +// Signals that the |future| is ready, passing |value| back to the context +// waiting for the result. Must only be called once for every future. +// |future| may not be NULL. +void future_ready(future_t *future, void *value); + +// Waits for the |future| to be ready. Returns the value set in |future_ready|. +// Frees the future before return. |future| may not be NULL. +void *future_await(future_t *async_result); + +//Free the future if this "future" is not used +void future_free(future_t *future); +#endif /* __FUTURE_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_functions.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_functions.h new file mode 100644 index 00000000..8102a0c1 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_functions.h @@ -0,0 +1,37 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _HASH_FUNCTIONS_H_ +#define _HASH_FUNCTIONS_H_ + +#include "osi/hash_map.h" + +typedef unsigned char hash_key_t[4]; + +hash_index_t hash_function_naive(const void *key); + +hash_index_t hash_function_integer(const void *key); + +// Hashes a pointer based only on its address value +hash_index_t hash_function_pointer(const void *key); + +hash_index_t hash_function_string(const void *key); + +void hash_function_blob(const unsigned char *s, unsigned int len, hash_key_t h); + +#endif /* _HASH_FUNCTIONS_H_ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_map.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_map.h new file mode 100644 index 00000000..fea1e021 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/hash_map.h @@ -0,0 +1,110 @@ +/****************************************************************************** + * + * Copyright (C) 2014 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef _HASH_MAP_H_ +#define _HASH_MAP_H_ + +#include +#include + +struct hash_map_t; +typedef struct hash_map_t hash_map_t; + +typedef struct hash_map_entry_t { + const void *key; + void *data; + const hash_map_t *hash_map; +} hash_map_entry_t; + +typedef size_t hash_index_t; + +// Takes a key structure and returns a hash value. +typedef hash_index_t (*hash_index_fn)(const void *key); +typedef bool (*hash_map_iter_cb)(hash_map_entry_t *hash_entry, void *context); + +typedef bool (*key_equality_fn)(const void *x, const void *y); + +typedef void (*key_free_fn)(void *data); +typedef void (*data_free_fn)(void *data); + +// Returns a new, empty hash_map. Returns NULL if not enough memory could be allocated +// for the hash_map structure. The returned hash_map must be freed with |hash_map_free|. +// The |num_bucket| specifies the number of hashable buckets for the map and must not +// be zero. The |hash_fn| specifies a hash function to be used and must not be NULL. +// The |key_fn| and |data_fn| are called whenever a hash_map element is removed from +// the hash_map. They can be used to release resources held by the hash_map element, +// e.g. memory or file descriptor. |key_fn| and |data_fn| may be NULL if no cleanup +// is necessary on element removal. |equality_fn| is used to check for key equality. +// If |equality_fn| is NULL, default pointer equality is used. +hash_map_t *hash_map_new( + size_t size, + hash_index_fn hash_fn, + key_free_fn key_fn, + data_free_fn data_fn, + key_equality_fn equality_fn); + +// Frees the hash_map. This function accepts NULL as an argument, in which case it +// behaves like a no-op. +void hash_map_free(hash_map_t *hash_map); + +// Returns true if the hash_map is empty (has no elements), false otherwise. +// Note that a NULL |hash_map| is not the same as an empty |hash_map|. This function +// does not accept a NULL |hash_map|. +//bool hash_map_is_empty(const hash_map_t *hash_map); + +// Returns the number of elements in the hash map. This function does not accept a +// NULL |hash_map|. +//size_t hash_map_size(const hash_map_t *hash_map); + +// Returns the number of buckets in the hash map. This function does not accept a +// NULL |hash_map|. +//size_t hash_map_num_buckets(const hash_map_t *hash_map); + +// Returns true if the hash_map has a valid entry for the presented key. +// This function does not accept a NULL |hash_map|. +bool hash_map_has_key(const hash_map_t *hash_map, const void *key); + +// Returns the element indexed by |key| in the hash_map without removing it. |hash_map| +// may not be NULL. Returns NULL if no entry indexed by |key|. +void *hash_map_get(const hash_map_t *hash_map, const void *key); + +// Sets the value |data| indexed by |key| into the |hash_map|. Neither |data| nor +// |hash_map| may be NULL. This function does not make copies of |data| nor |key| +// so the pointers must remain valid at least until the element is removed from the +// hash_map or the hash_map is freed. Returns true if |data| could be set, false +// otherwise (e.g. out of memory). +bool hash_map_set(hash_map_t *hash_map, const void *key, void *data); + +// Removes data indexed by |key| from the hash_map. |hash_map| may not be NULL. +// If |key_fn| or |data_fn| functions were specified in |hash_map_new|, they +// will be called back with |key| or |data| respectively. This function returns true +// if |key| was found in the hash_map and removed, false otherwise. +bool hash_map_erase(hash_map_t *hash_map, const void *key); + +// Removes all elements in the hash_map. Calling this function will return the hash_map +// to the same state it was in after |hash_map_new|. |hash_map| may not be NULL. +void hash_map_clear(hash_map_t *hash_map); + +// Iterates through the entire |hash_map| and calls |callback| for each data +// element and passes through the |context| argument. If the hash_map is +// empty, |callback| will never be called. It is not safe to mutate the +// hash_map inside the callback. Neither |hash_map| nor |callback| may be NULL. +// If |callback| returns false, the iteration loop will immediately exit. +void hash_map_foreach(hash_map_t *hash_map, hash_map_iter_cb callback, void *context); + +#endif /* _HASH_MAP_H_ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/list.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/list.h new file mode 100644 index 00000000..f066a1f2 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/list.h @@ -0,0 +1,121 @@ +#ifndef _LIST_H_ +#define _LIST_H_ + +#include +#include +struct list_node_t; +typedef struct list_node_t list_node_t; + +struct list_t; +typedef struct list_t list_t; + +typedef void (*list_free_cb)(void *data); +typedef bool (*list_iter_cb)(void *data, void *context); + +// Returns a new, empty list. Returns NULL if not enough memory could be allocated +// for the list structure. The returned list must be freed with |list_free|. The +// |callback| specifies a function to be called whenever a list element is removed +// from the list. It can be used to release resources held by the list element, e.g. +// memory or file descriptor. |callback| may be NULL if no cleanup is necessary on +// element removal. +list_t *list_new(list_free_cb callback); + + +list_node_t *list_free_node(list_t *list, list_node_t *node); + +// similar with list_free_node, this function doesn't free the node data +list_node_t *list_delete_node(list_t *list, list_node_t *node); + +// Frees the list. This function accepts NULL as an argument, in which case it +// behaves like a no-op. +void list_free(list_t *list); + +// Returns true if |list| is empty (has no elements), false otherwise. +// |list| may not be NULL. +bool list_is_empty(const list_t *list); + +// Returns true if the list contains |data|, false otherwise. +// |list| may not be NULL. +bool list_contains(const list_t *list, const void *data); + +// Returns list_node which contains |data|, NULL otherwise. +// |list| may not be NULL. +list_node_t *list_get_node(const list_t *list, const void *data); + +// Returns the length of the |list|. |list| may not be NULL. +size_t list_length(const list_t *list); + +// Returns the first element in the list without removing it. |list| may not +// be NULL or empty. +void *list_front(const list_t *list); + +// Returns the last element in the list without removing it. |list| may not +// be NULL or empty. +void *list_back(const list_t *list); +list_node_t *list_back_node(const list_t *list); + +// Inserts |data| after |prev_node| in |list|. |data|, |list|, and |prev_node| +// may not be NULL. This function does not make a copy of |data| so the pointer +// must remain valid at least until the element is removed from the list or the +// list is freed. Returns true if |data| could be inserted, false otherwise +// (e.g. out of memory). +bool list_insert_after(list_t *list, list_node_t *prev_node, void *data); + +// Inserts |data| at the beginning of |list|. Neither |data| nor |list| may be NULL. +// This function does not make a copy of |data| so the pointer must remain valid +// at least until the element is removed from the list or the list is freed. +// Returns true if |data| could be inserted, false otherwise (e.g. out of memory). +bool list_prepend(list_t *list, void *data); + +// Inserts |data| at the end of |list|. Neither |data| nor |list| may be NULL. +// This function does not make a copy of |data| so the pointer must remain valid +// at least until the element is removed from the list or the list is freed. +// Returns true if |data| could be inserted, false otherwise (e.g. out of memory). +bool list_append(list_t *list, void *data); + +// Removes |data| from the list. Neither |list| nor |data| may be NULL. If |data| +// is inserted multiple times in the list, this function will only remove the first +// instance. If a free function was specified in |list_new|, it will be called back +// with |data|. This function returns true if |data| was found in the list and removed, +// false otherwise. +//list_node_t list_remove_node(list_t *list, list_node_t *prev_node, list_node_t *node); +//list_node_t list_insert_node(list_t *list, list_node_t *prev_node, list_node_t *node); + +bool list_remove(list_t *list, void *data); + +// similar with list_remove, but do not free the node data +bool list_delete(list_t *list, void *data); + +// Removes all elements in the list. Calling this function will return the list to the +// same state it was in after |list_new|. |list| may not be NULL. +void list_clear(list_t *list); + +// Iterates through the entire |list| and calls |callback| for each data element. +// If the list is empty, |callback| will never be called. It is safe to mutate the +// list inside the callback. If an element is added before the node being visited, +// there will be no callback for the newly-inserted node. Neither |list| nor +// |callback| may be NULL. +list_node_t *list_foreach(const list_t *list, list_iter_cb callback, void *context); + +// Returns an iterator to the first element in |list|. |list| may not be NULL. +// The returned iterator is valid as long as it does not equal the value returned +// by |list_end|. +list_node_t *list_begin(const list_t *list); + +// Returns an iterator that points past the end of the list. In other words, +// this function returns the value of an invalid iterator for the given list. +// When an iterator has the same value as what's returned by this function, you +// may no longer call |list_next| with the iterator. |list| may not be NULL. +list_node_t *list_end(const list_t *list); + +// Given a valid iterator |node|, this function returns the next value for the +// iterator. If the returned value equals the value returned by |list_end|, the +// iterator has reached the end of the list and may no longer be used for any +// purpose. +list_node_t *list_next(const list_node_t *node); + +// Returns the value stored at the location pointed to by the iterator |node|. +// |node| must not equal the value returned by |list_end|. +void *list_node(const list_node_t *node); + +#endif /* _LIST_H_ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/mutex.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/mutex.h new file mode 100644 index 00000000..2055b2c1 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/mutex.h @@ -0,0 +1,52 @@ +/****************************************************************************** + * + * Copyright (C) 2015 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef __MUTEX_H__ +#define __MUTEX_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" +#include "osi/semaphore.h" + +#define OSI_MUTEX_MAX_TIMEOUT OSI_SEM_MAX_TIMEOUT + +#define osi_mutex_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define osi_mutex_set_invalid( x ) ( ( *x ) = NULL ) + +typedef xSemaphoreHandle osi_mutex_t; + +int osi_mutex_new(osi_mutex_t *mutex); + +int osi_mutex_lock(osi_mutex_t *mutex, uint32_t timeout); + +void osi_mutex_unlock(osi_mutex_t *mutex); + +void osi_mutex_free(osi_mutex_t *mutex); + +/* Just for a global mutex */ +int osi_mutex_global_init(void); + +void osi_mutex_global_deinit(void); + +void osi_mutex_global_lock(void); + +void osi_mutex_global_unlock(void); + +#endif /* __MUTEX_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/osi.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/osi.h new file mode 100644 index 00000000..3bd217af --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/osi.h @@ -0,0 +1,16 @@ + +#ifndef _OSI_H_ +#define _OSI_H_ + +#include +#include + +#define UNUSED_ATTR __attribute__((unused)) + +#define CONCAT(a, b) a##b +#define COMPILE_ASSERT(x) + +int osi_init(void); +void osi_deinit(void); + +#endif /*_OSI_H_*/ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/semaphore.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/semaphore.h new file mode 100644 index 00000000..621d5a2c --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/semaphore.h @@ -0,0 +1,43 @@ +/****************************************************************************** + * + * Copyright (C) 2015 Google, Inc. + * + * 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. + * + ******************************************************************************/ + +#ifndef __SEMAPHORE_H__ +#define __SEMAPHORE_H__ + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" + +#define OSI_SEM_MAX_TIMEOUT 0xffffffffUL + +typedef xSemaphoreHandle osi_sem_t; + +#define osi_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) +#define osi_sem_set_invalid( x ) ( ( *x ) = NULL ) + +int osi_sem_new(osi_sem_t *sem, uint32_t max_count, uint32_t init_count); + +void osi_sem_free(osi_sem_t *sem); + +int osi_sem_take(osi_sem_t *sem, uint32_t timeout); + +void osi_sem_give(osi_sem_t *sem); + + +#endif /* __SEMAPHORE_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/common/osi/include/osi/thread.h b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/thread.h new file mode 100644 index 00000000..fdabed1c --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/common/osi/include/osi/thread.h @@ -0,0 +1,91 @@ +// Copyright 2015-2016 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. + +#ifndef __THREAD_H__ +#define __THREAD_H__ + +#include "freertos/FreeRTOSConfig.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "freertos/task.h" +#include "osi/semaphore.h" +#include "esp_task.h" +#include "bt_common.h" + +#define portBASE_TYPE int + +#define OSI_THREAD_MAX_TIMEOUT OSI_SEM_MAX_TIMEOUT + +struct osi_thread; + +typedef struct osi_thread osi_thread_t; + +typedef void (*osi_thread_func_t)(void *context); + +typedef enum { + OSI_THREAD_CORE_0 = 0, + OSI_THREAD_CORE_1, + OSI_THREAD_CORE_AFFINITY, +} osi_thread_core_t; + +/* + * brief: Create a thread or task + * param name: thread name + * param stack_size: thread stack size + * param priority: thread priority + * param core: the CPU core which this thread run, OSI_THREAD_CORE_AFFINITY means unspecific CPU core + * param work_queue_num: speicify queue number, the queue[0] has highest priority, and the priority is decrease by index + * return : if create successfully, return thread handler; otherwise return NULL. + */ +osi_thread_t *osi_thread_create(const char *name, size_t stack_size, int priority, osi_thread_core_t core, uint8_t work_queue_num); + +/* + * brief: Destroy a thread or task + * param thread: point of thread handler + */ +void osi_thread_free(osi_thread_t *thread); + +/* + * brief: Post an msg to a thread and told the thread call the function + * param thread: point of thread handler + * param func: callback function that called by target thread + * param context: argument of callback function + * param queue_idx: the queue which the msg send to + * param timeout: post timeout, OSI_THREAD_MAX_TIMEOUT means blocking forever, 0 means never blocking, others means block millisecond + * return : if post successfully, return true, otherwise return false + */ +bool osi_thread_post(osi_thread_t *thread, osi_thread_func_t func, void *context, int queue_idx, uint32_t timeout); + +/* + * brief: Set the priority of thread + * param thread: point of thread handler + * param priority: priority + * return : if set successfully, return true, otherwise return false + */ +bool osi_thread_set_priority(osi_thread_t *thread, int priority); + +/* brief: Get thread name + * param thread: point of thread handler + * return: constant point of thread name + */ +const char *osi_thread_name(osi_thread_t *thread); + +/* brief: Get the size of the specified queue + * param thread: point of thread handler + * param wq_idx: the queue index of the thread + * return: queue size + */ +int osi_thread_queue_wait_size(osi_thread_t *thread, int wq_idx); + +#endif /* __THREAD_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_a2dp_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_a2dp_api.h new file mode 100644 index 00000000..e45af935 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_a2dp_api.h @@ -0,0 +1,373 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_A2DP_API_H__ +#define __ESP_A2DP_API_H__ + +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// Media codec types supported by A2DP +#define ESP_A2D_MCT_SBC (0) /*!< SBC */ +#define ESP_A2D_MCT_M12 (0x01) /*!< MPEG-1, 2 Audio */ +#define ESP_A2D_MCT_M24 (0x02) /*!< MPEG-2, 4 AAC */ +#define ESP_A2D_MCT_ATRAC (0x04) /*!< ATRAC family */ +#define ESP_A2D_MCT_NON_A2DP (0xff) + +typedef uint8_t esp_a2d_mct_t; + +/** A2DP media codec capabilities union + */ +typedef struct { + esp_a2d_mct_t type; /*!< A2DP media codec type */ +#define ESP_A2D_CIE_LEN_SBC (4) +#define ESP_A2D_CIE_LEN_M12 (4) +#define ESP_A2D_CIE_LEN_M24 (6) +#define ESP_A2D_CIE_LEN_ATRAC (7) + union { + uint8_t sbc[ESP_A2D_CIE_LEN_SBC]; /*!< SBC codec capabilities */ + uint8_t m12[ESP_A2D_CIE_LEN_M12]; /*!< MPEG-1,2 audio codec capabilities */ + uint8_t m24[ESP_A2D_CIE_LEN_M24]; /*!< MPEG-2, 4 AAC audio codec capabilities */ + uint8_t atrac[ESP_A2D_CIE_LEN_ATRAC]; /*!< ATRAC family codec capabilities */ + } cie; /*!< A2DP codec information element */ +} __attribute__((packed)) esp_a2d_mcc_t; + +/// Bluetooth A2DP connection states +typedef enum { + ESP_A2D_CONNECTION_STATE_DISCONNECTED = 0, /*!< connection released */ + ESP_A2D_CONNECTION_STATE_CONNECTING, /*!< connecting remote device */ + ESP_A2D_CONNECTION_STATE_CONNECTED, /*!< connection established */ + ESP_A2D_CONNECTION_STATE_DISCONNECTING /*!< disconnecting remote device */ +} esp_a2d_connection_state_t; + +/// Bluetooth A2DP disconnection reason +typedef enum { + ESP_A2D_DISC_RSN_NORMAL = 0, /*!< Finished disconnection that is initiated by local or remote device */ + ESP_A2D_DISC_RSN_ABNORMAL /*!< Abnormal disconnection caused by signal loss */ +} esp_a2d_disc_rsn_t; + +/// Bluetooth A2DP datapath states +typedef enum { + ESP_A2D_AUDIO_STATE_REMOTE_SUSPEND = 0, /*!< audio stream datapath suspended by remote device */ + ESP_A2D_AUDIO_STATE_STOPPED, /*!< audio stream datapath stopped */ + ESP_A2D_AUDIO_STATE_STARTED, /*!< audio stream datapath started */ +} esp_a2d_audio_state_t; + +/// A2DP media control command acknowledgement code +typedef enum { + ESP_A2D_MEDIA_CTRL_ACK_SUCCESS = 0, /*!< media control command is acknowledged with success */ + ESP_A2D_MEDIA_CTRL_ACK_FAILURE, /*!< media control command is acknowledged with failure */ + ESP_A2D_MEDIA_CTRL_ACK_BUSY, /*!< media control command is rejected, as previous command is not yet acknowledged */ +} esp_a2d_media_ctrl_ack_t; + +/// A2DP media control commands +typedef enum { + ESP_A2D_MEDIA_CTRL_NONE = 0, /*!< Not for application use, use inside stack only. */ + ESP_A2D_MEDIA_CTRL_CHECK_SRC_RDY, /*!< check whether AVDTP is connected, only used in A2DP source */ + ESP_A2D_MEDIA_CTRL_START, /*!< command to set up media transmission channel */ + ESP_A2D_MEDIA_CTRL_STOP, /*!< command to stop media transmission */ + ESP_A2D_MEDIA_CTRL_SUSPEND, /*!< command to suspend media transmission */ +} esp_a2d_media_ctrl_t; + +/// Bluetooth A2DP Initiation states +typedef enum { + ESP_A2D_DEINIT_SUCCESS = 0, /*!< A2DP profile deinit successful event */ + ESP_A2D_INIT_SUCCESS /*!< A2DP profile deinit successful event */ +} esp_a2d_init_state_t; + +/// A2DP callback events +typedef enum { + ESP_A2D_CONNECTION_STATE_EVT = 0, /*!< connection state changed event */ + ESP_A2D_AUDIO_STATE_EVT, /*!< audio stream transmission state changed event */ + ESP_A2D_AUDIO_CFG_EVT, /*!< audio codec is configured, only used for A2DP SINK */ + ESP_A2D_MEDIA_CTRL_ACK_EVT, /*!< acknowledge event in response to media control commands */ + ESP_A2D_PROF_STATE_EVT, /*!< indicate a2dp init&deinit complete */ +} esp_a2d_cb_event_t; + +/// A2DP state callback parameters +typedef union { + /** + * @brief ESP_A2D_CONNECTION_STATE_EVT + */ + struct a2d_conn_stat_param { + esp_a2d_connection_state_t state; /*!< one of values from esp_a2d_connection_state_t */ + esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ + esp_a2d_disc_rsn_t disc_rsn; /*!< reason of disconnection for "DISCONNECTED" */ + } conn_stat; /*!< A2DP connection status */ + + /** + * @brief ESP_A2D_AUDIO_STATE_EVT + */ + struct a2d_audio_stat_param { + esp_a2d_audio_state_t state; /*!< one of the values from esp_a2d_audio_state_t */ + esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ + } audio_stat; /*!< audio stream playing state */ + + /** + * @brief ESP_A2D_AUDIO_CFG_EVT + */ + struct a2d_audio_cfg_param { + esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ + esp_a2d_mcc_t mcc; /*!< A2DP media codec capability information */ + } audio_cfg; /*!< media codec configuration information */ + + /** + * @brief ESP_A2D_MEDIA_CTRL_ACK_EVT + */ + struct media_ctrl_stat_param { + esp_a2d_media_ctrl_t cmd; /*!< media control commands to acknowledge */ + esp_a2d_media_ctrl_ack_t status; /*!< acknowledgement to media control commands */ + } media_ctrl_stat; /*!< status in acknowledgement to media control commands */ + /** + * @brief ESP_A2D_PROF_STATE_EVT + */ + struct a2d_prof_stat_param { + esp_a2d_init_state_t init_state; /*!< a2dp profile state param */ + } a2d_prof_stat; /*!< status to indicate a2d prof init or deinit */ +} esp_a2d_cb_param_t; + +/** + * @brief A2DP profile callback function type + * + * @param event : Event type + * + * @param param : Pointer to callback parameter + */ +typedef void (* esp_a2d_cb_t)(esp_a2d_cb_event_t event, esp_a2d_cb_param_t *param); + +/** + * @brief A2DP sink data callback function + * + * @param[in] buf : pointer to the data received from A2DP source device and is PCM format decoded from SBC decoder; + * buf references to a static memory block and can be overwritten by upcoming data + * + * @param[in] len : size(in bytes) in buf + */ +typedef void (* esp_a2d_sink_data_cb_t)(const uint8_t *buf, uint32_t len); + +/** + * @brief A2DP source data read callback function + * + * @param[in] buf : buffer to be filled with PCM data stream from higher layer + * + * @param[in] len : size(in bytes) of data block to be copied to buf. -1 is an indication to user + * that data buffer shall be flushed + * + * @return size of bytes read successfully, if the argument len is -1, this value is ignored. + * + */ +typedef int32_t (* esp_a2d_source_data_cb_t)(uint8_t *buf, int32_t len); + +/** + * @brief Register application callback function to A2DP module. This function should be called + * only after esp_bluedroid_enable() completes successfully, used by both A2DP source + * and sink. + * + * @param[in] callback: A2DP event callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_a2d_register_callback(esp_a2d_cb_t callback); + + +/** + * @brief Register A2DP sink data output function; For now the output is PCM data stream decoded + * from SBC format. This function should be called only after esp_bluedroid_enable() + * completes successfully, used only by A2DP sink. The callback is invoked in the context + * of A2DP sink task whose stack size is configurable through menuconfig. + * + * @param[in] callback: A2DP sink data callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_a2d_sink_register_data_callback(esp_a2d_sink_data_cb_t callback); + + +/** + * + * @brief Initialize the bluetooth A2DP sink module. This function should be called + * after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT + * with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. + * If you want to use AVRC together, you should initiate AVRC first. This + * function should be called after esp_bluedroid_enable() completes successfully. + * + * @return + * - ESP_OK: if the initialization request is sent successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_sink_init(void); + + +/** + * + * @brief De-initialize for A2DP sink module. This function + * should be called only after esp_bluedroid_enable() completes successfully, + * and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. + * + * @return + * - ESP_OK: if the deinitialization request is sent successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_sink_deinit(void); + + +/** + * + * @brief Connect to remote bluetooth A2DP source device. This API must be called after + * esp_a2d_sink_init() and before esp_a2d_sink_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: connect request is sent to lower layer successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_sink_connect(esp_bd_addr_t remote_bda); + + +/** + * + * @brief Disconnect from the remote A2DP source device. This API must be called after + * esp_a2d_sink_init() and before esp_a2d_sink_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: disconnect request is sent to lower layer successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_sink_disconnect(esp_bd_addr_t remote_bda); + + +/** + * + * @brief Media control commands. This API can be used for both A2DP sink and source + * and must be called after esp_a2d_sink_init() and before esp_a2d_sink_deinit(). + * + * @param[in] ctrl: control commands for A2DP data channel + * + * @return + * - ESP_OK: control command is sent to lower layer successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_media_ctrl(esp_a2d_media_ctrl_t ctrl); + + +/** + * + * @brief Initialize the bluetooth A2DP source module. A2DP can work independently. + * If you want to use AVRC together, you should initiate AVRC first. This function should be called + * after esp_bluedroid_enable() completes successfully, and ESP_A2D_PROF_STATE_EVT + * with ESP_A2D_INIT_SUCCESS will reported to the APP layer. Note: A2DP can work independently. + * If you want to use AVRC together, you should initiate AVRC first. + * + * @return + * - ESP_OK: if the initialization request is sent to lower layer successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_source_init(void); + + +/** + * + * @brief De-initialize for A2DP source module. This function + * should be called only after esp_bluedroid_enable() completes successfully, + * and ESP_A2D_PROF_STATE_EVT with ESP_A2D_DEINIT_SUCCESS will reported to APP layer. + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_source_deinit(void); + + +/** + * @brief Register A2DP source data input function. For now, the input shoule be PCM data stream. + * This function should be called only after esp_bluedroid_enable() completes + * successfully. The callback is invoked in the context of A2DP source task whose + * stack size is configurable through menuconfig. + * + * @param[in] callback: A2DP source data callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_a2d_source_register_data_callback(esp_a2d_source_data_cb_t callback); + + +/** + * + * @brief Connect to remote A2DP sink device. This API must be called + * after esp_a2d_source_init() and before esp_a2d_source_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: connect request is sent to lower layer successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_source_connect(esp_bd_addr_t remote_bda); + + +/** + * + * @brief Disconnect from the remote A2DP sink device. This API must be called + * after esp_a2d_source_init() and before esp_a2d_source_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_a2d_source_disconnect(esp_bd_addr_t remote_bda); + +#ifdef __cplusplus +} +#endif + + +#endif /* __ESP_A2DP_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_avrc_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_avrc_api.h new file mode 100644 index 00000000..dd4d5fcb --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_avrc_api.h @@ -0,0 +1,743 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_AVRC_API_H__ +#define __ESP_AVRC_API_H__ + +#include +#include +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_AVRC_TRANS_LABEL_MAX 15 /*!< max transaction label */ + +/// AVRC feature bit mask +typedef enum { + ESP_AVRC_FEAT_RCTG = 0x0001, /*!< remote control target */ + ESP_AVRC_FEAT_RCCT = 0x0002, /*!< remote control controller */ + ESP_AVRC_FEAT_VENDOR = 0x0008, /*!< remote control vendor dependent commands */ + ESP_AVRC_FEAT_BROWSE = 0x0010, /*!< use browsing channel */ + ESP_AVRC_FEAT_META_DATA = 0x0040, /*!< remote control metadata transfer command/response */ + ESP_AVRC_FEAT_ADV_CTRL = 0x0200, /*!< remote control advanced control commmand/response */ +} esp_avrc_features_t; + +/// AVRC supported features flag retrieved in SDP record +typedef enum { + ESP_AVRC_FEAT_FLAG_CAT1 = 0x0001, /*!< category 1 */ + ESP_AVRC_FEAT_FLAG_CAT2 = 0x0002, /*!< category 2 */ + ESP_AVRC_FEAT_FLAG_CAT3 = 0x0004, /*!< category 3 */ + ESP_AVRC_FEAT_FLAG_CAT4 = 0x0008, /*!< category 4 */ + ESP_AVRC_FEAT_FLAG_BROWSING = 0x0040, /*!< browsing */ + ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE_PROP = 0x0080, /*!< Cover Art GetImageProperties */ + ESP_AVRC_FEAT_FLAG_COVER_ART_GET_IMAGE = 0x0100, /*!< Cover Art GetImage */ + ESP_AVRC_FEAT_FLAG_COVER_ART_GET_LINKED_THUMBNAIL = 0x0200, /*!< Cover Art GetLinkedThumbnail */ +} esp_avrc_feature_flag_t; + +/// AVRC passthrough command code +typedef enum { + ESP_AVRC_PT_CMD_SELECT = 0x00, /*!< select */ + ESP_AVRC_PT_CMD_UP = 0x01, /*!< up */ + ESP_AVRC_PT_CMD_DOWN = 0x02, /*!< down */ + ESP_AVRC_PT_CMD_LEFT = 0x03, /*!< left */ + ESP_AVRC_PT_CMD_RIGHT = 0x04, /*!< right */ + ESP_AVRC_PT_CMD_RIGHT_UP = 0x05, /*!< right-up */ + ESP_AVRC_PT_CMD_RIGHT_DOWN = 0x06, /*!< right-down */ + ESP_AVRC_PT_CMD_LEFT_UP = 0x07, /*!< left-up */ + ESP_AVRC_PT_CMD_LEFT_DOWN = 0x08, /*!< left-down */ + ESP_AVRC_PT_CMD_ROOT_MENU = 0x09, /*!< root menu */ + ESP_AVRC_PT_CMD_SETUP_MENU = 0x0A, /*!< setup menu */ + ESP_AVRC_PT_CMD_CONT_MENU = 0x0B, /*!< contents menu */ + ESP_AVRC_PT_CMD_FAV_MENU = 0x0C, /*!< favorite menu */ + ESP_AVRC_PT_CMD_EXIT = 0x0D, /*!< exit */ + ESP_AVRC_PT_CMD_0 = 0x20, /*!< 0 */ + ESP_AVRC_PT_CMD_1 = 0x21, /*!< 1 */ + ESP_AVRC_PT_CMD_2 = 0x22, /*!< 2 */ + ESP_AVRC_PT_CMD_3 = 0x23, /*!< 3 */ + ESP_AVRC_PT_CMD_4 = 0x24, /*!< 4 */ + ESP_AVRC_PT_CMD_5 = 0x25, /*!< 5 */ + ESP_AVRC_PT_CMD_6 = 0x26, /*!< 6 */ + ESP_AVRC_PT_CMD_7 = 0x27, /*!< 7 */ + ESP_AVRC_PT_CMD_8 = 0x28, /*!< 8 */ + ESP_AVRC_PT_CMD_9 = 0x29, /*!< 9 */ + ESP_AVRC_PT_CMD_DOT = 0x2A, /*!< dot */ + ESP_AVRC_PT_CMD_ENTER = 0x2B, /*!< enter */ + ESP_AVRC_PT_CMD_CLEAR = 0x2C, /*!< clear */ + ESP_AVRC_PT_CMD_CHAN_UP = 0x30, /*!< channel up */ + ESP_AVRC_PT_CMD_CHAN_DOWN = 0x31, /*!< channel down */ + ESP_AVRC_PT_CMD_PREV_CHAN = 0x32, /*!< previous channel */ + ESP_AVRC_PT_CMD_SOUND_SEL = 0x33, /*!< sound select */ + ESP_AVRC_PT_CMD_INPUT_SEL = 0x34, /*!< input select */ + ESP_AVRC_PT_CMD_DISP_INFO = 0x35, /*!< display information */ + ESP_AVRC_PT_CMD_HELP = 0x36, /*!< help */ + ESP_AVRC_PT_CMD_PAGE_UP = 0x37, /*!< page up */ + ESP_AVRC_PT_CMD_PAGE_DOWN = 0x38, /*!< page down */ + ESP_AVRC_PT_CMD_POWER = 0x40, /*!< power */ + ESP_AVRC_PT_CMD_VOL_UP = 0x41, /*!< volume up */ + ESP_AVRC_PT_CMD_VOL_DOWN = 0x42, /*!< volume down */ + ESP_AVRC_PT_CMD_MUTE = 0x43, /*!< mute */ + ESP_AVRC_PT_CMD_PLAY = 0x44, /*!< play */ + ESP_AVRC_PT_CMD_STOP = 0x45, /*!< stop */ + ESP_AVRC_PT_CMD_PAUSE = 0x46, /*!< pause */ + ESP_AVRC_PT_CMD_RECORD = 0x47, /*!< record */ + ESP_AVRC_PT_CMD_REWIND = 0x48, /*!< rewind */ + ESP_AVRC_PT_CMD_FAST_FORWARD = 0x49, /*!< fast forward */ + ESP_AVRC_PT_CMD_EJECT = 0x4A, /*!< eject */ + ESP_AVRC_PT_CMD_FORWARD = 0x4B, /*!< forward */ + ESP_AVRC_PT_CMD_BACKWARD = 0x4C, /*!< backward */ + ESP_AVRC_PT_CMD_ANGLE = 0x50, /*!< angle */ + ESP_AVRC_PT_CMD_SUBPICT = 0x51, /*!< subpicture */ + ESP_AVRC_PT_CMD_F1 = 0x71, /*!< F1 */ + ESP_AVRC_PT_CMD_F2 = 0x72, /*!< F2 */ + ESP_AVRC_PT_CMD_F3 = 0x73, /*!< F3 */ + ESP_AVRC_PT_CMD_F4 = 0x74, /*!< F4 */ + ESP_AVRC_PT_CMD_F5 = 0x75, /*!< F5 */ + ESP_AVRC_PT_CMD_VENDOR = 0x7E, /*!< vendor unique */ +} esp_avrc_pt_cmd_t; + +/// AVRC passthrough command filter +typedef enum { + ESP_AVRC_PSTH_FILTER_ALLOWED_CMD = 0, /*!< all of the PASSTHROUGH commands that can possibly be used, immuateble */ + ESP_AVRC_PSTH_FILTER_SUPPORTED_CMD = 1, /*!< PASSTHROUGH commands selectively supported according to the current configuration */ + ESP_AVRC_PSTH_FILTER_SUPPORT_MAX, +} esp_avrc_psth_filter_t; + +/// AVRC passthrough command bit mask +typedef struct { + uint16_t bits[8]; /*!< bit mask representation of PASSTHROUGH commands */ +} esp_avrc_psth_bit_mask_t; + +typedef enum { + ESP_AVRC_BIT_MASK_OP_TEST = 0, /*!< operation code to test a specific bit */ + ESP_AVRC_BIT_MASK_OP_SET = 1, /*!< operation code to set a specific bit */ + ESP_AVRC_BIT_MASK_OP_CLEAR = 2, /*!< operation code to clear a specific bit */ +} esp_avrc_bit_mask_op_t; + +/// AVRC passthrough command state +typedef enum { + ESP_AVRC_PT_CMD_STATE_PRESSED = 0, /*!< key pressed */ + ESP_AVRC_PT_CMD_STATE_RELEASED = 1 /*!< key released */ +} esp_avrc_pt_cmd_state_t; + +/// AVRC Controller callback events +typedef enum { + ESP_AVRC_CT_CONNECTION_STATE_EVT = 0, /*!< connection state changed event */ + ESP_AVRC_CT_PASSTHROUGH_RSP_EVT = 1, /*!< passthrough response event */ + ESP_AVRC_CT_METADATA_RSP_EVT = 2, /*!< metadata response event */ + ESP_AVRC_CT_PLAY_STATUS_RSP_EVT = 3, /*!< play status response event */ + ESP_AVRC_CT_CHANGE_NOTIFY_EVT = 4, /*!< notification event */ + ESP_AVRC_CT_REMOTE_FEATURES_EVT = 5, /*!< feature of remote device indication event */ + ESP_AVRC_CT_GET_RN_CAPABILITIES_RSP_EVT = 6, /*!< supported notification events capability of peer device */ + ESP_AVRC_CT_SET_ABSOLUTE_VOLUME_RSP_EVT = 7, /*!< set absolute volume response event */ +} esp_avrc_ct_cb_event_t; + +/// AVRC Target callback events +typedef enum { + ESP_AVRC_TG_CONNECTION_STATE_EVT = 0, /*!< connection state changed event */ + ESP_AVRC_TG_REMOTE_FEATURES_EVT = 1, /*!< feature of remote device indication event */ + ESP_AVRC_TG_PASSTHROUGH_CMD_EVT = 2, /*!< passthrough command event */ + ESP_AVRC_TG_SET_ABSOLUTE_VOLUME_CMD_EVT = 3, /*!< set absolute volume command from remote device */ + ESP_AVRC_TG_REGISTER_NOTIFICATION_EVT = 4, /*!< register notification event */ + ESP_AVRC_TG_SET_PLAYER_APP_VALUE_EVT = 5, /*!< set applicaton attribute value, attribute refer to esp_avrc_ps_attr_ids_t */ +} esp_avrc_tg_cb_event_t; + +/// AVRC metadata attribute mask +typedef enum { + ESP_AVRC_MD_ATTR_TITLE = 0x1, /*!< title of the playing track */ + ESP_AVRC_MD_ATTR_ARTIST = 0x2, /*!< track artist */ + ESP_AVRC_MD_ATTR_ALBUM = 0x4, /*!< album name */ + ESP_AVRC_MD_ATTR_TRACK_NUM = 0x8, /*!< track position on the album */ + ESP_AVRC_MD_ATTR_NUM_TRACKS = 0x10, /*!< number of tracks on the album */ + ESP_AVRC_MD_ATTR_GENRE = 0x20, /*!< track genre */ + ESP_AVRC_MD_ATTR_PLAYING_TIME = 0x40 /*!< total album playing time in miliseconds */ +} esp_avrc_md_attr_mask_t; + +/// AVRC event notification ids +typedef enum { + ESP_AVRC_RN_PLAY_STATUS_CHANGE = 0x01, /*!< track status change, eg. from playing to paused */ + ESP_AVRC_RN_TRACK_CHANGE = 0x02, /*!< new track is loaded */ + ESP_AVRC_RN_TRACK_REACHED_END = 0x03, /*!< current track reached end */ + ESP_AVRC_RN_TRACK_REACHED_START = 0x04, /*!< current track reached start position */ + ESP_AVRC_RN_PLAY_POS_CHANGED = 0x05, /*!< track playing position changed */ + ESP_AVRC_RN_BATTERY_STATUS_CHANGE = 0x06, /*!< battery status changed */ + ESP_AVRC_RN_SYSTEM_STATUS_CHANGE = 0x07, /*!< system status changed */ + ESP_AVRC_RN_APP_SETTING_CHANGE = 0x08, /*!< application settings changed */ + ESP_AVRC_RN_NOW_PLAYING_CHANGE = 0x09, /*!< now playing content changed */ + ESP_AVRC_RN_AVAILABLE_PLAYERS_CHANGE = 0x0a, /*!< available players changed */ + ESP_AVRC_RN_ADDRESSED_PLAYER_CHANGE = 0x0b, /*!< the addressed player changed */ + ESP_AVRC_RN_UIDS_CHANGE = 0x0c, /*!< UIDs changed */ + ESP_AVRC_RN_VOLUME_CHANGE = 0x0d, /*!< volume changed locally on TG */ + ESP_AVRC_RN_MAX_EVT +} esp_avrc_rn_event_ids_t; + +/// AVRC target notification event notification capability +typedef enum { + ESP_AVRC_RN_CAP_ALLOWED_EVT = 0, /*!< all of the notification events that can possibly be supported, immutable */ + ESP_AVRC_RN_CAP_SUPPORTED_EVT = 1, /*!< notification events selectively supported according to the current configuration */ + ESP_AVRC_RN_CAP_MAX, +} esp_avrc_rn_evt_cap_t; + +/// AVRC target notification event capability bit mask +typedef struct { + uint16_t bits; /*!< bit mask representation of PASSTHROUGH commands */ +} esp_avrc_rn_evt_cap_mask_t; + +/// AVRC notification response type +typedef enum { + ESP_AVRC_RN_RSP_INTERIM = 13, /*!< initial response to RegisterNotification, should be sent T_mtp(1000ms) from receiving the command */ + ESP_AVRC_RN_RSP_CHANGED = 15, /*!< final response to RegisterNotification command */ +} esp_avrc_rn_rsp_t; + +/// AVRC player setting ids +typedef enum { + ESP_AVRC_PS_EQUALIZER = 0x01, /*!< equalizer, on or off */ + ESP_AVRC_PS_REPEAT_MODE = 0x02, /*!< repeat mode */ + ESP_AVRC_PS_SHUFFLE_MODE = 0x03, /*!< shuffle mode */ + ESP_AVRC_PS_SCAN_MODE = 0x04, /*!< scan mode on or off */ + ESP_AVRC_PS_MAX_ATTR +} esp_avrc_ps_attr_ids_t; + +/// AVRC equalizer modes +typedef enum { + ESP_AVRC_PS_EQUALIZER_OFF = 0x1, /*!< equalizer OFF */ + ESP_AVRC_PS_EQUALIZER_ON = 0x2 /*!< equalizer ON */ +} esp_avrc_ps_eq_value_ids_t; + +/// AVRC repeat modes +typedef enum { + ESP_AVRC_PS_REPEAT_OFF = 0x1, /*!< repeat mode off */ + ESP_AVRC_PS_REPEAT_SINGLE = 0x2, /*!< single track repeat */ + ESP_AVRC_PS_REPEAT_GROUP = 0x3 /*!< group repeat */ +} esp_avrc_ps_rpt_value_ids_t; + + +/// AVRC shuffle modes +typedef enum { + ESP_AVRC_PS_SHUFFLE_OFF = 0x1, /* +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_BLUEDROID_STATUS_CHECK(status) \ + if (esp_bluedroid_get_status() != (status)) { \ + return ESP_ERR_INVALID_STATE; \ + } + + +/* relate to BT_STATUS_xxx in bt_def.h */ +/// Status Return Value +typedef enum { + ESP_BT_STATUS_SUCCESS = 0, /* relate to BT_STATUS_SUCCESS in bt_def.h */ + ESP_BT_STATUS_FAIL, /* relate to BT_STATUS_FAIL in bt_def.h */ + ESP_BT_STATUS_NOT_READY, /* relate to BT_STATUS_NOT_READY in bt_def.h */ + ESP_BT_STATUS_NOMEM, /* relate to BT_STATUS_NOMEM in bt_def.h */ + ESP_BT_STATUS_BUSY, /* relate to BT_STATUS_BUSY in bt_def.h */ + ESP_BT_STATUS_DONE = 5, /* relate to BT_STATUS_DONE in bt_def.h */ + ESP_BT_STATUS_UNSUPPORTED, /* relate to BT_STATUS_UNSUPPORTED in bt_def.h */ + ESP_BT_STATUS_PARM_INVALID, /* relate to BT_STATUS_PARM_INVALID in bt_def.h */ + ESP_BT_STATUS_UNHANDLED, /* relate to BT_STATUS_UNHANDLED in bt_def.h */ + ESP_BT_STATUS_AUTH_FAILURE, /* relate to BT_STATUS_AUTH_FAILURE in bt_def.h */ + ESP_BT_STATUS_RMT_DEV_DOWN = 10, /* relate to BT_STATUS_RMT_DEV_DOWN in bt_def.h */ + ESP_BT_STATUS_AUTH_REJECTED, /* relate to BT_STATUS_AUTH_REJECTED in bt_def.h */ + ESP_BT_STATUS_INVALID_STATIC_RAND_ADDR, /* relate to BT_STATUS_INVALID_STATIC_RAND_ADDR in bt_def.h */ + ESP_BT_STATUS_PENDING, /* relate to BT_STATUS_PENDING in bt_def.h */ + ESP_BT_STATUS_UNACCEPT_CONN_INTERVAL, /* relate to BT_UNACCEPT_CONN_INTERVAL in bt_def.h */ + ESP_BT_STATUS_PARAM_OUT_OF_RANGE, /* relate to BT_PARAM_OUT_OF_RANGE in bt_def.h */ + ESP_BT_STATUS_TIMEOUT, /* relate to BT_STATUS_TIMEOUT in bt_def.h */ + ESP_BT_STATUS_PEER_LE_DATA_LEN_UNSUPPORTED, /* relate to BTM_PEER_LE_DATA_LEN_UNSUPPORTED in stack/btm_api.h */ + ESP_BT_STATUS_CONTROL_LE_DATA_LEN_UNSUPPORTED,/* relate to BTM_CONTROL_LE_DATA_LEN_UNSUPPORTED in stack/btm_api.h */ + ESP_BT_STATUS_ERR_ILLEGAL_PARAMETER_FMT, /* relate to HCI_ERR_ILLEGAL_PARAMETER_FMT in stack/hcidefs.h */ + ESP_BT_STATUS_MEMORY_FULL = 20, /* relate to BT_STATUS_MEMORY_FULL in bt_def.h */ + ESP_BT_STATUS_EIR_TOO_LARGE, /* relate to BT_STATUS_EIR_TOO_LARGE in bt_def.h */ +} esp_bt_status_t; + + +/*Define the bt octet 16 bit size*/ +#define ESP_BT_OCTET16_LEN 16 +typedef uint8_t esp_bt_octet16_t[ESP_BT_OCTET16_LEN]; /* octet array: size 16 */ + +#define ESP_BT_OCTET8_LEN 8 +typedef uint8_t esp_bt_octet8_t[ESP_BT_OCTET8_LEN]; /* octet array: size 8 */ + +typedef uint8_t esp_link_key[ESP_BT_OCTET16_LEN]; /* Link Key */ + +/// Default GATT interface id +#define ESP_DEFAULT_GATT_IF 0xff + +#define ESP_BLE_CONN_INT_MIN 0x0006 /*!< relate to BTM_BLE_CONN_INT_MIN in stack/btm_ble_api.h */ +#define ESP_BLE_CONN_INT_MAX 0x0C80 /*!< relate to BTM_BLE_CONN_INT_MAX in stack/btm_ble_api.h */ +#define ESP_BLE_CONN_LATENCY_MAX 499 /*!< relate to ESP_BLE_CONN_LATENCY_MAX in stack/btm_ble_api.h */ +#define ESP_BLE_CONN_SUP_TOUT_MIN 0x000A /*!< relate to BTM_BLE_CONN_SUP_TOUT_MIN in stack/btm_ble_api.h */ +#define ESP_BLE_CONN_SUP_TOUT_MAX 0x0C80 /*!< relate to ESP_BLE_CONN_SUP_TOUT_MAX in stack/btm_ble_api.h */ +#define ESP_BLE_CONN_PARAM_UNDEF 0xffff /* use this value when a specific value not to be overwritten */ /* relate to ESP_BLE_CONN_PARAM_UNDEF in stack/btm_ble_api.h */ +#define ESP_BLE_SCAN_PARAM_UNDEF 0xffffffff /* relate to ESP_BLE_SCAN_PARAM_UNDEF in stack/btm_ble_api.h */ + +/// Check the param is valid or not +#define ESP_BLE_IS_VALID_PARAM(x, min, max) (((x) >= (min) && (x) <= (max)) || ((x) == ESP_BLE_CONN_PARAM_UNDEF)) + +/// UUID type +typedef struct { +#define ESP_UUID_LEN_16 2 +#define ESP_UUID_LEN_32 4 +#define ESP_UUID_LEN_128 16 + uint16_t len; /*!< UUID length, 16bit, 32bit or 128bit */ + union { + uint16_t uuid16; /*!< 16bit UUID */ + uint32_t uuid32; /*!< 32bit UUID */ + uint8_t uuid128[ESP_UUID_LEN_128]; /*!< 128bit UUID */ + } uuid; /*!< UUID */ +} __attribute__((packed)) esp_bt_uuid_t; + +/// Bluetooth device type +typedef enum { + ESP_BT_DEVICE_TYPE_BREDR = 0x01, + ESP_BT_DEVICE_TYPE_BLE = 0x02, + ESP_BT_DEVICE_TYPE_DUMO = 0x03, +} esp_bt_dev_type_t; + +/// Bluetooth address length +#define ESP_BD_ADDR_LEN 6 + +/// Bluetooth device address +typedef uint8_t esp_bd_addr_t[ESP_BD_ADDR_LEN]; + +/// BLE device address type +typedef enum { + BLE_ADDR_TYPE_PUBLIC = 0x00, + BLE_ADDR_TYPE_RANDOM = 0x01, + BLE_ADDR_TYPE_RPA_PUBLIC = 0x02, + BLE_ADDR_TYPE_RPA_RANDOM = 0x03, +} esp_ble_addr_type_t; + +/// white list address type +typedef enum { + BLE_WL_ADDR_TYPE_PUBLIC = 0x00, + BLE_WL_ADDR_TYPE_RANDOM = 0x01, +} esp_ble_wl_addr_type_t; + +/// Used to exchange the encryption key in the init key & response key +#define ESP_BLE_ENC_KEY_MASK (1 << 0) /* relate to BTM_BLE_ENC_KEY_MASK in stack/btm_api.h */ +/// Used to exchange the IRK key in the init key & response key +#define ESP_BLE_ID_KEY_MASK (1 << 1) /* relate to BTM_BLE_ID_KEY_MASK in stack/btm_api.h */ +/// Used to exchange the CSRK key in the init key & response key +#define ESP_BLE_CSR_KEY_MASK (1 << 2) /* relate to BTM_BLE_CSR_KEY_MASK in stack/btm_api.h */ +/// Used to exchange the link key(this key just used in the BLE & BR/EDR coexist mode) in the init key & response key +#define ESP_BLE_LINK_KEY_MASK (1 << 3) /* relate to BTM_BLE_LINK_KEY_MASK in stack/btm_api.h */ +typedef uint8_t esp_ble_key_mask_t; /* the key mask type */ + +/// Minimum of the application id +#define ESP_APP_ID_MIN 0x0000 +/// Maximum of the application id +#define ESP_APP_ID_MAX 0x7fff + +#define ESP_BD_ADDR_STR "%02x:%02x:%02x:%02x:%02x:%02x" +#define ESP_BD_ADDR_HEX(addr) addr[0], addr[1], addr[2], addr[3], addr[4], addr[5] + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_BT_DEFS_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_device.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_device.h new file mode 100644 index 00000000..3e2bb794 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_device.h @@ -0,0 +1,58 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_BT_DEVICE_H__ +#define __ESP_BT_DEVICE_H__ + +#include +#include +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * + * @brief Get bluetooth device address. Must use after "esp_bluedroid_enable". + * + * @return bluetooth device address (six bytes), or NULL if bluetooth stack is not enabled + */ +const uint8_t *esp_bt_dev_get_address(void); + + +/** + * @brief Set bluetooth device name. This function should be called after esp_bluedroid_enable() + * completes successfully. + * + * A BR/EDR/LE device type shall have a single Bluetooth device name which shall be + * identical irrespective of the physical channel used to perform the name discovery procedure. + * + * @param[in] name : device name to be set + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_ARG : if name is NULL pointer or empty, or string length out of limit + * - ESP_ERR_INVALID_STATE : if bluetooth stack is not yet enabled + * - ESP_FAIL : others + */ +esp_err_t esp_bt_dev_set_device_name(const char *name); + +#ifdef __cplusplus +} +#endif + + +#endif /* __ESP_BT_DEVICE_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_main.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_main.h new file mode 100644 index 00000000..9a5b7591 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_bt_main.h @@ -0,0 +1,81 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_BT_MAIN_H__ +#define __ESP_BT_MAIN_H__ + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Bluetooth stack status type, to indicate whether the bluetooth stack is ready. + */ +typedef enum { + ESP_BLUEDROID_STATUS_UNINITIALIZED = 0, /*!< Bluetooth not initialized */ + ESP_BLUEDROID_STATUS_INITIALIZED, /*!< Bluetooth initialized but not enabled */ + ESP_BLUEDROID_STATUS_ENABLED /*!< Bluetooth initialized and enabled */ +} esp_bluedroid_status_t; + +/** + * @brief Get bluetooth stack status + * + * @return Bluetooth stack status + * + */ +esp_bluedroid_status_t esp_bluedroid_get_status(void); + +/** + * @brief Enable bluetooth, must after esp_bluedroid_init(). + * + * @return + * - ESP_OK : Succeed + * - Other : Failed + */ +esp_err_t esp_bluedroid_enable(void); + +/** + * @brief Disable bluetooth, must prior to esp_bluedroid_deinit(). + * + * @return + * - ESP_OK : Succeed + * - Other : Failed + */ +esp_err_t esp_bluedroid_disable(void); + +/** + * @brief Init and alloc the resource for bluetooth, must be prior to every bluetooth stuff. + * + * @return + * - ESP_OK : Succeed + * - Other : Failed + */ +esp_err_t esp_bluedroid_init(void); + +/** + * @brief Deinit and free the resource for bluetooth, must be after every bluetooth stuff. + * + * @return + * - ESP_OK : Succeed + * - Other : Failed + */ +esp_err_t esp_bluedroid_deinit(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_BT_MAIN_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h new file mode 100644 index 00000000..ce309935 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_ble_api.h @@ -0,0 +1,2154 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_GAP_BLE_API_H__ +#define __ESP_GAP_BLE_API_H__ + +#include +#include + +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/**@{ + * BLE_ADV_DATA_FLAG data flag bit definition used for advertising data flag + */ +#define ESP_BLE_ADV_FLAG_LIMIT_DISC (0x01 << 0) +#define ESP_BLE_ADV_FLAG_GEN_DISC (0x01 << 1) +#define ESP_BLE_ADV_FLAG_BREDR_NOT_SPT (0x01 << 2) +#define ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT (0x01 << 3) +#define ESP_BLE_ADV_FLAG_DMT_HOST_SPT (0x01 << 4) +#define ESP_BLE_ADV_FLAG_NON_LIMIT_DISC (0x00 ) +/** + * @} + */ + +/* relate to BTM_LE_KEY_xxx in stack/btm_api.h */ +#define ESP_LE_KEY_NONE 0 /* relate to BTM_LE_KEY_NONE in stack/btm_api.h */ +#define ESP_LE_KEY_PENC (1 << 0) /*!< encryption key, encryption information of peer device */ /* relate to BTM_LE_KEY_PENC in stack/btm_api.h */ +#define ESP_LE_KEY_PID (1 << 1) /*!< identity key of the peer device */ /* relate to BTM_LE_KEY_PID in stack/btm_api.h */ +#define ESP_LE_KEY_PCSRK (1 << 2) /*!< peer SRK */ /* relate to BTM_LE_KEY_PCSRK in stack/btm_api.h */ +#define ESP_LE_KEY_PLK (1 << 3) /*!< Link key*/ /* relate to BTM_LE_KEY_PLK in stack/btm_api.h */ +#define ESP_LE_KEY_LLK (ESP_LE_KEY_PLK << 4) /* relate to BTM_LE_KEY_LLK in stack/btm_api.h */ +#define ESP_LE_KEY_LENC (ESP_LE_KEY_PENC << 4) /*!< master role security information:div */ /* relate to BTM_LE_KEY_LENC in stack/btm_api.h */ +#define ESP_LE_KEY_LID (ESP_LE_KEY_PID << 4) /*!< master device ID key */ /* relate to BTM_LE_KEY_LID in stack/btm_api.h */ +#define ESP_LE_KEY_LCSRK (ESP_LE_KEY_PCSRK << 4) /*!< local CSRK has been deliver to peer */ /* relate to BTM_LE_KEY_LCSRK in stack/btm_api.h */ +typedef uint8_t esp_ble_key_type_t; + +/* relate to BTM_LE_AUTH_xxx in stack/btm_api.h */ +#define ESP_LE_AUTH_NO_BOND 0x00 /*!< 0*/ /* relate to BTM_LE_AUTH_NO_BOND in stack/btm_api.h */ +#define ESP_LE_AUTH_BOND 0x01 /*!< 1 << 0 */ /* relate to BTM_LE_AUTH_BOND in stack/btm_api.h */ +#define ESP_LE_AUTH_REQ_MITM (1 << 2) /*!< 1 << 2 */ /* relate to BTM_LE_AUTH_REQ_MITM in stack/btm_api.h */ +#define ESP_LE_AUTH_REQ_BOND_MITM (ESP_LE_AUTH_BOND | ESP_LE_AUTH_REQ_MITM)/*!< 0101*/ +#define ESP_LE_AUTH_REQ_SC_ONLY (1 << 3) /*!< 1 << 3 */ /* relate to BTM_LE_AUTH_REQ_SC_ONLY in stack/btm_api.h */ +#define ESP_LE_AUTH_REQ_SC_BOND (ESP_LE_AUTH_BOND | ESP_LE_AUTH_REQ_SC_ONLY) /*!< 1001 */ /* relate to BTM_LE_AUTH_REQ_SC_BOND in stack/btm_api.h */ +#define ESP_LE_AUTH_REQ_SC_MITM (ESP_LE_AUTH_REQ_MITM | ESP_LE_AUTH_REQ_SC_ONLY) /*!< 1100 */ /* relate to BTM_LE_AUTH_REQ_SC_MITM in stack/btm_api.h */ +#define ESP_LE_AUTH_REQ_SC_MITM_BOND (ESP_LE_AUTH_REQ_MITM | ESP_LE_AUTH_REQ_SC_ONLY | ESP_LE_AUTH_BOND) /*!< 1101 */ /* relate to BTM_LE_AUTH_REQ_SC_MITM_BOND in stack/btm_api.h */ +typedef uint8_t esp_ble_auth_req_t; /*!< combination of the above bit pattern */ + +#define ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE 0 +#define ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE 1 + +#define ESP_BLE_OOB_DISABLE 0 +#define ESP_BLE_OOB_ENABLE 1 + +/* relate to BTM_IO_CAP_xxx in stack/btm_api.h */ +#define ESP_IO_CAP_OUT 0 /*!< DisplayOnly */ /* relate to BTM_IO_CAP_OUT in stack/btm_api.h */ +#define ESP_IO_CAP_IO 1 /*!< DisplayYesNo */ /* relate to BTM_IO_CAP_IO in stack/btm_api.h */ +#define ESP_IO_CAP_IN 2 /*!< KeyboardOnly */ /* relate to BTM_IO_CAP_IN in stack/btm_api.h */ +#define ESP_IO_CAP_NONE 3 /*!< NoInputNoOutput */ /* relate to BTM_IO_CAP_NONE in stack/btm_api.h */ +#define ESP_IO_CAP_KBDISP 4 /*!< Keyboard display */ /* relate to BTM_IO_CAP_KBDISP in stack/btm_api.h */ + +#define ESP_BLE_APPEARANCE_UNKNOWN 0x0000 /* relate to BTM_BLE_APPEARANCE_UNKNOWN in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_PHONE 0x0040 /* relate to BTM_BLE_APPEARANCE_GENERIC_PHONE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_COMPUTER 0x0080 /* relate to BTM_BLE_APPEARANCE_GENERIC_COMPUTER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_WATCH 0x00C0 /* relate to BTM_BLE_APPEARANCE_GENERIC_WATCH in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_SPORTS_WATCH 0x00C1 /* relate to BTM_BLE_APPEARANCE_SPORTS_WATCH in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_CLOCK 0x0100 /* relate to BTM_BLE_APPEARANCE_GENERIC_CLOCK in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_DISPLAY 0x0140 /* relate to BTM_BLE_APPEARANCE_GENERIC_DISPLAY in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_REMOTE 0x0180 /* relate to BTM_BLE_APPEARANCE_GENERIC_REMOTE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_EYEGLASSES 0x01C0 /* relate to BTM_BLE_APPEARANCE_GENERIC_EYEGLASSES in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_TAG 0x0200 /* relate to BTM_BLE_APPEARANCE_GENERIC_TAG in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_KEYRING 0x0240 /* relate to BTM_BLE_APPEARANCE_GENERIC_KEYRING in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER 0x0280 /* relate to BTM_BLE_APPEARANCE_GENERIC_MEDIA_PLAYER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER 0x02C0 /* relate to BTM_BLE_APPEARANCE_GENERIC_BARCODE_SCANNER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_THERMOMETER 0x0300 /* relate to BTM_BLE_APPEARANCE_GENERIC_THERMOMETER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_THERMOMETER_EAR 0x0301 /* relate to BTM_BLE_APPEARANCE_THERMOMETER_EAR in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_HEART_RATE 0x0340 /* relate to BTM_BLE_APPEARANCE_GENERIC_HEART_RATE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HEART_RATE_BELT 0x0341 /* relate to BTM_BLE_APPEARANCE_HEART_RATE_BELT in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE 0x0380 /* relate to BTM_BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_BLOOD_PRESSURE_ARM 0x0381 /* relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_ARM in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST 0x0382 /* relate to BTM_BLE_APPEARANCE_BLOOD_PRESSURE_WRIST in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_HID 0x03C0 /* relate to BTM_BLE_APPEARANCE_GENERIC_HID in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_KEYBOARD 0x03C1 /* relate to BTM_BLE_APPEARANCE_HID_KEYBOARD in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_MOUSE 0x03C2 /* relate to BTM_BLE_APPEARANCE_HID_MOUSE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_JOYSTICK 0x03C3 /* relate to BTM_BLE_APPEARANCE_HID_JOYSTICK in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_GAMEPAD 0x03C4 /* relate to BTM_BLE_APPEARANCE_HID_GAMEPAD in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_DIGITIZER_TABLET 0x03C5 /* relate to BTM_BLE_APPEARANCE_HID_DIGITIZER_TABLET in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_CARD_READER 0x03C6 /* relate to BTM_BLE_APPEARANCE_HID_CARD_READER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_DIGITAL_PEN 0x03C7 /* relate to BTM_BLE_APPEARANCE_HID_DIGITAL_PEN in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_HID_BARCODE_SCANNER 0x03C8 /* relate to BTM_BLE_APPEARANCE_HID_BARCODE_SCANNER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_GLUCOSE 0x0400 /* relate to BTM_BLE_APPEARANCE_GENERIC_GLUCOSE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_WALKING 0x0440 /* relate to BTM_BLE_APPEARANCE_GENERIC_WALKING in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_WALKING_IN_SHOE 0x0441 /* relate to BTM_BLE_APPEARANCE_WALKING_IN_SHOE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_WALKING_ON_SHOE 0x0442 /* relate to BTM_BLE_APPEARANCE_WALKING_ON_SHOE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_WALKING_ON_HIP 0x0443 /* relate to BTM_BLE_APPEARANCE_WALKING_ON_HIP in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_CYCLING 0x0480 /* relate to BTM_BLE_APPEARANCE_GENERIC_CYCLING in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_CYCLING_COMPUTER 0x0481 /* relate to BTM_BLE_APPEARANCE_CYCLING_COMPUTER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_CYCLING_SPEED 0x0482 /* relate to BTM_BLE_APPEARANCE_CYCLING_SPEED in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_CYCLING_CADENCE 0x0483 /* relate to BTM_BLE_APPEARANCE_CYCLING_CADENCE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_CYCLING_POWER 0x0484 /* relate to BTM_BLE_APPEARANCE_CYCLING_POWER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_CYCLING_SPEED_CADENCE 0x0485 /* relate to BTM_BLE_APPEARANCE_CYCLING_SPEED_CADENCE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER 0x0C40 /* relate to BTM_BLE_APPEARANCE_GENERIC_PULSE_OXIMETER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP 0x0C41 /* relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_FINGERTIP in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_PULSE_OXIMETER_WRIST 0x0C42 /* relate to BTM_BLE_APPEARANCE_PULSE_OXIMETER_WRIST in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_WEIGHT 0x0C80 /* relate to BTM_BLE_APPEARANCE_GENERIC_WEIGHT in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE 0x0CC0 /* relate to BTM_BLE_APPEARANCE_GENERIC_PERSONAL_MOBILITY_DEVICE in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_POWERED_WHEELCHAIR 0x0CC1 /* relate to BTM_BLE_APPEARANCE_POWERED_WHEELCHAIR in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_MOBILITY_SCOOTER 0x0CC2 /* relate to BTM_BLE_APPEARANCE_MOBILITY_SCOOTER in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR 0x0D00 /* relate to BTM_BLE_APPEARANCE_GENERIC_CONTINUOUS_GLUCOSE_MONITOR in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_INSULIN_PUMP 0x0D40 /* relate to BTM_BLE_APPEARANCE_GENERIC_INSULIN_PUMP in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP 0x0D41 /* relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_DURABLE_PUMP in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP 0x0D44 /* relate to BTM_BLE_APPEARANCE_INSULIN_PUMP_PATCH_PUMP in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_INSULIN_PEN 0x0D48 /* relate to BTM_BLE_APPEARANCE_INSULIN_PEN in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY 0x0D80 /* relate to BTM_BLE_APPEARANCE_GENERIC_MEDICATION_DELIVERY in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS 0x1440 /* relate to BTM_BLE_APPEARANCE_GENERIC_OUTDOOR_SPORTS in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION 0x1441 /* relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV 0x1442 /* relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_AND_NAV in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD 0x1443 /* relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD in stack/btm_ble_api.h */ +#define ESP_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV 0x1444 /* relate to BTM_BLE_APPEARANCE_OUTDOOR_SPORTS_LOCATION_POD_AND_NAV in stack/btm_ble_api.h */ + +typedef uint8_t esp_ble_io_cap_t; /*!< combination of the io capability */ + +/// GAP BLE callback event type +typedef enum { +#if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT = 0, /*!< When advertising data set complete, the event comes */ + ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT, /*!< When scan response data set complete, the event comes */ + ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT, /*!< When scan parameters set complete, the event comes */ + ESP_GAP_BLE_SCAN_RESULT_EVT, /*!< When one scan result ready, the event comes each time */ + ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT, /*!< When raw advertising data set complete, the event comes */ + ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT, /*!< When raw advertising data set complete, the event comes */ + ESP_GAP_BLE_ADV_START_COMPLETE_EVT, /*!< When start advertising complete, the event comes */ + ESP_GAP_BLE_SCAN_START_COMPLETE_EVT, /*!< When start scan complete, the event comes */ +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_AUTH_CMPL_EVT = 8, /* Authentication complete indication. */ + ESP_GAP_BLE_KEY_EVT, /* BLE key event for peer device keys */ + ESP_GAP_BLE_SEC_REQ_EVT, /* BLE security request */ + ESP_GAP_BLE_PASSKEY_NOTIF_EVT, /* passkey notification event */ + ESP_GAP_BLE_PASSKEY_REQ_EVT, /* passkey request event */ + ESP_GAP_BLE_OOB_REQ_EVT, /* OOB request event */ + ESP_GAP_BLE_LOCAL_IR_EVT, /* BLE local IR event */ + ESP_GAP_BLE_LOCAL_ER_EVT, /* BLE local ER event */ + ESP_GAP_BLE_NC_REQ_EVT, /* Numeric Comparison request event */ +#if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT, /*!< When stop adv complete, the event comes */ + ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT, /*!< When stop scan complete, the event comes */ +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT = 19, /*!< When set the static rand address complete, the event comes */ + ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT, /*!< When update connection parameters complete, the event comes */ + ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT, /*!< When set pkt length complete, the event comes */ + ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT, /*!< When Enable/disable privacy on the local device complete, the event comes */ + ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT, /*!< When remove the bond device complete, the event comes */ + ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT, /*!< When clear the bond device clear complete, the event comes */ + ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT, /*!< When get the bond device list complete, the event comes */ + ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT, /*!< When read the rssi complete, the event comes */ + ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT, /*!< When add or remove whitelist complete, the event comes */ +#if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT, /*!< When update duplicate exceptional list complete, the event comes */ +#endif //#if (BLE_42_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_SET_CHANNELS_EVT = 29, /*!< When setting BLE channels complete, the event comes */ +#if (BLE_50_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_READ_PHY_COMPLETE_EVT, + ESP_GAP_BLE_SET_PREFERED_DEFAULT_PHY_COMPLETE_EVT, + ESP_GAP_BLE_SET_PREFERED_PHY_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT, + ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT, + ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT, + ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT, + ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT, + ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT, + ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT, + ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT, + ESP_GAP_BLE_EXT_ADV_REPORT_EVT, + ESP_GAP_BLE_SCAN_TIMEOUT_EVT, + ESP_GAP_BLE_ADV_TERMINATED_EVT, + ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT, + ESP_GAP_BLE_CHANNEL_SELETE_ALGORITHM_EVT, + ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT, + ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT, + ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT, +#endif // #if (BLE_50_FEATURE_SUPPORT == TRUE) + ESP_GAP_BLE_EVT_MAX, +} esp_gap_ble_cb_event_t; + +#define ESP_GAP_BLE_CHANNELS_LEN 5 +typedef uint8_t esp_gap_ble_channels[ESP_GAP_BLE_CHANNELS_LEN]; + +/// This is the old name, just for backwards compatibility +#define ESP_GAP_BLE_ADD_WHITELIST_COMPLETE_EVT ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT + +/// Advertising data maximum length +#define ESP_BLE_ADV_DATA_LEN_MAX 31 +/// Scan response data maximum length +#define ESP_BLE_SCAN_RSP_DATA_LEN_MAX 31 + +/* relate to BTM_BLE_AD_TYPE_xxx in stack/btm_ble_api.h */ +/// The type of advertising data(not adv_type) +typedef enum { + ESP_BLE_AD_TYPE_FLAG = 0x01, /* relate to BTM_BLE_AD_TYPE_FLAG in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_16SRV_PART = 0x02, /* relate to BTM_BLE_AD_TYPE_16SRV_PART in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_16SRV_CMPL = 0x03, /* relate to BTM_BLE_AD_TYPE_16SRV_CMPL in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_32SRV_PART = 0x04, /* relate to BTM_BLE_AD_TYPE_32SRV_PART in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_32SRV_CMPL = 0x05, /* relate to BTM_BLE_AD_TYPE_32SRV_CMPL in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_128SRV_PART = 0x06, /* relate to BTM_BLE_AD_TYPE_128SRV_PART in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_128SRV_CMPL = 0x07, /* relate to BTM_BLE_AD_TYPE_128SRV_CMPL in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_NAME_SHORT = 0x08, /* relate to BTM_BLE_AD_TYPE_NAME_SHORT in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_NAME_CMPL = 0x09, /* relate to BTM_BLE_AD_TYPE_NAME_CMPL in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_TX_PWR = 0x0A, /* relate to BTM_BLE_AD_TYPE_TX_PWR in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_DEV_CLASS = 0x0D, /* relate to BTM_BLE_AD_TYPE_DEV_CLASS in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SM_TK = 0x10, /* relate to BTM_BLE_AD_TYPE_SM_TK in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SM_OOB_FLAG = 0x11, /* relate to BTM_BLE_AD_TYPE_SM_OOB_FLAG in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_INT_RANGE = 0x12, /* relate to BTM_BLE_AD_TYPE_INT_RANGE in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SOL_SRV_UUID = 0x14, /* relate to BTM_BLE_AD_TYPE_SOL_SRV_UUID in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_128SOL_SRV_UUID = 0x15, /* relate to BTM_BLE_AD_TYPE_128SOL_SRV_UUID in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SERVICE_DATA = 0x16, /* relate to BTM_BLE_AD_TYPE_SERVICE_DATA in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_PUBLIC_TARGET = 0x17, /* relate to BTM_BLE_AD_TYPE_PUBLIC_TARGET in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_RANDOM_TARGET = 0x18, /* relate to BTM_BLE_AD_TYPE_RANDOM_TARGET in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_APPEARANCE = 0x19, /* relate to BTM_BLE_AD_TYPE_APPEARANCE in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_ADV_INT = 0x1A, /* relate to BTM_BLE_AD_TYPE_ADV_INT in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_LE_DEV_ADDR = 0x1b, /* relate to BTM_BLE_AD_TYPE_LE_DEV_ADDR in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_LE_ROLE = 0x1c, /* relate to BTM_BLE_AD_TYPE_LE_ROLE in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SPAIR_C256 = 0x1d, /* relate to BTM_BLE_AD_TYPE_SPAIR_C256 in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_SPAIR_R256 = 0x1e, /* relate to BTM_BLE_AD_TYPE_SPAIR_R256 in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_32SOL_SRV_UUID = 0x1f, /* relate to BTM_BLE_AD_TYPE_32SOL_SRV_UUID in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_32SERVICE_DATA = 0x20, /* relate to BTM_BLE_AD_TYPE_32SERVICE_DATA in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_128SERVICE_DATA = 0x21, /* relate to BTM_BLE_AD_TYPE_128SERVICE_DATA in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_LE_SECURE_CONFIRM = 0x22, /* relate to BTM_BLE_AD_TYPE_LE_SECURE_CONFIRM in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_LE_SECURE_RANDOM = 0x23, /* relate to BTM_BLE_AD_TYPE_LE_SECURE_RANDOM in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_URI = 0x24, /* relate to BTM_BLE_AD_TYPE_URI in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_INDOOR_POSITION = 0x25, /* relate to BTM_BLE_AD_TYPE_INDOOR_POSITION in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_TRANS_DISC_DATA = 0x26, /* relate to BTM_BLE_AD_TYPE_TRANS_DISC_DATA in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_LE_SUPPORT_FEATURE = 0x27, /* relate to BTM_BLE_AD_TYPE_LE_SUPPORT_FEATURE in stack/btm_ble_api.h */ + ESP_BLE_AD_TYPE_CHAN_MAP_UPDATE = 0x28, /* relate to BTM_BLE_AD_TYPE_CHAN_MAP_UPDATE in stack/btm_ble_api.h */ + ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE = 0xFF, /* relate to BTM_BLE_AD_MANUFACTURER_SPECIFIC_TYPE in stack/btm_ble_api.h */ +} esp_ble_adv_data_type; + +/// Advertising mode +typedef enum { + ADV_TYPE_IND = 0x00, + ADV_TYPE_DIRECT_IND_HIGH = 0x01, + ADV_TYPE_SCAN_IND = 0x02, + ADV_TYPE_NONCONN_IND = 0x03, + ADV_TYPE_DIRECT_IND_LOW = 0x04, +} esp_ble_adv_type_t; + +/// Advertising channel mask +typedef enum { + ADV_CHNL_37 = 0x01, + ADV_CHNL_38 = 0x02, + ADV_CHNL_39 = 0x04, + ADV_CHNL_ALL = 0x07, +} esp_ble_adv_channel_t; + +typedef enum { + ///Allow both scan and connection requests from anyone + ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY = 0x00, + ///Allow both scan req from White List devices only and connection req from anyone + ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY, + ///Allow both scan req from anyone and connection req from White List devices only + ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST, + ///Allow scan and connection requests from White List devices only + ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST, + ///Enumeration end value for advertising filter policy value check +} esp_ble_adv_filter_t; + + +/* relate to BTA_DM_BLE_SEC_xxx in bta/bta_api.h */ +typedef enum { + ESP_BLE_SEC_ENCRYPT = 1, /* relate to BTA_DM_BLE_SEC_ENCRYPT in bta/bta_api.h. If the device has already + bonded, the stack will used LTK to encrypt with the remote device directly. + Else if the device hasn't bonded, the stack will used the default authentication request + used the esp_ble_gap_set_security_param function set by the user. */ + ESP_BLE_SEC_ENCRYPT_NO_MITM, /* relate to BTA_DM_BLE_SEC_ENCRYPT_NO_MITM in bta/bta_api.h. If the device has already + bonded, the stack will check the LTK Whether the authentication request has been met, if met, used the LTK + to encrypt with the remote device directly, else Re-pair with the remote device. + Else if the device hasn't bonded, the stack will used NO MITM authentication request in the current link instead of + used the authreq in the esp_ble_gap_set_security_param function set by the user. */ + ESP_BLE_SEC_ENCRYPT_MITM, /* relate to BTA_DM_BLE_SEC_ENCRYPT_MITM in bta/bta_api.h. If the device has already + bonded, the stack will check the LTK Whether the authentication request has been met, if met, used the LTK + to encrypt with the remote device directly, else Re-pair with the remote device. + Else if the device hasn't bonded, the stack will used MITM authentication request in the current link instead of + used the authreq in the esp_ble_gap_set_security_param function set by the user. */ +}esp_ble_sec_act_t; + +typedef enum { + ESP_BLE_SM_PASSKEY = 0, + /* Authentication requirements of local device */ + ESP_BLE_SM_AUTHEN_REQ_MODE, + /* The IO capability of local device */ + ESP_BLE_SM_IOCAP_MODE, + /* Initiator Key Distribution/Generation */ + ESP_BLE_SM_SET_INIT_KEY, + /* Responder Key Distribution/Generation */ + ESP_BLE_SM_SET_RSP_KEY, + /* Maximum Encryption key size to support */ + ESP_BLE_SM_MAX_KEY_SIZE, + /* Minimum Encryption key size requirement from Peer */ + ESP_BLE_SM_MIN_KEY_SIZE, + /* Set static Passkey */ + ESP_BLE_SM_SET_STATIC_PASSKEY, + /* Reset static Passkey */ + ESP_BLE_SM_CLEAR_STATIC_PASSKEY, + /* Accept only specified SMP Authentication requirement */ + ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, + /* Enable/Disable OOB support */ + ESP_BLE_SM_OOB_SUPPORT, + /* Appl encryption key size */ + ESP_BLE_APP_ENC_KEY_SIZE, + ESP_BLE_SM_MAX_PARAM, +} esp_ble_sm_param_t; + +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/// Advertising parameters +typedef struct { + uint16_t adv_int_min; /*!< Minimum advertising interval for + undirected and low duty cycle directed advertising. + Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) + Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec */ + uint16_t adv_int_max; /*!< Maximum advertising interval for + undirected and low duty cycle directed advertising. + Range: 0x0020 to 0x4000 Default: N = 0x0800 (1.28 second) + Time = N * 0.625 msec Time Range: 20 ms to 10.24 sec Advertising max interval */ + esp_ble_adv_type_t adv_type; /*!< Advertising type */ + esp_ble_addr_type_t own_addr_type; /*!< Owner bluetooth device address type */ + esp_bd_addr_t peer_addr; /*!< Peer device bluetooth device address */ + esp_ble_addr_type_t peer_addr_type; /*!< Peer device bluetooth device address type, only support public address type and random address type */ + esp_ble_adv_channel_t channel_map; /*!< Advertising channel map */ + esp_ble_adv_filter_t adv_filter_policy; /*!< Advertising filter policy */ +} esp_ble_adv_params_t; + +/// Advertising data content, according to "Supplement to the Bluetooth Core Specification" +typedef struct { + bool set_scan_rsp; /*!< Set this advertising data as scan response or not*/ + bool include_name; /*!< Advertising data include device name or not */ + bool include_txpower; /*!< Advertising data include TX power */ + int min_interval; /*!< Advertising data show slave preferred connection min interval. + The connection interval in the following manner: + connIntervalmin = Conn_Interval_Min * 1.25 ms + Conn_Interval_Min range: 0x0006 to 0x0C80 + Value of 0xFFFF indicates no specific minimum. + Values not defined above are reserved for future use.*/ + + int max_interval; /*!< Advertising data show slave preferred connection max interval. + The connection interval in the following manner: + connIntervalmax = Conn_Interval_Max * 1.25 ms + Conn_Interval_Max range: 0x0006 to 0x0C80 + Conn_Interval_Max shall be equal to or greater than the Conn_Interval_Min. + Value of 0xFFFF indicates no specific maximum. + Values not defined above are reserved for future use.*/ + + int appearance; /*!< External appearance of device */ + uint16_t manufacturer_len; /*!< Manufacturer data length */ + uint8_t *p_manufacturer_data; /*!< Manufacturer data point */ + uint16_t service_data_len; /*!< Service data length */ + uint8_t *p_service_data; /*!< Service data point */ + uint16_t service_uuid_len; /*!< Service uuid length */ + uint8_t *p_service_uuid; /*!< Service uuid array point */ + uint8_t flag; /*!< Advertising flag of discovery mode, see BLE_ADV_DATA_FLAG detail */ +} esp_ble_adv_data_t; + +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + +/// Ble scan type +typedef enum { + BLE_SCAN_TYPE_PASSIVE = 0x0, /*!< Passive scan */ + BLE_SCAN_TYPE_ACTIVE = 0x1, /*!< Active scan */ +} esp_ble_scan_type_t; + +/// Ble scan filter type +typedef enum { + BLE_SCAN_FILTER_ALLOW_ALL = 0x0, /*!< Accept all : + 1. advertisement packets except directed advertising packets not addressed to this device (default). */ + BLE_SCAN_FILTER_ALLOW_ONLY_WLST = 0x1, /*!< Accept only : + 1. advertisement packets from devices where the advertiser’s address is in the White list. + 2. Directed advertising packets which are not addressed for this device shall be ignored. */ + BLE_SCAN_FILTER_ALLOW_UND_RPA_DIR = 0x2, /*!< Accept all : + 1. undirected advertisement packets, and + 2. directed advertising packets where the initiator address is a resolvable private address, and + 3. directed advertising packets addressed to this device. */ + BLE_SCAN_FILTER_ALLOW_WLIST_RPA_DIR = 0x3, /*!< Accept all : + 1. advertisement packets from devices where the advertiser’s address is in the White list, and + 2. directed advertising packets where the initiator address is a resolvable private address, and + 3. directed advertising packets addressed to this device.*/ +} esp_ble_scan_filter_t; + +/// Ble scan duplicate type +typedef enum { + BLE_SCAN_DUPLICATE_DISABLE = 0x0, /*!< the Link Layer should generate advertising reports to the host for each packet received */ + BLE_SCAN_DUPLICATE_ENABLE = 0x1, /*!< the Link Layer should filter out duplicate advertising reports to the Host */ + BLE_SCAN_DUPLICATE_MAX = 0x2, /*!< 0x02 – 0xFF, Reserved for future use */ +} esp_ble_scan_duplicate_t; +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/// Ble scan parameters +typedef struct { + esp_ble_scan_type_t scan_type; /*!< Scan type */ + esp_ble_addr_type_t own_addr_type; /*!< Owner address type */ + esp_ble_scan_filter_t scan_filter_policy; /*!< Scan filter policy */ + uint16_t scan_interval; /*!< Scan interval. This is defined as the time interval from + when the Controller started its last LE scan until it begins the subsequent LE scan. + Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) + Time = N * 0.625 msec + Time Range: 2.5 msec to 10.24 seconds*/ + uint16_t scan_window; /*!< Scan window. The duration of the LE scan. LE_Scan_Window + shall be less than or equal to LE_Scan_Interval + Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms) + Time = N * 0.625 msec + Time Range: 2.5 msec to 10240 msec */ + esp_ble_scan_duplicate_t scan_duplicate; /*!< The Scan_Duplicates parameter controls whether the Link Layer should filter out + duplicate advertising reports (BLE_SCAN_DUPLICATE_ENABLE) to the Host, or if the Link Layer should generate + advertising reports for each packet received */ +} esp_ble_scan_params_t; +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) +/// connection parameters information +typedef struct { + uint16_t interval; /*!< connection interval */ + uint16_t latency; /*!< Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 */ + uint16_t timeout; /*!< Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. + Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec + Time Range: 100 msec to 32 seconds */ +} esp_gap_conn_params_t; + +/// Connection update parameters +typedef struct { + esp_bd_addr_t bda; /*!< Bluetooth device address */ + uint16_t min_int; /*!< Min connection interval */ + uint16_t max_int; /*!< Max connection interval */ + uint16_t latency; /*!< Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 */ + uint16_t timeout; /*!< Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. + Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec + Time Range: 100 msec to 32 seconds */ +} esp_ble_conn_update_params_t; + +/** +* @brief BLE pkt date length keys +*/ +typedef struct +{ + uint16_t rx_len; /*!< pkt rx data length value */ + uint16_t tx_len; /*!< pkt tx data length value */ +}esp_ble_pkt_data_length_params_t; + +/** +* @brief BLE encryption keys +*/ +typedef struct +{ + esp_bt_octet16_t ltk; /*!< The long term key*/ + esp_bt_octet8_t rand; /*!< The random number*/ + uint16_t ediv; /*!< The ediv value*/ + uint8_t sec_level; /*!< The security level of the security link*/ + uint8_t key_size; /*!< The key size(7~16) of the security link*/ +} esp_ble_penc_keys_t; /*!< The key type*/ + +/** +* @brief BLE CSRK keys +*/ +typedef struct +{ + uint32_t counter; /*!< The counter */ + esp_bt_octet16_t csrk; /*!< The csrk key */ + uint8_t sec_level; /*!< The security level */ +} esp_ble_pcsrk_keys_t; /*!< The pcsrk key type */ + +/** +* @brief BLE pid keys +*/ +typedef struct +{ + esp_bt_octet16_t irk; /*!< The irk value */ + esp_ble_addr_type_t addr_type; /*!< The address type */ + esp_bd_addr_t static_addr; /*!< The static address */ +} esp_ble_pid_keys_t; /*!< The pid key type */ + +/** +* @brief BLE Encryption reproduction keys +*/ +typedef struct +{ + esp_bt_octet16_t ltk; /*!< The long term key */ + uint16_t div; /*!< The div value */ + uint8_t key_size; /*!< The key size of the security link */ + uint8_t sec_level; /*!< The security level of the security link */ +} esp_ble_lenc_keys_t; /*!< The key type */ + +/** +* @brief BLE SRK keys +*/ +typedef struct +{ + uint32_t counter; /*!< The counter value */ + uint16_t div; /*!< The div value */ + uint8_t sec_level; /*!< The security level of the security link */ + esp_bt_octet16_t csrk; /*!< The csrk key value */ +} esp_ble_lcsrk_keys; /*!< The csrk key type */ + +/** +* @brief Structure associated with ESP_KEY_NOTIF_EVT +*/ +typedef struct +{ + esp_bd_addr_t bd_addr; /*!< peer address */ + uint32_t passkey; /*!< the numeric value for comparison. If just_works, do not show this number to UI */ +} esp_ble_sec_key_notif_t; /*!< BLE key notify type*/ + +/** +* @brief Structure of the security request +*/ +typedef struct +{ + esp_bd_addr_t bd_addr; /*!< peer address */ +} esp_ble_sec_req_t; /*!< BLE security request type*/ + +/** +* @brief union type of the security key value +*/ +typedef union +{ + esp_ble_penc_keys_t penc_key; /*!< received peer encryption key */ + esp_ble_pcsrk_keys_t pcsrk_key; /*!< received peer device SRK */ + esp_ble_pid_keys_t pid_key; /*!< peer device ID key */ + esp_ble_lenc_keys_t lenc_key; /*!< local encryption reproduction keys LTK = = d1(ER,DIV,0)*/ + esp_ble_lcsrk_keys lcsrk_key; /*!< local device CSRK = d1(ER,DIV,1)*/ +} esp_ble_key_value_t; /*!< ble key value type*/ + +/** +* @brief struct type of the bond key information value +*/ +typedef struct +{ + esp_ble_key_mask_t key_mask; /*!< the key mask to indicate witch key is present */ + esp_ble_penc_keys_t penc_key; /*!< received peer encryption key */ + esp_ble_pcsrk_keys_t pcsrk_key; /*!< received peer device SRK */ + esp_ble_pid_keys_t pid_key; /*!< peer device ID key */ +} esp_ble_bond_key_info_t; /*!< ble bond key information value type */ + +/** +* @brief struct type of the bond device value +*/ +typedef struct +{ + esp_bd_addr_t bd_addr; /*!< peer address */ + esp_ble_bond_key_info_t bond_key; /*!< the bond key information */ +} esp_ble_bond_dev_t; /*!< the ble bond device type */ + + +/** +* @brief union type of the security key value +*/ +typedef struct +{ + esp_bd_addr_t bd_addr; /*!< peer address */ + esp_ble_key_type_t key_type; /*!< key type of the security link */ + esp_ble_key_value_t p_key_value; /*!< the pointer to the key value */ +} esp_ble_key_t; /*!< the union to the ble key value type*/ + +/** +* @brief structure type of the ble local id keys value +*/ +typedef struct { + esp_bt_octet16_t ir; /*!< the 16 bits of the ir value */ + esp_bt_octet16_t irk; /*!< the 16 bits of the ir key value */ + esp_bt_octet16_t dhk; /*!< the 16 bits of the dh key value */ +} esp_ble_local_id_keys_t; /*!< the structure of the ble local id keys value type*/ + + +/** + * @brief Structure associated with ESP_AUTH_CMPL_EVT + */ +typedef struct +{ + esp_bd_addr_t bd_addr; /*!< BD address peer device. */ + bool key_present; /*!< Valid link key value in key element */ + esp_link_key key; /*!< Link key associated with peer device. */ + uint8_t key_type; /*!< The type of Link Key */ + bool success; /*!< TRUE of authentication succeeded, FALSE if failed. */ + uint8_t fail_reason; /*!< The HCI reason/error code for when success=FALSE */ + esp_ble_addr_type_t addr_type; /*!< Peer device address type */ + esp_bt_dev_type_t dev_type; /*!< Device type */ + esp_ble_auth_req_t auth_mode; /*!< authentication mode */ +} esp_ble_auth_cmpl_t; /*!< The ble authentication complete cb type */ + +/** + * @brief union associated with ble security + */ +typedef union +{ + esp_ble_sec_key_notif_t key_notif; /*!< passkey notification */ + esp_ble_sec_req_t ble_req; /*!< BLE SMP related request */ + esp_ble_key_t ble_key; /*!< BLE SMP keys used when pairing */ + esp_ble_local_id_keys_t ble_id_keys; /*!< BLE IR event */ + esp_ble_auth_cmpl_t auth_cmpl; /*!< Authentication complete indication. */ +} esp_ble_sec_t; /*!< BLE security type */ +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/// Sub Event of ESP_GAP_BLE_SCAN_RESULT_EVT +typedef enum { + ESP_GAP_SEARCH_INQ_RES_EVT = 0, /*!< Inquiry result for a peer device. */ + ESP_GAP_SEARCH_INQ_CMPL_EVT = 1, /*!< Inquiry complete. */ + ESP_GAP_SEARCH_DISC_RES_EVT = 2, /*!< Discovery result for a peer device. */ + ESP_GAP_SEARCH_DISC_BLE_RES_EVT = 3, /*!< Discovery result for BLE GATT based service on a peer device. */ + ESP_GAP_SEARCH_DISC_CMPL_EVT = 4, /*!< Discovery complete. */ + ESP_GAP_SEARCH_DI_DISC_CMPL_EVT = 5, /*!< Discovery complete. */ + ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT = 6, /*!< Search cancelled */ + ESP_GAP_SEARCH_INQ_DISCARD_NUM_EVT = 7, /*!< The number of pkt discarded by flow control */ +} esp_gap_search_evt_t; +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief Ble scan result event type, to indicate the + * result is scan response or advertising data or other + */ +typedef enum { + ESP_BLE_EVT_CONN_ADV = 0x00, /*!< Connectable undirected advertising (ADV_IND) */ + ESP_BLE_EVT_CONN_DIR_ADV = 0x01, /*!< Connectable directed advertising (ADV_DIRECT_IND) */ + ESP_BLE_EVT_DISC_ADV = 0x02, /*!< Scannable undirected advertising (ADV_SCAN_IND) */ + ESP_BLE_EVT_NON_CONN_ADV = 0x03, /*!< Non connectable undirected advertising (ADV_NONCONN_IND) */ + ESP_BLE_EVT_SCAN_RSP = 0x04, /*!< Scan Response (SCAN_RSP) */ +} esp_ble_evt_type_t; + +typedef enum{ + ESP_BLE_WHITELIST_REMOVE = 0X00, /*!< remove mac from whitelist */ + ESP_BLE_WHITELIST_ADD = 0X01, /*!< add address to whitelist */ +}esp_ble_wl_opration_t; +#if (BLE_42_FEATURE_SUPPORT == TRUE) +typedef enum { + ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_ADD = 0, /*!< Add device info into duplicate scan exceptional list */ + ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_REMOVE, /*!< Remove device info from duplicate scan exceptional list */ + ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, /*!< Clean duplicate scan exceptional list */ +} esp_bt_duplicate_exceptional_subcode_type_t; +#endif //#if (BLE_42_FEATURE_SUPPORT == TRUE) + +#define BLE_BIT(n) (1UL<<(n)) +#if (BLE_42_FEATURE_SUPPORT == TRUE) +typedef enum { + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_ADV_ADDR = 0, /*!< BLE advertising address , device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_LINK_ID, /*!< BLE mesh link ID, it is for BLE mesh, device info will be added into ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_BEACON_TYPE, /*!< BLE mesh beacon AD type, the format is | Len | 0x2B | Beacon Type | Beacon Data | */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROV_SRV_ADV, /*!< BLE mesh provisioning service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1827 | .... |` */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_INFO_MESH_PROXY_SRV_ADV, /*!< BLE mesh adv with proxy service uuid, the format is | 0x02 | 0x01 | flags | 0x03 | 0x03 | 0x1828 | .... |` */ +} esp_ble_duplicate_exceptional_info_type_t; + +typedef enum { + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ADDR_LIST = BLE_BIT(0), /*!< duplicate scan exceptional addr list */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_LINK_ID_LIST = BLE_BIT(1), /*!< duplicate scan exceptional mesh link ID list */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_BEACON_TYPE_LIST = BLE_BIT(2), /*!< duplicate scan exceptional mesh beacon type list */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROV_SRV_ADV_LIST = BLE_BIT(3), /*!< duplicate scan exceptional mesh adv with provisioning service uuid */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_MESH_PROXY_SRV_ADV_LIST = BLE_BIT(4), /*!< duplicate scan exceptional mesh adv with provisioning service uuid */ + ESP_BLE_DUPLICATE_SCAN_EXCEPTIONAL_ALL_LIST = 0xFFFF, /*!< duplicate scan exceptional all list */ +} esp_duplicate_scan_exceptional_list_type_t; + +typedef uint8_t esp_duplicate_info_t[ESP_BD_ADDR_LEN]; + +#endif //#if (BLE_42_FEATURE_SUPPORT == TRUE) + +#if (BLE_50_FEATURE_SUPPORT == TRUE) +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_NONCONN_NONSCANNABLE_UNDIRECTED (0 << 0) // Non-Connectable and Non-Scannable Undirected advertising +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE (1 << 0) // Connectable advertising +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE (1 << 1) // Scannable advertising +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED (1 << 2) // Directed advertising +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED (1 << 3) // High Duty Cycle Directed Connectable advertising (<= 3.75 ms Advertis- ing Interval) +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY (1 << 4) // Use legacy advertising PDUs +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_ANON_ADV (1 << 5) // Omit advertiser's address from all PDUs ("anonymous advertising") +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_INCLUDE_TX_PWR (1 << 6) // Include TxPower in the extended header of the advertising PDU +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_MASK (0x7F) // Reserved for future use + +/* If extended advertising PDU types are being used (bit 4 = 0) then: + The advertisement shall not be both connectable and scannable. + High duty cycle directed connectable advertising (<= 3.75 ms advertising interval) shall not be used (bit 3 = 0) +*/ +// ADV_IND +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_IND (ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE) +// ADV_DIRECT_IND (low duty cycle) +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_LD_DIR (ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_DIRECTED) +// ADV_DIRECT_IND (high duty cycle) +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_HD_DIR (ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_CONNECTABLE |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_HD_DIRECTED) +// ADV_SCAN_IND +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_SCAN (ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY |\ + ESP_BLE_GAP_SET_EXT_ADV_PROP_SCANNABLE) +// ADV_NONCONN_IND +#define ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY_NONCONN (ESP_BLE_GAP_SET_EXT_ADV_PROP_LEGACY) +typedef uint16_t esp_ble_ext_adv_type_mask_t; + +#define ESP_BLE_GAP_PHY_1M 1 +#define ESP_BLE_GAP_PHY_2M 2 +#define ESP_BLE_GAP_PHY_CODED 3 +typedef uint8_t esp_ble_gap_phy_t; + +#define ESP_BLE_GAP_NO_PREFER_TRANSMIT_PHY (1<<0) +#define ESP_BLE_GAP_NO_PREFER_RECEIVE_PHY (1<<1) +typedef uint8_t esp_ble_gap_all_phys_t; + +// Primary phy only support 1M and LE coded phy +#define ESP_BLE_GAP_PRI_PHY_1M ESP_BLE_GAP_PHY_1M +#define ESP_BLE_GAP_PRI_PHY_CODED ESP_BLE_GAP_PHY_CODED +typedef uint8_t esp_ble_gap_pri_phy_t; // primary phy + +#define ESP_BLE_GAP_PHY_1M_PREF_MASK (1 << 0) +#define ESP_BLE_GAP_PHY_2M_PREF_MASK (1 << 1) +#define ESP_BLE_GAP_PHY_CODED_PREF_MASK (1 << 2) +typedef uint8_t esp_ble_gap_phy_mask_t; + +#define ESP_BLE_GAP_PHY_OPTIONS_NO_PREF 0 // The Host has no preferred coding when transmitting on the LE Coded PHY +#define ESP_BLE_GAP_PHY_OPTIONS_PREF_S2_CODING 1 // The Host prefers that S=2 coding be used when transmitting on the LE Coded PHY +#define ESP_BLE_GAP_PHY_OPTIONS_PREF_S8_CODING 2 // The Host prefers that S=8 coding be used when transmitting on the LE Coded PHY +typedef uint16_t esp_ble_gap_prefer_phy_options_t; + +#define ESP_BLE_GAP_EXT_SCAN_CFG_UNCODE_MASK 0x01 +#define ESP_BLE_GAP_EXT_SCAN_CFG_CODE_MASK 0x02 +typedef uint8_t esp_ble_ext_scan_cfg_mask_t; + +#define ESP_BLE_GAP_EXT_ADV_DATA_COMPLETE 0x00 +#define ESP_BLE_GAP_EXT_ADV_DATA_INCOMPLETE 0x01 +#define ESP_BLE_GAP_EXT_ADV_DATA_TRUNCATED 0x02 +typedef uint8_t esp_ble_gap_ext_adv_data_status_t; + +#define ESP_BLE_GAP_SYNC_POLICY_BY_ADV_INFO 0 +#define ESP_BLE_GAP_SYNC_POLICY_BY_PERIODIC_LIST 1 +typedef uint8_t esp_ble_gap_sync_t; + +/* Advertising report */ +#define ESP_BLE_ADV_REPORT_EXT_ADV_IND (1<<0) +#define ESP_BLE_ADV_REPORT_EXT_SCAN_IND (1<<1) +#define ESP_BLE_ADV_REPORT_EXT_DIRECT_ADV (1<<2) +#define ESP_BLE_ADV_REPORT_EXT_SCAN_RSP (1<<3) +/* Bluetooth 5.0, Vol 2, Part E, 7.7.65.13 */ +#define ESP_BLE_LEGACY_ADV_TYPE_IND (0x13) +#define ESP_BLE_LEGACY_ADV_TYPE_DIRECT_IND (0x15) +#define ESP_BLE_LEGACY_ADV_TYPE_SCAN_IND (0x12) +#define ESP_BLE_LEGACY_ADV_TYPE_NONCON_IND (0x10) +#define ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_IND (0x1b) +#define ESP_BLE_LEGACY_ADV_TYPE_SCAN_RSP_TO_ADV_SCAN_IND (0x1a) +typedef uint8_t esp_ble_gap_adv_type_t; + +/** +* @brief ext adv parameters +*/ +typedef struct { + esp_ble_ext_adv_type_mask_t type; /*!< ext adv type */ + uint32_t interval_min; /*!< ext adv minimum interval */ + uint32_t interval_max; /*!< ext adv maximum interval */ + esp_ble_adv_channel_t channel_map; /*!< ext adv channel map */ + esp_ble_addr_type_t own_addr_type; /*!< ext adv own addresss type */ + esp_ble_addr_type_t peer_addr_type; /*!< ext adv peer address type */ + esp_bd_addr_t peer_addr; /*!< ext adv peer address */ + esp_ble_adv_filter_t filter_policy; /*!< ext adv filter policy */ + int8_t tx_power; /*!< ext adv tx power */ + esp_ble_gap_pri_phy_t primary_phy; /*!< ext adv primary phy */ + uint8_t max_skip; /*!< ext adv maximum skip */ + esp_ble_gap_phy_t secondary_phy; /*!< ext adv secondary phy */ + uint8_t sid; /*!< ext adv sid */ + bool scan_req_notif; /*!< ext adv sacn request event notify */ +} esp_ble_gap_ext_adv_params_t; + +/** +* @brief ext scan config +*/ +typedef struct { + esp_ble_scan_type_t scan_type; /*!< ext scan type */ + uint16_t scan_interval; /*!< ext scan interval */ + uint16_t scan_window; /*!< ext scan window */ +} esp_ble_ext_scan_cfg_t; + +/** +* @brief ext scan parameters +*/ +typedef struct { + esp_ble_addr_type_t own_addr_type; /*!< ext scan own addresss type */ + esp_ble_scan_filter_t filter_policy; /*!< ext scan filter policy */ + esp_ble_scan_duplicate_t scan_duplicate; /*!< ext scan duplicate scan */ + esp_ble_ext_scan_cfg_mask_t cfg_mask; /*!< ext scan config mask */ + esp_ble_ext_scan_cfg_t uncoded_cfg; /*!< ext scan uncoded config parameters */ + esp_ble_ext_scan_cfg_t coded_cfg; /*!< ext scan coded config parameters */ +} esp_ble_ext_scan_params_t; + +/** +* @brief create extend connection parameters +*/ +typedef struct { + uint16_t scan_interval; /*!< init scan interval */ + uint16_t scan_window; /*!< init scan window */ + uint16_t interval_min; /*!< minimum interval */ + uint16_t interval_max; /*!< maximum interval */ + uint16_t latency; /*!< ext scan type */ + uint16_t supervision_timeout; /*!< connection supervision timeout */ + uint16_t min_ce_len; /*!< minimum ce length */ + uint16_t max_ce_len; /*!< maximum ce length */ +} esp_ble_gap_conn_params_t; + +/** +* @brief extend adv enable parameters +*/ +typedef struct { + uint8_t instance; /*!< advertising handle */ + int duration; /*!< advertising duration */ + int max_events; /*!< maximum number of extended advertising events */ +} esp_ble_gap_ext_adv_t; + +/** +* @brief periodic adv parameters +*/ +typedef struct { + uint16_t interval_min; /*!< periodic advertising minimum interval */ + uint16_t interval_max; /*!< periodic advertising maximum interval */ + uint8_t properties; /*!< periodic advertising properties */ +} esp_ble_gap_periodic_adv_params_t; + +/** +* @brief periodic adv sync parameters +*/ +typedef struct { + esp_ble_gap_sync_t filter_policy; /*!< periodic advertising sync filter policy */ + uint8_t sid; /*!< periodic advertising sid */ + esp_ble_addr_type_t addr_type; /*!< periodic advertising address type */ + esp_bd_addr_t addr; /*!< periodic advertising address */ + uint16_t skip; /*!< the maximum number of periodic advertising events that can be skipped */ + uint16_t sync_timeout; /*!< synchronization timeout */ +} esp_ble_gap_periodic_adv_sync_params_t; + +/** +* @brief extend adv report parameters +*/ +typedef struct { + // uint8_t props; + // uint8_t legacy_event_type; + esp_ble_gap_adv_type_t event_type; /*!< extend advertising type */ + uint8_t addr_type; /*!< extend advertising address type */ + esp_bd_addr_t addr; /*!< extend advertising address */ + esp_ble_gap_pri_phy_t primary_phy; /*!< extend advertising primary phy */ + esp_ble_gap_phy_t secondly_phy; /*!< extend advertising secondary phy */ + uint8_t sid; /*!< extend advertising sid */ + uint8_t tx_power; /*!< extend advertising tx power */ + int8_t rssi; /*!< extend advertising rssi */ + uint16_t per_adv_interval; /*!< periodic advertising interval */ + uint8_t dir_addr_type; /*!< direct address type */ + esp_bd_addr_t dir_addr; /*!< direct address */ + esp_ble_gap_ext_adv_data_status_t data_status; /*!< data type */ + uint8_t adv_data_len; /*!< extend advertising data length */ + uint8_t adv_data[251]; /*!< extend advertising data */ +} esp_ble_gap_ext_adv_reprot_t; + +/** +* @brief periodic adv report parameters +*/ +typedef struct { + uint16_t sync_handle; /*!< periodic advertising train handle */ + uint8_t tx_power; /*!< periodic advertising tx power*/ + int8_t rssi; /*!< periodic advertising rssi */ + esp_ble_gap_ext_adv_data_status_t data_status; /*!< periodic advertising data type*/ + uint8_t data_length; /*!< periodic advertising data length */ + uint8_t data[251]; /*!< periodic advertising data */ +} esp_ble_gap_periodic_adv_report_t; + +/** +* @brief perodic adv sync establish parameters +*/ +typedef struct { + uint8_t status; /*!< periodic advertising sync status */ + uint16_t sync_handle; /*!< periodic advertising train handle */ + uint8_t sid; /*!< periodic advertising sid */ + esp_ble_addr_type_t addr_type; /*!< periodic advertising address type */ + esp_bd_addr_t adv_addr; /*!< periodic advertising address */ + esp_ble_gap_phy_t adv_phy; /*!< periodic advertising adv phy type */ + uint16_t period_adv_interval; /*!< periodic advertising interval */ + uint8_t adv_clk_accuracy; /*!< periodic advertising clock accuracy */ +} esp_ble_gap_periodic_adv_sync_estab_t; + +#endif //#if (BLE_50_FEATURE_SUPPORT == TRUE) + +/** + * @brief Gap callback parameters union + */ +typedef union { +#if (BLE_42_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT + */ + struct ble_adv_data_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set advertising data operation success status */ + } adv_data_cmpl; /*!< Event parameter of ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT + */ + struct ble_scan_rsp_data_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set scan response data operation success status */ + } scan_rsp_data_cmpl; /*!< Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT + */ + struct ble_scan_param_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set scan param operation success status */ + } scan_param_cmpl; /*!< Event parameter of ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_RESULT_EVT + */ + struct ble_scan_result_evt_param { + esp_gap_search_evt_t search_evt; /*!< Search event type */ + esp_bd_addr_t bda; /*!< Bluetooth device address which has been searched */ + esp_bt_dev_type_t dev_type; /*!< Device type */ + esp_ble_addr_type_t ble_addr_type; /*!< Ble device address type */ + esp_ble_evt_type_t ble_evt_type; /*!< Ble scan result event type */ + int rssi; /*!< Searched device's RSSI */ + uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX + ESP_BLE_SCAN_RSP_DATA_LEN_MAX]; /*!< Received EIR */ + int flag; /*!< Advertising data flag bit */ + int num_resps; /*!< Scan result number */ + uint8_t adv_data_len; /*!< Adv data length */ + uint8_t scan_rsp_len; /*!< Scan response length */ + uint32_t num_dis; /*!< The number of discard packets */ + } scan_rst; /*!< Event parameter of ESP_GAP_BLE_SCAN_RESULT_EVT */ + /** + * @brief ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT + */ + struct ble_adv_data_raw_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set raw advertising data operation success status */ + } adv_data_raw_cmpl; /*!< Event parameter of ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT + */ + struct ble_scan_rsp_data_raw_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set raw advertising data operation success status */ + } scan_rsp_data_raw_cmpl; /*!< Event parameter of ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_ADV_START_COMPLETE_EVT + */ + struct ble_adv_start_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate advertising start operation success status */ + } adv_start_cmpl; /*!< Event parameter of ESP_GAP_BLE_ADV_START_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_START_COMPLETE_EVT + */ + struct ble_scan_start_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate scan start operation success status */ + } scan_start_cmpl; /*!< Event parameter of ESP_GAP_BLE_SCAN_START_COMPLETE_EVT */ +#endif //#if (BLE_42_FEATURE_SUPPORT == TRUE) + esp_ble_sec_t ble_security; /*!< ble gap security union type */ +#if (BLE_42_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT + */ + struct ble_scan_stop_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate scan stop operation success status */ + } scan_stop_cmpl; /*!< Event parameter of ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT + */ + struct ble_adv_stop_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate adv stop operation success status */ + } adv_stop_cmpl; /*!< Event parameter of ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT */ +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT + */ + struct ble_set_rand_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate set static rand address operation success status */ + } set_rand_addr_cmpl; /*!< Event parameter of ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT */ + /** + * @brief ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT + */ + struct ble_update_conn_params_evt_param { + esp_bt_status_t status; /*!< Indicate update connection parameters success status */ + esp_bd_addr_t bda; /*!< Bluetooth device address */ + uint16_t min_int; /*!< Min connection interval */ + uint16_t max_int; /*!< Max connection interval */ + uint16_t latency; /*!< Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 */ + uint16_t conn_int; /*!< Current connection interval */ + uint16_t timeout; /*!< Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. + Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec */ + }update_conn_params; /*!< Event parameter of ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT */ + /** + * @brief ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT + */ + struct ble_pkt_data_length_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set pkt data length operation success status */ + esp_ble_pkt_data_length_params_t params; /*!< pkt data length value */ + } pkt_data_lenth_cmpl; /*!< Event parameter of ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT + */ + struct ble_local_privacy_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the set local privacy operation success status */ + } local_privacy_cmpl; /*!< Event parameter of ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT + */ + struct ble_remove_bond_dev_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the remove bond device operation success status */ + esp_bd_addr_t bd_addr; /*!< The device address which has been remove from the bond list */ + }remove_bond_dev_cmpl; /*!< Event parameter of ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT + */ + struct ble_clear_bond_dev_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the clear bond device operation success status */ + }clear_bond_dev_cmpl; /*!< Event parameter of ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT + */ + struct ble_get_bond_dev_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the get bond device operation success status */ + uint8_t dev_num; /*!< Indicate the get number device in the bond list */ + esp_ble_bond_dev_t *bond_dev; /*!< the pointer to the bond device Structure */ + }get_bond_dev_cmpl; /*!< Event parameter of ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT + */ + struct ble_read_rssi_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the read adv tx power operation success status */ + int8_t rssi; /*!< The ble remote device rssi value, the range is from -127 to 20, the unit is dbm, + if the RSSI cannot be read, the RSSI metric shall be set to 127. */ + esp_bd_addr_t remote_addr; /*!< The remote device address */ + } read_rssi_cmpl; /*!< Event parameter of ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT + */ + struct ble_update_whitelist_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate the add or remove whitelist operation success status */ + esp_ble_wl_opration_t wl_opration; /*!< The value is ESP_BLE_WHITELIST_ADD if add address to whitelist operation success, ESP_BLE_WHITELIST_REMOVE if remove address from the whitelist operation success */ + } update_whitelist_cmpl; /*!< Event parameter of ESP_GAP_BLE_UPDATE_WHITELIST_COMPLETE_EVT */ +#if (BLE_42_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT + */ + struct ble_update_duplicate_exceptional_list_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate update duplicate scan exceptional list operation success status */ + uint8_t subcode; /*!< Define in esp_bt_duplicate_exceptional_subcode_type_t */ + uint16_t length; /*!< The length of device_info */ + esp_duplicate_info_t device_info; /*!< device information, when subcode is ESP_BLE_DUPLICATE_EXCEPTIONAL_LIST_CLEAN, the value is invalid */ + } update_duplicate_exceptional_list_cmpl; /*!< Event parameter of ESP_GAP_BLE_UPDATE_DUPLICATE_EXCEPTIONAL_LIST_COMPLETE_EVT */ +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_SET_CHANNELS_EVT + */ + struct ble_set_channels_evt_param { + esp_bt_status_t stat; /*!< BLE set channel status */ + } ble_set_channels; /*!< Event parameter of ESP_GAP_BLE_SET_CHANNELS_EVT */ + +#if (BLE_50_FEATURE_SUPPORT == TRUE) + /** + * @brief ESP_GAP_BLE_READ_PHY_COMPLETE_EVT + */ + struct ble_read_phy_cmpl_evt_param { + esp_bt_status_t status; /*!< read phy complete status */ + esp_bd_addr_t bda; /*!< read phy address */ + esp_ble_gap_phy_t tx_phy; /*!< tx phy type */ + esp_ble_gap_phy_t rx_phy; /*!< rx phy type */ + } read_phy; /*!< Event parameter of ESP_GAP_BLE_READ_PHY_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SET_PREFERED_DEFAULT_PHY_COMPLETE_EVT + */ + struct ble_set_perf_def_phy_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate perf default phy set status */ + } set_perf_def_phy; /*!< Event parameter of ESP_GAP_BLE_SET_PREFERED_DEFAULT_PHY_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SET_PREFERED_PHY_COMPLETE_EVT + */ + struct ble_set_perf_phy_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate perf phy set status */ + } set_perf_phy; /*!< Event parameter of ESP_GAP_BLE_SET_PREFERED_PHY_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT + */ + struct ble_ext_adv_set_rand_addr_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate extend advertising random address set status */ + } ext_adv_set_rand_addr; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_SET_RAND_ADDR_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT + */ + struct ble_ext_adv_set_params_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate extend advertising parameters set status */ + } ext_adv_set_params; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_SET_PARAMS_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT + */ + struct ble_ext_adv_data_set_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate extend advertising data set status */ + } ext_adv_data_set; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_DATA_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT + */ + struct ble_ext_adv_scan_rsp_set_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate extend advertising sacn response data set status */ + } scan_rsp_set; /*!< Event parameter of ESP_GAP_BLE_EXT_SCAN_RSP_DATA_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT + */ + struct ble_ext_adv_start_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate advertising start operation success status */ + } ext_adv_start; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_START_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT + */ + struct ble_ext_adv_stop_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate advertising stop operation success status */ + } ext_adv_stop; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_STOP_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT + */ + struct ble_ext_adv_set_remove_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate advertising stop operation success status */ + } ext_adv_remove; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_SET_REMOVE_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT + */ + struct ble_ext_adv_set_clear_cmpl_evt_param { + esp_bt_status_t status; /*!< Indicate advertising stop operation success status */ + } ext_adv_clear; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_SET_CLEAR_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT + */ + struct ble_periodic_adv_set_params_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertisingparameters set status */ + } peroid_adv_set_params; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SET_PARAMS_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT + */ + struct ble_periodic_adv_data_set_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising data set status */ + } period_adv_data_set; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_DATA_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT + */ + struct ble_periodic_adv_start_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising start status */ + } period_adv_start; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_START_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT + */ + struct ble_periodic_adv_stop_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising stop status */ + } period_adv_stop; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_STOP_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT + */ + struct ble_period_adv_create_sync_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising create sync status */ + } period_adv_create_sync; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CREATE_SYNC_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT + */ + struct ble_period_adv_sync_cancel_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising sync cancle status */ + } period_adv_sync_cancel; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_CANCEL_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT + */ + struct ble_period_adv_sync_terminate_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising sync terminate status */ + } period_adv_sync_term; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_TERMINATE_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT + */ + struct ble_period_adv_add_dev_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising device list add status */ + } period_adv_add_dev; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_ADD_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT + */ + struct ble_period_adv_remove_dev_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising device list remove status */ + } period_adv_remove_dev; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REMOVE_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT + */ + struct ble_period_adv_clear_dev_cmpl_param { + esp_bt_status_t status; /*!< Indicate periodic advertising device list clean status */ + } period_adv_clear_dev; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_CLEAR_DEV_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT + */ + struct ble_set_ext_scan_params_cmpl_param { + esp_bt_status_t status; /*!< Indicate extend advertising parameters set status */ + } set_ext_scan_params; /*!< Event parameter of ESP_GAP_BLE_SET_EXT_SCAN_PARAMS_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT + */ + struct ble_ext_scan_start_cmpl_param { + esp_bt_status_t status; /*!< Indicate extend advertising start status */ + } ext_scan_start; /*!< Event parameter of ESP_GAP_BLE_EXT_SCAN_START_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT + */ + struct ble_ext_scan_stop_cmpl_param { + esp_bt_status_t status; /*!< Indicate extend advertising stop status */ + } ext_scan_stop; /*!< Event parameter of ESP_GAP_BLE_EXT_SCAN_STOP_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT + */ + struct ble_ext_conn_params_set_cmpl_param { + esp_bt_status_t status; /*!< Indicate extend connection parameters set status */ + } ext_conn_params_set; /*!< Event parameter of ESP_GAP_BLE_PREFER_EXT_CONN_PARAMS_SET_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_ADV_TERMINATED_EVT + */ + struct ble_adv_terminate_param { + uint8_t status; /*!< Indicate adv terminate status */ + /* status 0x3c indicates that advertising for a fixed duration completed or, + for directed advertising, that advertising completed without a connection + being created; + status 0x00 indicates that advertising successfully ended with a connection being created. + */ + uint8_t adv_instance; /*!< extend advertising handle */ + uint16_t conn_idx; /*!< connection index */ + uint8_t completed_event; /*!< the number of completed extend advertising events */ + } adv_terminate; /*!< Event parameter of ESP_GAP_BLE_ADV_TERMINATED_EVT */ + /** + * @brief ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT + */ + struct ble_scan_req_received_param { + uint8_t adv_instance; /*!< extend advertising handle */ + esp_ble_addr_type_t scan_addr_type; /*!< scanner address type */ + esp_bd_addr_t scan_addr; /*!< scanner address */ + } scan_req_received; /*!< Event parameter of ESP_GAP_BLE_SCAN_REQ_RECEIVED_EVT */ + /** + * @brief ESP_GAP_BLE_CHANNEL_SELETE_ALGORITHM_EVT + */ + struct ble_channel_sel_alg_param { + uint16_t conn_handle; /*!< connection handle */ + uint8_t channel_sel_alg; /*!< channel selection algorithm */ + } channel_sel_alg; /*!< Event parameter of ESP_GAP_BLE_CHANNEL_SELETE_ALGORITHM_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT + */ + struct ble_periodic_adv_sync_lost_param { + uint16_t sync_handle; /*!< sync handle */ + } periodic_adv_sync_lost; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_LOST_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT + */ + struct ble_periodic_adv_sync_estab_param { + uint8_t status; /*!< periodic advertising sync status */ + uint16_t sync_handle; /*!< periodic advertising sync handle */ + uint8_t sid; /*!< periodic advertising sid */ + esp_ble_addr_type_t adv_addr_type; /*!< periodic advertising address type */ + esp_bd_addr_t adv_addr; /*!< periodic advertising address */ + esp_ble_gap_phy_t adv_phy; /*!< periodic advertising phy type */ + uint16_t period_adv_interval; /*!< periodic advertising interval */ + uint8_t adv_clk_accuracy; /*!< periodic advertising clock accuracy */ + } periodic_adv_sync_estab; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_SYNC_ESTAB_EVT */ + /** + * @brief ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT + */ + struct ble_phy_update_cmpl_param { + esp_bt_status_t status; /*!< phy update status */ + esp_bd_addr_t bda; /*!< address */ + esp_ble_gap_phy_t tx_phy; /*!< tx phy type */ + esp_ble_gap_phy_t rx_phy; /*!< rx phy type */ + } phy_update; /*!< Event parameter of ESP_GAP_BLE_PHY_UPDATE_COMPLETE_EVT */ + /** + * @brief ESP_GAP_BLE_EXT_ADV_REPORT_EVT + */ + struct ble_ext_adv_report_param { + esp_ble_gap_ext_adv_reprot_t params; /*!< extend advertising report parameters */ + } ext_adv_report; /*!< Event parameter of ESP_GAP_BLE_EXT_ADV_REPORT_EVT */ + /** + * @brief ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT + */ + struct ble_periodic_adv_report_param { + esp_ble_gap_periodic_adv_report_t params; /*!< periodic advertising report parameters */ + } period_adv_report; /*!< Event parameter of ESP_GAP_BLE_PERIODIC_ADV_REPORT_EVT */ +#endif // #if (BLE_50_FEATURE_SUPPORT == TRUE) +} esp_ble_gap_cb_param_t; + +/** + * @brief GAP callback function type + * @param event : Event type + * @param param : Point to callback parameter, currently is union type + */ +typedef void (* esp_gap_ble_cb_t)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param); + +/** + * @brief This function is called to occur gap event, such as scan result + * + * @param[in] callback: callback function + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_register_callback(esp_gap_ble_cb_t callback); + +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief This function is called to override the BTA default ADV parameters. + * + * @param[in] adv_data: Pointer to User defined ADV data structure. This + * memory space can not be freed until callback of config_adv_data + * is received. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_config_adv_data (esp_ble_adv_data_t *adv_data); + + + +/** + * @brief This function is called to set scan parameters + * + * @param[in] scan_params: Pointer to User defined scan_params data structure. This + * memory space can not be freed until callback of set_scan_params + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_set_scan_params(esp_ble_scan_params_t *scan_params); + + +/** + * @brief This procedure keep the device scanning the peer device which advertising on the air + * + * @param[in] duration: Keeping the scanning time, the unit is second. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_start_scanning(uint32_t duration); + + +/** + * @brief This function call to stop the device scanning the peer device which advertising on the air + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_stop_scanning(void); + +/** + * @brief This function is called to start advertising. + * + * @param[in] adv_params: pointer to User defined adv_params data structure. + + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_start_advertising (esp_ble_adv_params_t *adv_params); + + + +/** + * @brief This function is called to stop advertising. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_stop_advertising(void); +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + + +/** + * @brief Update connection parameters, can only be used when connection is up. + * + * @param[in] params - connection update parameters + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_update_conn_params(esp_ble_conn_update_params_t *params); + + +/** + * @brief This function is to set maximum LE data packet size + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_set_pkt_data_len(esp_bd_addr_t remote_device, uint16_t tx_data_length); + +/** + * @brief This function sets the static Random Address and Non-Resolvable Private Address for the application + * + * @param[in] rand_addr: the random address which should be setting + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_set_rand_addr(esp_bd_addr_t rand_addr); + +/** + * @brief This function clears the random address for the application + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_clear_rand_addr(void); + + + +/** + * @brief Enable/disable privacy on the local device + * + * @param[in] privacy_enable - enable/disable privacy on remote device. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_config_local_privacy (bool privacy_enable); + +/** + * @brief set local gap appearance icon + * + * + * @param[in] icon - External appearance value, these values are defined by the Bluetooth SIG, please refer to + * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_config_local_icon (uint16_t icon); + +/** +* @brief Add or remove device from white list +* +* @param[in] add_remove: the value is true if added the ble device to the white list, and false remove to the white list. +* @param[in] remote_bda: the remote device address add/remove from the white list. +* @param[in] wl_addr_type: whitelist address type +* @return +* - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_update_whitelist(bool add_remove, esp_bd_addr_t remote_bda, esp_ble_wl_addr_type_t wl_addr_type); + +/** +* @brief Clear all white list +* +* @return +* - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_clear_whitelist(void); + +/** +* @brief Get the whitelist size in the controller +* +* @param[out] length: the white list length. +* @return +* - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_get_whitelist_size(uint16_t *length); +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/** +* @brief This function is called to set the preferred connection +* parameters when default connection parameter is not desired before connecting. +* This API can only be used in the master role. +* +* @param[in] bd_addr: BD address of the peripheral +* @param[in] min_conn_int: minimum preferred connection interval +* @param[in] max_conn_int: maximum preferred connection interval +* @param[in] slave_latency: preferred slave latency +* @param[in] supervision_tout: preferred supervision timeout +* +* @return +* - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_set_prefer_conn_params(esp_bd_addr_t bd_addr, + uint16_t min_conn_int, uint16_t max_conn_int, + uint16_t slave_latency, uint16_t supervision_tout); +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief Set device name to the local device + * + * @param[in] name - device name. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_set_device_name(const char *name); + +/** + * @brief This function is called to get local used address and adress type. + * uint8_t *esp_bt_dev_get_address(void) get the public address + * + * @param[in] local_used_addr - current local used ble address (six bytes) + * @param[in] addr_type - ble address type + * + * @return - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_get_local_used_addr(esp_bd_addr_t local_used_addr, uint8_t * addr_type); +/** + * @brief This function is called to get ADV data for a specific type. + * + * @param[in] adv_data - pointer of ADV data which to be resolved + * @param[in] type - finding ADV data type + * @param[out] length - return the length of ADV data not including type + * + * @return pointer of ADV data + * + */ +uint8_t *esp_ble_resolve_adv_data(uint8_t *adv_data, uint8_t type, uint8_t *length); +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief This function is called to set raw advertising data. User need to fill + * ADV data by self. + * + * @param[in] raw_data : raw advertising data + * @param[in] raw_data_len : raw advertising data length , less than 31 bytes + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gap_config_adv_data_raw(uint8_t *raw_data, uint32_t raw_data_len); + +/** + * @brief This function is called to set raw scan response data. User need to fill + * scan response data by self. + * + * @param[in] raw_data : raw scan response data + * @param[in] raw_data_len : raw scan response data length , less than 31 bytes + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_gap_config_scan_rsp_data_raw(uint8_t *raw_data, uint32_t raw_data_len); +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + +/** + * @brief This function is called to read the RSSI of remote device. + * The address of link policy results are returned in the gap callback function with + * ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT event. + * + * @param[in] remote_addr : The remote connection device address. + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_gap_read_rssi(esp_bd_addr_t remote_addr); +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief This function is called to add a device info into the duplicate scan exceptional list. + * + * + * @param[in] type: device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t + * when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. + * @param[in] device_info: the device information. + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_gap_add_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info); + +/** + * @brief This function is called to remove a device info from the duplicate scan exceptional list. + * + * + * @param[in] type: device info type, it is defined in esp_ble_duplicate_exceptional_info_type_t + * when type is MESH_BEACON_TYPE, MESH_PROV_SRV_ADV or MESH_PROXY_SRV_ADV , device_info is invalid. + * @param[in] device_info: the device information. + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_gap_remove_duplicate_scan_exceptional_device(esp_ble_duplicate_exceptional_info_type_t type, esp_duplicate_info_t device_info); + +/** + * @brief This function is called to clean the duplicate scan exceptional list. + * This API will delete all device information in the duplicate scan exceptional list. + * + * + * @param[in] list_type: duplicate scan exceptional list type, the value can be one or more of esp_duplicate_scan_exceptional_list_type_t. + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_ble_gap_clean_duplicate_scan_exceptional_list(esp_duplicate_scan_exceptional_list_type_t list_type); +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + +#if (SMP_INCLUDED == TRUE) +/** +* @brief Set a GAP security parameter value. Overrides the default value. +* +* Secure connection is highly recommended to avoid some major +* vulnerabilities like 'Impersonation in the Pin Pairing Protocol' +* (CVE-2020-26555) and 'Authentication of the LE Legacy Pairing +* Protocol'. +* +* To accept only `secure connection mode`, it is necessary do as following: +* +* 1. Set bit `ESP_LE_AUTH_REQ_SC_ONLY` (`param_type` is +* `ESP_BLE_SM_AUTHEN_REQ_MODE`), bit `ESP_LE_AUTH_BOND` and bit +* `ESP_LE_AUTH_REQ_MITM` is optional as required. +* +* 2. Set to `ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_ENABLE` (`param_type` is +* `ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH`). +* +* @param[in] param_type : the type of the param which to be set +* @param[in] value : the param value +* @param[in] len : the length of the param value +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_set_security_param(esp_ble_sm_param_t param_type, + void *value, uint8_t len); + +/** +* @brief Grant security request access. +* +* @param[in] bd_addr : BD address of the peer +* @param[in] accept : accept the security request or not +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_security_rsp(esp_bd_addr_t bd_addr, bool accept); + + +/** +* @brief Set a gap parameter value. Use this function to change +* the default GAP parameter values. +* +* @param[in] bd_addr : the address of the peer device need to encryption +* @param[in] sec_act : This is the security action to indicate +* what kind of BLE security level is required for +* the BLE link if the BLE is supported +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_set_encryption(esp_bd_addr_t bd_addr, esp_ble_sec_act_t sec_act); + +/** +* @brief Reply the key value to the peer device in the legacy connection stage. +* +* @param[in] bd_addr : BD address of the peer +* @param[in] accept : passkey entry successful or declined. +* @param[in] passkey : passkey value, must be a 6 digit number, +* can be lead by 0. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey); + + +/** +* @brief Reply the confirm value to the peer device in the secure connection stage. +* +* @param[in] bd_addr : BD address of the peer device +* @param[in] accept : numbers to compare are the same or different. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_confirm_reply(esp_bd_addr_t bd_addr, bool accept); + +/** +* @brief Removes a device from the security database list of +* peer device. It manages unpairing event while connected. +* +* @param[in] bd_addr : BD address of the peer device +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_remove_bond_device(esp_bd_addr_t bd_addr); + +/** +* @brief Get the device number from the security database list of peer device. +* It will return the device bonded number immediately. +* +* @return - >= 0 : bonded devices number. +* - ESP_FAIL : failed +* +*/ +int esp_ble_get_bond_device_num(void); + + +/** +* @brief Get the device from the security database list of peer device. +* It will return the device bonded information immediately. +* @param[inout] dev_num: Indicate the dev_list array(buffer) size as input. +* If dev_num is large enough, it means the actual number as output. +* Suggest that dev_num value equal to esp_ble_get_bond_device_num(). +* +* @param[out] dev_list: an array(buffer) of `esp_ble_bond_dev_t` type. Use for storing the bonded devices address. +* The dev_list should be allocated by who call this API. +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_get_bond_device_list(int *dev_num, esp_ble_bond_dev_t *dev_list); + +/** +* @brief This function is called to provide the OOB data for +* SMP in response to ESP_GAP_BLE_OOB_REQ_EVT +* +* @param[in] bd_addr: BD address of the peer device. +* @param[in] TK: TK value, the TK value shall be a 128-bit random number +* @param[in] len: length of tk, should always be 128-bit +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_oob_req_reply(esp_bd_addr_t bd_addr, uint8_t *TK, uint8_t len); + +#endif /* #if (SMP_INCLUDED == TRUE) */ + +/** +* @brief This function is to disconnect the physical connection of the peer device +* gattc may have multiple virtual GATT server connections when multiple app_id registered. +* esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t conn_id) only close one virtual GATT server connection. +* if there exist other virtual GATT server connections, it does not disconnect the physical connection. +* esp_ble_gap_disconnect(esp_bd_addr_t remote_device) disconnect the physical connection directly. +* +* +* +* @param[in] remote_device : BD address of the peer device +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_disconnect(esp_bd_addr_t remote_device); + +/** +* @brief This function is called to read the connection +* parameters information of the device +* +* @param[in] bd_addr: BD address of the peer device. +* @param[out] conn_params: the connection parameters information +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_get_current_conn_params(esp_bd_addr_t bd_addr, esp_gap_conn_params_t *conn_params); + +/** +* @brief BLE set channels +* +* @param[in] channels : The n th such field (in the range 0 to 36) contains the value for the link layer channel index n. +* 0 means channel n is bad. +* 1 means channel n is unknown. +* The most significant bits are reserved and shall be set to 0. +* At least one channel shall be marked as unknown. +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_gap_ble_set_channels(esp_gap_ble_channels channels); + +/** +* @brief This function is called to authorized a link after Authentication(MITM protection) +* +* @param[in] bd_addr: BD address of the peer device. +* @param[out] authorize: Authorized the link or not. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_gap_ble_set_authorization(esp_bd_addr_t bd_addr, bool authorize); + +#if (BLE_50_FEATURE_SUPPORT == TRUE) + +/** +* @brief This function is used to read the current transmitter PHY +* and receiver PHY on the connection identified by remote address. +* +* @param[in] bd_addr : BD address of the peer device +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_read_phy(esp_bd_addr_t bd_addr); + +/** +* @brief This function is used to allows the Host to specify its preferred values +* for the transmitter PHY and receiver PHY to be used for all subsequent connections +* over the LE transport. +* +* @param[in] tx_phy_mask : indicates the transmitter PHYs that the Host prefers the Controller to use +* @param[in] rx_phy_mask : indicates the receiver PHYs that the Host prefers the Controller to use +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_set_prefered_default_phy(esp_ble_gap_phy_mask_t tx_phy_mask, esp_ble_gap_phy_mask_t rx_phy_mask); +/** +* @brief This function is used to set the PHY preferences for the connection identified by the remote address. +* The Controller might not be able to make the change (e.g. because the peer does not support the requested PHY) +* or may decide that the current PHY is preferable. +* +* @param[in] bd_addr : remote address +* @param[in] all_phys_mask : a bit field that allows the Host to specify +* @param[in] tx_phy_mask : a bit field that indicates the transmitter PHYs that the Host prefers the Controller to use +* @param[in] rx_phy_mask : a bit field that indicates the receiver PHYs that the Host prefers the Controller to use +* @param[in] phy_options : a bit field that allows the Host to specify options for PHYs +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_set_prefered_phy(esp_bd_addr_t bd_addr, + esp_ble_gap_all_phys_t all_phys_mask, + esp_ble_gap_phy_mask_t tx_phy_mask, + esp_ble_gap_phy_mask_t rx_phy_mask, + esp_ble_gap_prefer_phy_options_t phy_options); + +/** +* @brief This function is used by the Host to set the random device address specified by the Random_Address parameter. +* +* @param[in] instance : Used to identify an advertising set +* @param[in] rand_addr : Random Device Address +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_set_rand_addr(uint8_t instance, esp_bd_addr_t rand_addr); + +/** +* @brief This function is used by the Host to set the advertising parameters. +* +* @param[in] instance : identifies the advertising set whose parameters are being configured. +* @param[in] params : advertising parameters +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_set_params(uint8_t instance, const esp_ble_gap_ext_adv_params_t *params); + +/** +* @brief This function is used to set the data used in advertising PDUs that have a data field +* +* @param[in] instance : identifies the advertising set whose data are being configured +* @param[in] length : data length +* @param[in] data : data information +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_config_ext_adv_data_raw(uint8_t instance, uint16_t length, const uint8_t *data); + +/** +* @brief This function is used to provide scan response data used in scanning response PDUs +* +* @param[in] instance : identifies the advertising set whose response data are being configured. +* @param[in] length : responsedata length +* @param[in] scan_rsp_data : response data information +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_config_ext_scan_rsp_data_raw(uint8_t instance, uint16_t length, + const uint8_t *scan_rsp_data); +/** +* @brief This function is used to request the Controller to enable one or more +* advertising sets using the advertising sets identified by the instance parameter. +* +* @param[in] num_adv : Number of advertising sets to enable or disable +* @param[in] ext_adv : adv parameters +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_start(uint8_t num_adv, const esp_ble_gap_ext_adv_t *ext_adv); + +/** +* @brief This function is used to request the Controller to disable one or more +* advertising sets using the advertising sets identified by the instance parameter. +* +* @param[in] num_adv : Number of advertising sets to enable or disable +* @param[in] ext_adv_inst : ext adv instance +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_stop(uint8_t num_adv, const uint8_t *ext_adv_inst); + +/** +* @brief This function is used to remove an advertising set from the Controller. +* +* @param[in] instance : Used to identify an advertising set +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_set_remove(uint8_t instance); + +/** +* @brief This function is used to remove all existing advertising sets from the Controller. +* +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_ext_adv_set_clear(void); + +/** +* @brief This function is used by the Host to set the parameters for periodic advertising. +* +* @param[in] instance : identifies the advertising set whose periodic advertising parameters are being configured. +* @param[in] params : periodic adv parameters +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_set_params(uint8_t instance, const esp_ble_gap_periodic_adv_params_t *params); + +/** +* @brief This function is used to set the data used in periodic advertising PDUs. +* +* @param[in] instance : identifies the advertising set whose periodic advertising parameters are being configured. +* @param[in] length : the length of periodic data +* @param[in] data : periodic data information +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_config_periodic_adv_data_raw(uint8_t instance, uint16_t length, + const uint8_t *data); +/** +* @brief This function is used to request the Controller to enable the periodic advertising for the advertising set specified +* +* @param[in] instance : Used to identify an advertising set +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_start(uint8_t instance); + +/** +* @brief This function is used to request the Controller to disable the periodic advertising for the advertising set specified +* +* @param[in] instance : Used to identify an advertising set +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_stop(uint8_t instance); + +/** +* @brief This function is used to set the extended scan parameters to be used on the advertising channels. +* +* @param[in] params : scan parameters +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_set_ext_scan_params(const esp_ble_ext_scan_params_t *params); + +/** +* @brief This function is used to enable scanning. +* +* @param[in] duration : Scan duration +* @param[in] period : Time interval from when the Controller started its last Scan Duration until it begins the subsequent Scan Duration. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_start_ext_scan(uint32_t duration, uint16_t period); + +/** +* @brief This function is used to disable scanning. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_stop_ext_scan(void); + +/** +* @brief This function is used to synchronize with periodic advertising from an advertiser and begin receiving periodic advertising packets. +* +* @param[in] params : sync parameters +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_create_sync(const esp_ble_gap_periodic_adv_sync_params_t *params); + +/** +* @brief This function is used to cancel the LE_Periodic_Advertising_Create_Sync command while it is pending. +* +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_sync_cancel(void); + +/** +* @brief This function is used to stop reception of the periodic advertising identified by the Sync Handle parameter. +* +* @param[in] sync_handle : identify the periodic advertiser +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_sync_terminate(uint16_t sync_handle); + +/** +* @brief This function is used to add a single device to the Periodic Advertiser list stored in the Controller +* +* @param[in] addr_type : address type +* @param[in] addr : Device Address +* @param[in] sid : Advertising SID subfield in the ADI field used to identify the Periodic Advertising +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_add_dev_to_list(esp_ble_addr_type_t addr_type, + esp_bd_addr_t addr, + uint8_t sid); + +/** +* @brief This function is used to remove one device from the list of Periodic Advertisers stored in the Controller. +* Removals from the Periodic Advertisers List take effect immediately. +* +* @param[in] addr_type : address type +* @param[in] addr : Device Address +* @param[in] sid : Advertising SID subfield in the ADI field used to identify the Periodic Advertising +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_remove_dev_from_list(esp_ble_addr_type_t addr_type, + esp_bd_addr_t addr, + uint8_t sid); +/** +* @brief This function is used to remove all devices from the list of Periodic Advertisers in the Controller. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_periodic_adv_clear_dev(void); + +/** +* @brief This function is used to set aux connection parameters +* +* @param[in] addr : device address +* @param[in] phy_mask : indicates the PHY(s) on which the advertising packets should be received on the primary advertising channel and the PHYs for which connection parameters have been specified. +* @param[in] phy_1m_conn_params : Scan connectable advertisements on the LE 1M PHY. Connection parameters for the LE 1M PHY are provided. +* @param[in] phy_2m_conn_params : Connection parameters for the LE 2M PHY are provided. +* @param[in] phy_coded_conn_params : Scan connectable advertisements on the LE Coded PHY. Connection parameters for the LE Coded PHY are provided. +* +* @return - ESP_OK : success +* - other : failed +* +*/ +esp_err_t esp_ble_gap_prefer_ext_connect_params_set(esp_bd_addr_t addr, + esp_ble_gap_phy_mask_t phy_mask, + const esp_ble_gap_conn_params_t *phy_1m_conn_params, + const esp_ble_gap_conn_params_t *phy_2m_conn_params, + const esp_ble_gap_conn_params_t *phy_coded_conn_params); + +#endif //#if (BLE_50_FEATURE_SUPPORT == TRUE) + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GAP_BLE_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h new file mode 100644 index 00000000..73c8605e --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gap_bt_api.h @@ -0,0 +1,777 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_GAP_BT_API_H__ +#define __ESP_GAP_BT_API_H__ + +#include +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// RSSI threshold +#define ESP_BT_GAP_RSSI_HIGH_THRLD -20 /*!< High RSSI threshold */ +#define ESP_BT_GAP_RSSI_LOW_THRLD -45 /*!< Low RSSI threshold */ + +/// Class of device +typedef struct { + uint32_t reserved_2: 2; /*!< undefined */ + uint32_t minor: 6; /*!< minor class */ + uint32_t major: 5; /*!< major class */ + uint32_t service: 11; /*!< service class */ + uint32_t reserved_8: 8; /*!< undefined */ +} esp_bt_cod_t; + +/// class of device settings +typedef enum { + ESP_BT_SET_COD_MAJOR_MINOR = 0x01, /*!< overwrite major, minor class */ + ESP_BT_SET_COD_SERVICE_CLASS = 0x02, /*!< set the bits in the input, the current bit will remain */ + ESP_BT_CLR_COD_SERVICE_CLASS = 0x04, /*!< clear the bits in the input, others will remain */ + ESP_BT_SET_COD_ALL = 0x08, /*!< overwrite major, minor, set the bits in service class */ + ESP_BT_INIT_COD = 0x0a, /*!< overwrite major, minor, and service class */ +} esp_bt_cod_mode_t; + +#define ESP_BT_GAP_AFH_CHANNELS_LEN 10 +typedef uint8_t esp_bt_gap_afh_channels[ESP_BT_GAP_AFH_CHANNELS_LEN]; + + +/// Discoverability and Connectability mode +typedef enum { + ESP_BT_NON_CONNECTABLE, /*!< Non-connectable */ + ESP_BT_CONNECTABLE, /*!< Connectable */ +} esp_bt_connection_mode_t; + +typedef enum { + ESP_BT_NON_DISCOVERABLE, /*!< Non-discoverable */ + ESP_BT_LIMITED_DISCOVERABLE, /*!< Limited Discoverable */ + ESP_BT_GENERAL_DISCOVERABLE, /*!< General Discoverable */ +} esp_bt_discovery_mode_t; + +/// Bluetooth Device Property type +typedef enum { + ESP_BT_GAP_DEV_PROP_BDNAME = 1, /*!< Bluetooth device name, value type is int8_t [] */ + ESP_BT_GAP_DEV_PROP_COD, /*!< Class of Device, value type is uint32_t */ + ESP_BT_GAP_DEV_PROP_RSSI, /*!< Received Signal strength Indication, value type is int8_t, ranging from -128 to 127 */ + ESP_BT_GAP_DEV_PROP_EIR, /*!< Extended Inquiry Response, value type is uint8_t [] */ +} esp_bt_gap_dev_prop_type_t; + +/// Maximum bytes of Bluetooth device name +#define ESP_BT_GAP_MAX_BDNAME_LEN (248) + +/// Maximum size of EIR Significant part +#define ESP_BT_GAP_EIR_DATA_LEN (240) + +/// Bluetooth Device Property Descriptor +typedef struct { + esp_bt_gap_dev_prop_type_t type; /*!< Device property type */ + int len; /*!< Device property value length */ + void *val; /*!< Device property value */ +} esp_bt_gap_dev_prop_t; + +/// Extended Inquiry Response data type +#define ESP_BT_EIR_TYPE_FLAGS 0x01 /*!< Flag with information such as BR/EDR and LE support */ +#define ESP_BT_EIR_TYPE_INCMPL_16BITS_UUID 0x02 /*!< Incomplete list of 16-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_CMPL_16BITS_UUID 0x03 /*!< Complete list of 16-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_INCMPL_32BITS_UUID 0x04 /*!< Incomplete list of 32-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_CMPL_32BITS_UUID 0x05 /*!< Complete list of 32-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_INCMPL_128BITS_UUID 0x06 /*!< Incomplete list of 128-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_CMPL_128BITS_UUID 0x07 /*!< Complete list of 128-bit service UUIDs */ +#define ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME 0x08 /*!< Shortened Local Name */ +#define ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME 0x09 /*!< Complete Local Name */ +#define ESP_BT_EIR_TYPE_TX_POWER_LEVEL 0x0a /*!< Tx power level, value is 1 octet ranging from -127 to 127, unit is dBm*/ +#define ESP_BT_EIR_TYPE_URL 0x24 /*!< Uniform resource identifier */ +#define ESP_BT_EIR_TYPE_MANU_SPECIFIC 0xff /*!< Manufacturer specific data */ +#define ESP_BT_EIR_TYPE_MAX_NUM 12 /*!< MAX number of EIR type */ + +typedef uint8_t esp_bt_eir_type_t; + + + +/* ESP_BT_EIR_FLAG bit definition */ +#define ESP_BT_EIR_FLAG_LIMIT_DISC (0x01 << 0) +#define ESP_BT_EIR_FLAG_GEN_DISC (0x01 << 1) +#define ESP_BT_EIR_FLAG_BREDR_NOT_SPT (0x01 << 2) +#define ESP_BT_EIR_FLAG_DMT_CONTROLLER_SPT (0x01 << 3) +#define ESP_BT_EIR_FLAG_DMT_HOST_SPT (0x01 << 4) + +#define ESP_BT_EIR_MAX_LEN 240 +/// EIR data content, according to "Supplement to the Bluetooth Core Specification" +typedef struct { + bool fec_required; /*!< FEC is required or not, true by default */ + bool include_txpower; /*!< EIR data include TX power, false by default */ + bool include_uuid; /*!< EIR data include UUID, false by default */ + uint8_t flag; /*!< EIR flags, see ESP_BT_EIR_FLAG for details, EIR will not include flag if it is 0, 0 by default */ + uint16_t manufacturer_len; /*!< Manufacturer data length, 0 by default */ + uint8_t *p_manufacturer_data; /*!< Manufacturer data point */ + uint16_t url_len; /*!< URL length, 0 by default */ + uint8_t *p_url; /*!< URL point */ +} esp_bt_eir_data_t; + +/// Major service class field of Class of Device, mutiple bits can be set +typedef enum { + ESP_BT_COD_SRVC_NONE = 0, /*!< None indicates an invalid value */ + ESP_BT_COD_SRVC_LMTD_DISCOVER = 0x1, /*!< Limited Discoverable Mode */ + ESP_BT_COD_SRVC_POSITIONING = 0x8, /*!< Positioning (Location identification) */ + ESP_BT_COD_SRVC_NETWORKING = 0x10, /*!< Networking, e.g. LAN, Ad hoc */ + ESP_BT_COD_SRVC_RENDERING = 0x20, /*!< Rendering, e.g. Printing, Speakers */ + ESP_BT_COD_SRVC_CAPTURING = 0x40, /*!< Capturing, e.g. Scanner, Microphone */ + ESP_BT_COD_SRVC_OBJ_TRANSFER = 0x80, /*!< Object Transfer, e.g. v-Inbox, v-Folder */ + ESP_BT_COD_SRVC_AUDIO = 0x100, /*!< Audio, e.g. Speaker, Microphone, Headset service */ + ESP_BT_COD_SRVC_TELEPHONY = 0x200, /*!< Telephony, e.g. Cordless telephony, Modem, Headset service */ + ESP_BT_COD_SRVC_INFORMATION = 0x400, /*!< Information, e.g., WEB-server, WAP-server */ +} esp_bt_cod_srvc_t; + +typedef enum{ + ESP_BT_PIN_TYPE_VARIABLE = 0, /*!< Refer to BTM_PIN_TYPE_VARIABLE */ + ESP_BT_PIN_TYPE_FIXED = 1, /*!< Refer to BTM_PIN_TYPE_FIXED */ +} esp_bt_pin_type_t; + +#define ESP_BT_PIN_CODE_LEN 16 /*!< Max pin code length */ +typedef uint8_t esp_bt_pin_code_t[ESP_BT_PIN_CODE_LEN]; /*!< Pin Code (upto 128 bits) MSB is 0 */ + +typedef enum { + ESP_BT_SP_IOCAP_MODE = 0, /*!< Set IO mode */ + //ESP_BT_SP_OOB_DATA, //TODO /*!< Set OOB data */ +} esp_bt_sp_param_t; + +/* relate to BTM_IO_CAP_xxx in stack/btm_api.h */ +#define ESP_BT_IO_CAP_OUT 0 /*!< DisplayOnly */ /* relate to BTM_IO_CAP_OUT in stack/btm_api.h */ +#define ESP_BT_IO_CAP_IO 1 /*!< DisplayYesNo */ /* relate to BTM_IO_CAP_IO in stack/btm_api.h */ +#define ESP_BT_IO_CAP_IN 2 /*!< KeyboardOnly */ /* relate to BTM_IO_CAP_IN in stack/btm_api.h */ +#define ESP_BT_IO_CAP_NONE 3 /*!< NoInputNoOutput */ /* relate to BTM_IO_CAP_NONE in stack/btm_api.h */ +typedef uint8_t esp_bt_io_cap_t; /*!< Combination of the IO Capability */ + + +/* BTM Power manager modes */ +#define ESP_BT_PM_MD_ACTIVE 0x00 /*!< Active mode */ +#define ESP_BT_PM_MD_HOLD 0x01 /*!< Hold mode */ +#define ESP_BT_PM_MD_SNIFF 0x02 /*!< Sniff mode */ +#define ESP_BT_PM_MD_PARK 0x03 /*!< Park state */ +typedef uint8_t esp_bt_pm_mode_t; + + + +/// Bits of major service class field +#define ESP_BT_COD_SRVC_BIT_MASK (0xffe000) /*!< Major service bit mask */ +#define ESP_BT_COD_SRVC_BIT_OFFSET (13) /*!< Major service bit offset */ + +/// Major device class field of Class of Device +typedef enum { + ESP_BT_COD_MAJOR_DEV_MISC = 0, /*!< Miscellaneous */ + ESP_BT_COD_MAJOR_DEV_COMPUTER = 1, /*!< Computer */ + ESP_BT_COD_MAJOR_DEV_PHONE = 2, /*!< Phone(cellular, cordless, pay phone, modem */ + ESP_BT_COD_MAJOR_DEV_LAN_NAP = 3, /*!< LAN, Network Access Point */ + ESP_BT_COD_MAJOR_DEV_AV = 4, /*!< Audio/Video(headset, speaker, stereo, video display, VCR */ + ESP_BT_COD_MAJOR_DEV_PERIPHERAL = 5, /*!< Peripheral(mouse, joystick, keyboard) */ + ESP_BT_COD_MAJOR_DEV_IMAGING = 6, /*!< Imaging(printer, scanner, camera, display */ + ESP_BT_COD_MAJOR_DEV_WEARABLE = 7, /*!< Wearable */ + ESP_BT_COD_MAJOR_DEV_TOY = 8, /*!< Toy */ + ESP_BT_COD_MAJOR_DEV_HEALTH = 9, /*!< Health */ + ESP_BT_COD_MAJOR_DEV_UNCATEGORIZED = 31, /*!< Uncategorized: device not specified */ +} esp_bt_cod_major_dev_t; + +/// Bits of major device class field +#define ESP_BT_COD_MAJOR_DEV_BIT_MASK (0x1f00) /*!< Major device bit mask */ +#define ESP_BT_COD_MAJOR_DEV_BIT_OFFSET (8) /*!< Major device bit offset */ + +/// Bits of minor device class field +#define ESP_BT_COD_MINOR_DEV_BIT_MASK (0xfc) /*!< Minor device bit mask */ +#define ESP_BT_COD_MINOR_DEV_BIT_OFFSET (2) /*!< Minor device bit offset */ + +/// Bits of format type +#define ESP_BT_COD_FORMAT_TYPE_BIT_MASK (0x03) /*!< Format type bit mask */ +#define ESP_BT_COD_FORMAT_TYPE_BIT_OFFSET (0) /*!< Format type bit offset */ + +/// Class of device format type 1 +#define ESP_BT_COD_FORMAT_TYPE_1 (0x00) + +/** Bluetooth Device Discovery state */ +typedef enum { + ESP_BT_GAP_DISCOVERY_STOPPED, /*!< Device discovery stopped */ + ESP_BT_GAP_DISCOVERY_STARTED, /*!< Device discovery started */ +} esp_bt_gap_discovery_state_t; + +/// BT GAP callback events +typedef enum { + ESP_BT_GAP_DISC_RES_EVT = 0, /*!< Device discovery result event */ + ESP_BT_GAP_DISC_STATE_CHANGED_EVT, /*!< Discovery state changed event */ + ESP_BT_GAP_RMT_SRVCS_EVT, /*!< Get remote services event */ + ESP_BT_GAP_RMT_SRVC_REC_EVT, /*!< Get remote service record event */ + ESP_BT_GAP_AUTH_CMPL_EVT, /*!< Authentication complete event */ + ESP_BT_GAP_PIN_REQ_EVT, /*!< Legacy Pairing Pin code request */ + ESP_BT_GAP_CFM_REQ_EVT, /*!< Security Simple Pairing User Confirmation request. */ + ESP_BT_GAP_KEY_NOTIF_EVT, /*!< Security Simple Pairing Passkey Notification */ + ESP_BT_GAP_KEY_REQ_EVT, /*!< Security Simple Pairing Passkey request */ + ESP_BT_GAP_READ_RSSI_DELTA_EVT, /*!< Read rssi event */ + ESP_BT_GAP_CONFIG_EIR_DATA_EVT, /*!< Config EIR data event */ + ESP_BT_GAP_SET_AFH_CHANNELS_EVT, /*!< Set AFH channels event */ + ESP_BT_GAP_READ_REMOTE_NAME_EVT, /*!< Read Remote Name event */ + ESP_BT_GAP_MODE_CHG_EVT, + ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT, /*!< remove bond device complete event */ + ESP_BT_GAP_QOS_CMPL_EVT, /*!< QOS complete event */ + ESP_BT_GAP_EVT_MAX, +} esp_bt_gap_cb_event_t; + +/** Inquiry Mode */ +typedef enum { + ESP_BT_INQ_MODE_GENERAL_INQUIRY, /*!< General inquiry mode */ + ESP_BT_INQ_MODE_LIMITED_INQUIRY, /*!< Limited inquiry mode */ +} esp_bt_inq_mode_t; + +/** Minimum and Maximum inquiry length*/ +#define ESP_BT_GAP_MIN_INQ_LEN (0x01) /*!< Minimum inquiry duration, unit is 1.28s */ +#define ESP_BT_GAP_MAX_INQ_LEN (0x30) /*!< Maximum inquiry duration, unit is 1.28s */ + +/// A2DP state callback parameters +typedef union { + /** + * @brief ESP_BT_GAP_DISC_RES_EVT + */ + struct disc_res_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + int num_prop; /*!< number of properties got */ + esp_bt_gap_dev_prop_t *prop; /*!< properties discovered from the new device */ + } disc_res; /*!< discovery result parameter struct */ + + /** + * @brief ESP_BT_GAP_DISC_STATE_CHANGED_EVT + */ + struct disc_state_changed_param { + esp_bt_gap_discovery_state_t state; /*!< discovery state */ + } disc_st_chg; /*!< discovery state changed parameter struct */ + + /** + * @brief ESP_BT_GAP_RMT_SRVCS_EVT + */ + struct rmt_srvcs_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_status_t stat; /*!< service search status */ + int num_uuids; /*!< number of UUID in uuid_list */ + esp_bt_uuid_t *uuid_list; /*!< list of service UUIDs of remote device */ + } rmt_srvcs; /*!< services of remote device parameter struct */ + + /** + * @brief ESP_BT_GAP_RMT_SRVC_REC_EVT + */ + struct rmt_srvc_rec_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_status_t stat; /*!< service search status */ + } rmt_srvc_rec; /*!< specific service record from remote device parameter struct */ + + /** + * @brief ESP_BT_GAP_READ_RSSI_DELTA_EVT * + */ + struct read_rssi_delta_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_status_t stat; /*!< read rssi status */ + int8_t rssi_delta; /*!< rssi delta value range -128 ~127, The value zero indicates that the RSSI is inside the Golden Receive Power Range, the Golden Receive Power Range is from ESP_BT_GAP_RSSI_LOW_THRLD to ESP_BT_GAP_RSSI_HIGH_THRLD */ + } read_rssi_delta; /*!< read rssi parameter struct */ + + /** + * @brief ESP_BT_GAP_CONFIG_EIR_DATA_EVT * + */ + struct config_eir_data_param { + esp_bt_status_t stat; /*!< config EIR status: + ESP_BT_STATUS_SUCCESS: config success + ESP_BT_STATUS_EIR_TOO_LARGE: the EIR data is more than 240B. The EIR may not contain the whole data. + others: failed + */ + uint8_t eir_type_num; /*!< the number of EIR types in EIR type */ + esp_bt_eir_type_t eir_type[ESP_BT_EIR_TYPE_MAX_NUM]; /*!< EIR types in EIR type */ + } config_eir_data; /*!< config EIR data */ + + /** + * @brief ESP_BT_GAP_AUTH_CMPL_EVT + */ + struct auth_cmpl_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_status_t stat; /*!< authentication complete status */ + uint8_t device_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; /*!< device name */ + } auth_cmpl; /*!< authentication complete parameter struct */ + + /** + * @brief ESP_BT_GAP_PIN_REQ_EVT + */ + struct pin_req_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + bool min_16_digit; /*!< TRUE if the pin returned must be at least 16 digits */ + } pin_req; /*!< pin request parameter struct */ + + /** + * @brief ESP_BT_GAP_CFM_REQ_EVT + */ + struct cfm_req_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + uint32_t num_val; /*!< the numeric value for comparison. */ + } cfm_req; /*!< confirm request parameter struct */ + + /** + * @brief ESP_BT_GAP_KEY_NOTIF_EVT + */ + struct key_notif_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + uint32_t passkey; /*!< the numeric value for passkey entry. */ + } key_notif; /*!< passkey notif parameter struct */ + + /** + * @brief ESP_BT_GAP_KEY_REQ_EVT + */ + struct key_req_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + } key_req; /*!< passkey request parameter struct */ + + /** + * @brief ESP_BT_GAP_SET_AFH_CHANNELS_EVT + */ + struct set_afh_channels_param { + esp_bt_status_t stat; /*!< set AFH channel status */ + } set_afh_channels; /*!< set AFH channel parameter struct */ + + /** + * @brief ESP_BT_GAP_READ_REMOTE_NAME_EVT + */ + struct read_rmt_name_param { + esp_bt_status_t stat; /*!< read Remote Name status */ + uint8_t rmt_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; /*!< Remote device name */ + } read_rmt_name; /*!< read Remote Name parameter struct */ + + /** + * @brief ESP_BT_GAP_MODE_CHG_EVT + */ + struct mode_chg_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_pm_mode_t mode; /*!< PM mode*/ + } mode_chg; /*!< mode change event parameter struct */ + + /** + * @brief ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT + */ + struct bt_remove_bond_dev_cmpl_evt_param { + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + esp_bt_status_t status; /*!< Indicate the remove bond device operation success status */ + }remove_bond_dev_cmpl; /*!< Event parameter of ESP_BT_GAP_REMOVE_BOND_DEV_COMPLETE_EVT */ + + /** + * @brief ESP_BT_GAP_QOS_CMPL_EVT + */ + struct qos_cmpl_param { + esp_bt_status_t stat; /*!< QoS status */ + esp_bd_addr_t bda; /*!< remote bluetooth device address*/ + uint32_t t_poll; /*!< poll interval, the maximum time between transmissions + which from the master to a particular slave on the ACL + logical transport. unit is 0.625ms. */ + } qos_cmpl; /*!< QoS complete parameter struct */ +} esp_bt_gap_cb_param_t; + +/** + * @brief bluetooth GAP callback function type + * + * @param event : Event type + * + * @param param : Pointer to callback parameter + */ +typedef void (* esp_bt_gap_cb_t)(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param); + +/** + * @brief get major service field of COD + * + * @param[in] cod: Class of Device + * + * @return major service bits + */ +static inline uint32_t esp_bt_gap_get_cod_srvc(uint32_t cod) +{ + return (cod & ESP_BT_COD_SRVC_BIT_MASK) >> ESP_BT_COD_SRVC_BIT_OFFSET; +} + +/** + * @brief get major device field of COD + * + * @param[in] cod: Class of Device + * + * @return major device bits + */ +static inline uint32_t esp_bt_gap_get_cod_major_dev(uint32_t cod) +{ + return (cod & ESP_BT_COD_MAJOR_DEV_BIT_MASK) >> ESP_BT_COD_MAJOR_DEV_BIT_OFFSET; +} + +/** + * @brief get minor service field of COD + * + * @param[in] cod: Class of Device + * + * @return minor service bits + */ +static inline uint32_t esp_bt_gap_get_cod_minor_dev(uint32_t cod) +{ + return (cod & ESP_BT_COD_MINOR_DEV_BIT_MASK) >> ESP_BT_COD_MINOR_DEV_BIT_OFFSET; +} + +/** + * @brief get format type of COD + * + * @param[in] cod: Class of Device + * + * @return format type + */ +static inline uint32_t esp_bt_gap_get_cod_format_type(uint32_t cod) +{ + return (cod & ESP_BT_COD_FORMAT_TYPE_BIT_MASK); +} + +/** + * @brief decide the integrity of COD + * + * @param[in] cod: Class of Device + * + * @return + * - true if cod is valid + * - false otherise + */ +static inline bool esp_bt_gap_is_valid_cod(uint32_t cod) +{ + if (esp_bt_gap_get_cod_format_type(cod) == ESP_BT_COD_FORMAT_TYPE_1 && + esp_bt_gap_get_cod_srvc(cod) != ESP_BT_COD_SRVC_NONE) { + return true; + } + + return false; +} + +/** + * @brief register callback function. This function should be called after esp_bluedroid_enable() completes successfully + * + * @return + * - ESP_OK : Succeed + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_register_callback(esp_bt_gap_cb_t callback); + +/** + * @brief Set discoverability and connectability mode for legacy bluetooth. This function should + * be called after esp_bluedroid_enable() completes successfully + * + * @param[in] c_mode : one of the enums of esp_bt_connection_mode_t + * + * @param[in] d_mode : one of the enums of esp_bt_discovery_mode_t + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_ARG: if argument invalid + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_set_scan_mode(esp_bt_connection_mode_t c_mode, esp_bt_discovery_mode_t d_mode); + +/** + * @brief This function starts Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. + * When Inquiry is halted and cached results do not contain device name, then Name Discovery will connect to the peer target to get the device name. + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT when Inquriry is started or Name Discovery is completed. + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_RES_EVT each time the two types of discovery results are got. + * + * @param[in] mode - Inquiry mode + * + * @param[in] inq_len - Inquiry duration in 1.28 sec units, ranging from 0x01 to 0x30. This parameter only specifies the total duration of the Inquiry process, + * - when this time expires, Inquiry will be halted. + * + * @param[in] num_rsps - Number of responses that can be received before the Inquiry is halted, value 0 indicates an unlimited number of responses. + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_ERR_INVALID_ARG: if invalid parameters are provided + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_start_discovery(esp_bt_inq_mode_t mode, uint8_t inq_len, uint8_t num_rsps); + +/** + * @brief Cancel Inquiry and Name Discovery. This function should be called after esp_bluedroid_enable() completes successfully. + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_DISC_STATE_CHANGED_EVT if Inquiry or Name Discovery is cancelled by + * calling this function. + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_cancel_discovery(void); + +/** + * @brief Start SDP to get remote services. This function should be called after esp_bluedroid_enable() completes successfully. + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVCS_EVT after service discovery ends. + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_get_remote_services(esp_bd_addr_t remote_bda); + +/** + * @brief Start SDP to look up the service matching uuid on the remote device. This function should be called after + * esp_bluedroid_enable() completes successfully. + * + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_RMT_SRVC_REC_EVT after service discovery ends + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_get_remote_service_record(esp_bd_addr_t remote_bda, esp_bt_uuid_t *uuid); + +/** + * @brief This function is called to get EIR data for a specific type. + * + * @param[in] eir - pointer of raw eir data to be resolved + * @param[in] type - specific EIR data type + * @param[out] length - return the length of EIR data excluding fields of length and data type + * + * @return pointer of starting position of eir data excluding eir data type, NULL if not found + * + */ +uint8_t *esp_bt_gap_resolve_eir_data(uint8_t *eir, esp_bt_eir_type_t type, uint8_t *length); + +/** + * @brief This function is called to config EIR data. + * + * esp_bt_gap_cb_t will be called with ESP_BT_GAP_CONFIG_EIR_DATA_EVT after config EIR ends. + * + * @param[in] eir_data - pointer of EIR data content + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_ERR_INVALID_ARG: if param is invalid + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_config_eir_data(esp_bt_eir_data_t *eir_data); + +/** + * @brief This function is called to set class of device. + * The structure esp_bt_gap_cb_t will be called with ESP_BT_GAP_SET_COD_EVT after set COD ends. + * Some profile have special restrictions on class of device, changes may cause these profile do not work. + * + * @param[in] cod - class of device + * @param[in] mode - setting mode + * + * @return + * - ESP_OK : Succeed + * - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_ERR_INVALID_ARG: if param is invalid + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_set_cod(esp_bt_cod_t cod, esp_bt_cod_mode_t mode); + +/** + * @brief This function is called to get class of device. + * + * @param[out] cod - class of device + * + * @return + * - ESP_OK : Succeed + * - ESP_FAIL: others + */ +esp_err_t esp_bt_gap_get_cod(esp_bt_cod_t *cod); + +/** + * @brief This function is called to read RSSI delta by address after connected. The RSSI value returned by ESP_BT_GAP_READ_RSSI_DELTA_EVT. + * + * + * @param[in] remote_addr - remote device address, corresponding to a certain connection handle + * @return + * - ESP_OK : Succeed + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_gap_read_rssi_delta(esp_bd_addr_t remote_addr); + +/** +* @brief Removes a device from the security database list of +* peer device. +* +* @param[in] bd_addr : BD address of the peer device +* +* @return - ESP_OK : success +* - ESP_FAIL : failed +* +*/ +esp_err_t esp_bt_gap_remove_bond_device(esp_bd_addr_t bd_addr); + +/** +* @brief Get the device number from the security database list of peer device. +* It will return the device bonded number immediately. +* +* @return - >= 0 : bonded devices number +* - ESP_FAIL : failed +* +*/ +int esp_bt_gap_get_bond_device_num(void); + +/** +* @brief Get the device from the security database list of peer device. +* It will return the device bonded information immediately. +* +* @param[inout] dev_num: Indicate the dev_list array(buffer) size as input. +* If dev_num is large enough, it means the actual number as output. +* Suggest that dev_num value equal to esp_ble_get_bond_device_num(). +* +* @param[out] dev_list: an array(buffer) of `esp_bd_addr_t` type. Use for storing the bonded devices address. +* The dev_list should be allocated by who call this API. +* +* @return +* - ESP_OK : Succeed +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - ESP_FAIL: others +*/ +esp_err_t esp_bt_gap_get_bond_device_list(int *dev_num, esp_bd_addr_t *dev_list); + +/** +* @brief Set pin type and default pin code for legacy pairing. +* +* @param[in] pin_type: Use variable or fixed pin. +* If pin_type is ESP_BT_PIN_TYPE_VARIABLE, pin_code and pin_code_len +* will be ignored, and ESP_BT_GAP_PIN_REQ_EVT will come when control +* requests for pin code. +* Else, will use fixed pin code and not callback to users. +* +* @param[in] pin_code_len: Length of pin_code +* +* @param[in] pin_code: Pin_code +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +*/ +esp_err_t esp_bt_gap_set_pin(esp_bt_pin_type_t pin_type, uint8_t pin_code_len, esp_bt_pin_code_t pin_code); + +/** +* @brief Reply the pin_code to the peer device for legacy pairing +* when ESP_BT_GAP_PIN_REQ_EVT is coming. +* +* @param[in] bd_addr: BD address of the peer +* +* @param[in] accept: Pin_code reply successful or declined. +* +* @param[in] pin_code_len: Length of pin_code +* +* @param[in] pin_code: Pin_code +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +*/ +esp_err_t esp_bt_gap_pin_reply(esp_bd_addr_t bd_addr, bool accept, uint8_t pin_code_len, esp_bt_pin_code_t pin_code); + +#if (BT_SSP_INCLUDED == TRUE) +/** +* @brief Set a GAP security parameter value. Overrides the default value. +* +* @param[in] param_type : the type of the param which is to be set +* +* @param[in] value : the param value +* +* @param[in] len : the length of the param value +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_set_security_param(esp_bt_sp_param_t param_type, + void *value, uint8_t len); + +/** +* @brief Reply the key value to the peer device in the legacy connection stage. +* +* @param[in] bd_addr : BD address of the peer +* +* @param[in] accept : passkey entry successful or declined. +* +* @param[in] passkey : passkey value, must be a 6 digit number, can be lead by 0. +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_ssp_passkey_reply(esp_bd_addr_t bd_addr, bool accept, uint32_t passkey); + + +/** +* @brief Reply the confirm value to the peer device in the legacy connection stage. +* +* @param[in] bd_addr : BD address of the peer device +* +* @param[in] accept : numbers to compare are the same or different +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_ssp_confirm_reply(esp_bd_addr_t bd_addr, bool accept); + +#endif /*(BT_SSP_INCLUDED == TRUE)*/ + +/** +* @brief Set the AFH channels +* +* @param[in] channels : The n th such field (in the range 0 to 78) contains the value for channel n : +* 0 means channel n is bad. +* 1 means channel n is unknown. +* The most significant bit is reserved and shall be set to 0. +* At least 20 channels shall be marked as unknown. +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_set_afh_channels(esp_bt_gap_afh_channels channels); + +/** +* @brief Read the remote device name +* +* @param[in] remote_bda: The remote device's address +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_read_remote_name(esp_bd_addr_t remote_bda); + +/** +* @brief Config Quality of service +* +* @param[in] remote_bda: The remote device's address +* @param[in] t_poll: Poll interval, the maximum time between transmissions + which from the master to a particular slave on the ACL + logical transport. unit is 0.625ms +* +* @return - ESP_OK : success +* - ESP_ERR_INVALID_STATE: if bluetooth stack is not yet enabled +* - other : failed +* +*/ +esp_err_t esp_bt_gap_set_qos(esp_bd_addr_t remote_bda, uint32_t t_poll); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GAP_BT_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_common_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_common_api.h new file mode 100644 index 00000000..447a26bd --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_common_api.h @@ -0,0 +1,56 @@ +// Copyright 2015-2017 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. + +#ifndef __ESP_GATT_COMMON_API_H__ +#define __ESP_GATT_COMMON_API_H__ + +#include +#include + +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Maximum Transmission Unit used in GATT +#define ESP_GATT_DEF_BLE_MTU_SIZE 23 /* relate to GATT_DEF_BLE_MTU_SIZE in stack/gatt_api.h */ + +// Maximum Transmission Unit allowed in GATT +#define ESP_GATT_MAX_MTU_SIZE 517 /* relate to GATT_MAX_MTU_SIZE in stack/gatt_api.h */ + +/** + * @brief This function is called to set local MTU, + * the function is called before BLE connection. + * + * @param[in] mtu: the size of MTU. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +extern esp_err_t esp_ble_gatt_set_local_mtu (uint16_t mtu); + +#if (BLE_INCLUDED == TRUE) +extern uint16_t esp_ble_get_sendable_packets_num (void); +extern uint16_t esp_ble_get_cur_sendable_packets_num (uint16_t connid); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GATT_COMMON_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_defs.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_defs.h new file mode 100644 index 00000000..9177753b --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatt_defs.h @@ -0,0 +1,492 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_GATT_DEFS_H__ +#define __ESP_GATT_DEFS_H__ + +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// GATT INVALID UUID +#define ESP_GATT_ILLEGAL_UUID 0 +/// GATT INVALID HANDLE +#define ESP_GATT_ILLEGAL_HANDLE 0 +/// GATT attribute max handle +#define ESP_GATT_ATTR_HANDLE_MAX 100 +#define ESP_GATT_MAX_READ_MULTI_HANDLES 10 /* Max attributes to read in one request */ + + +/**@{ + * All "ESP_GATT_UUID_xxx" is attribute types + */ +#define ESP_GATT_UUID_IMMEDIATE_ALERT_SVC 0x1802 /* Immediate alert Service*/ +#define ESP_GATT_UUID_LINK_LOSS_SVC 0x1803 /* Link Loss Service*/ +#define ESP_GATT_UUID_TX_POWER_SVC 0x1804 /* TX Power Service*/ +#define ESP_GATT_UUID_CURRENT_TIME_SVC 0x1805 /* Current Time Service Service*/ +#define ESP_GATT_UUID_REF_TIME_UPDATE_SVC 0x1806 /* Reference Time Update Service*/ +#define ESP_GATT_UUID_NEXT_DST_CHANGE_SVC 0x1807 /* Next DST Change Service*/ +#define ESP_GATT_UUID_GLUCOSE_SVC 0x1808 /* Glucose Service*/ +#define ESP_GATT_UUID_HEALTH_THERMOM_SVC 0x1809 /* Health Thermometer Service*/ +#define ESP_GATT_UUID_DEVICE_INFO_SVC 0x180A /* Device Information Service*/ +#define ESP_GATT_UUID_HEART_RATE_SVC 0x180D /* Heart Rate Service*/ +#define ESP_GATT_UUID_PHONE_ALERT_STATUS_SVC 0x180E /* Phone Alert Status Service*/ +#define ESP_GATT_UUID_BATTERY_SERVICE_SVC 0x180F /* Battery Service*/ +#define ESP_GATT_UUID_BLOOD_PRESSURE_SVC 0x1810 /* Blood Pressure Service*/ +#define ESP_GATT_UUID_ALERT_NTF_SVC 0x1811 /* Alert Notification Service*/ +#define ESP_GATT_UUID_HID_SVC 0x1812 /* HID Service*/ +#define ESP_GATT_UUID_SCAN_PARAMETERS_SVC 0x1813 /* Scan Parameters Service*/ +#define ESP_GATT_UUID_RUNNING_SPEED_CADENCE_SVC 0x1814 /* Running Speed and Cadence Service*/ +#define ESP_GATT_UUID_Automation_IO_SVC 0x1815 /* Automation IO Service*/ +#define ESP_GATT_UUID_CYCLING_SPEED_CADENCE_SVC 0x1816 /* Cycling Speed and Cadence Service*/ +#define ESP_GATT_UUID_CYCLING_POWER_SVC 0x1818 /* Cycling Power Service*/ +#define ESP_GATT_UUID_LOCATION_AND_NAVIGATION_SVC 0x1819 /* Location and Navigation Service*/ +#define ESP_GATT_UUID_ENVIRONMENTAL_SENSING_SVC 0x181A /* Environmental Sensing Service*/ +#define ESP_GATT_UUID_BODY_COMPOSITION 0x181B /* Body Composition Service*/ +#define ESP_GATT_UUID_USER_DATA_SVC 0x181C /* User Data Service*/ +#define ESP_GATT_UUID_WEIGHT_SCALE_SVC 0x181D /* Weight Scale Service*/ +#define ESP_GATT_UUID_BOND_MANAGEMENT_SVC 0x181E /* Bond Management Service*/ +#define ESP_GATT_UUID_CONT_GLUCOSE_MONITOR_SVC 0x181F /* Continuous Glucose Monitoring Service*/ + +#define ESP_GATT_UUID_PRI_SERVICE 0x2800 +#define ESP_GATT_UUID_SEC_SERVICE 0x2801 +#define ESP_GATT_UUID_INCLUDE_SERVICE 0x2802 +#define ESP_GATT_UUID_CHAR_DECLARE 0x2803 /* Characteristic Declaration*/ + +#define ESP_GATT_UUID_CHAR_EXT_PROP 0x2900 /* Characteristic Extended Properties */ +#define ESP_GATT_UUID_CHAR_DESCRIPTION 0x2901 /* Characteristic User Description*/ +#define ESP_GATT_UUID_CHAR_CLIENT_CONFIG 0x2902 /* Client Characteristic Configuration */ +#define ESP_GATT_UUID_CHAR_SRVR_CONFIG 0x2903 /* Server Characteristic Configuration */ +#define ESP_GATT_UUID_CHAR_PRESENT_FORMAT 0x2904 /* Characteristic Presentation Format*/ +#define ESP_GATT_UUID_CHAR_AGG_FORMAT 0x2905 /* Characteristic Aggregate Format*/ +#define ESP_GATT_UUID_CHAR_VALID_RANGE 0x2906 /* Characteristic Valid Range */ +#define ESP_GATT_UUID_EXT_RPT_REF_DESCR 0x2907 /* External Report Reference */ +#define ESP_GATT_UUID_RPT_REF_DESCR 0x2908 /* Report Reference */ +#define ESP_GATT_UUID_NUM_DIGITALS_DESCR 0x2909 /* Number of Digitals */ +#define ESP_GATT_UUID_VALUE_TRIGGER_DESCR 0x290A /* Value Trigger Setting */ +#define ESP_GATT_UUID_ENV_SENSING_CONFIG_DESCR 0x290B /* Environmental Sensing Configuration */ +#define ESP_GATT_UUID_ENV_SENSING_MEASUREMENT_DESCR 0x290C /* Environmental Sensing Measurement */ +#define ESP_GATT_UUID_ENV_SENSING_TRIGGER_DESCR 0x290D /* Environmental Sensing Trigger Setting */ +#define ESP_GATT_UUID_TIME_TRIGGER_DESCR 0x290E /* Time Trigger Setting */ + +/* GAP Profile Attributes */ +#define ESP_GATT_UUID_GAP_DEVICE_NAME 0x2A00 +#define ESP_GATT_UUID_GAP_ICON 0x2A01 +#define ESP_GATT_UUID_GAP_PREF_CONN_PARAM 0x2A04 +#define ESP_GATT_UUID_GAP_CENTRAL_ADDR_RESOL 0x2AA6 + +/* Attribute Profile Attribute UUID */ +#define ESP_GATT_UUID_GATT_SRV_CHGD 0x2A05 + +/* Link ESP_Loss Service */ +#define ESP_GATT_UUID_ALERT_LEVEL 0x2A06 /* Alert Level */ +#define ESP_GATT_UUID_TX_POWER_LEVEL 0x2A07 /* TX power level */ + +/* Current Time Service */ +#define ESP_GATT_UUID_CURRENT_TIME 0x2A2B /* Current Time */ +#define ESP_GATT_UUID_LOCAL_TIME_INFO 0x2A0F /* Local time info */ +#define ESP_GATT_UUID_REF_TIME_INFO 0x2A14 /* reference time information */ + +/* Network availability Profile */ +#define ESP_GATT_UUID_NW_STATUS 0x2A18 /* network availability status */ +#define ESP_GATT_UUID_NW_TRIGGER 0x2A1A /* Network availability trigger */ + +/* Phone alert */ +#define ESP_GATT_UUID_ALERT_STATUS 0x2A3F /* alert status */ +#define ESP_GATT_UUID_RINGER_CP 0x2A40 /* ringer control point */ +#define ESP_GATT_UUID_RINGER_SETTING 0x2A41 /* ringer setting */ + +/* Glucose Service */ +#define ESP_GATT_UUID_GM_MEASUREMENT 0x2A18 +#define ESP_GATT_UUID_GM_CONTEXT 0x2A34 +#define ESP_GATT_UUID_GM_CONTROL_POINT 0x2A52 +#define ESP_GATT_UUID_GM_FEATURE 0x2A51 + +/* device information characteristic */ +#define ESP_GATT_UUID_SYSTEM_ID 0x2A23 +#define ESP_GATT_UUID_MODEL_NUMBER_STR 0x2A24 +#define ESP_GATT_UUID_SERIAL_NUMBER_STR 0x2A25 +#define ESP_GATT_UUID_FW_VERSION_STR 0x2A26 +#define ESP_GATT_UUID_HW_VERSION_STR 0x2A27 +#define ESP_GATT_UUID_SW_VERSION_STR 0x2A28 +#define ESP_GATT_UUID_MANU_NAME 0x2A29 +#define ESP_GATT_UUID_IEEE_DATA 0x2A2A +#define ESP_GATT_UUID_PNP_ID 0x2A50 + +/* HID characteristics */ +#define ESP_GATT_UUID_HID_INFORMATION 0x2A4A +#define ESP_GATT_UUID_HID_REPORT_MAP 0x2A4B +#define ESP_GATT_UUID_HID_CONTROL_POINT 0x2A4C +#define ESP_GATT_UUID_HID_REPORT 0x2A4D +#define ESP_GATT_UUID_HID_PROTO_MODE 0x2A4E +#define ESP_GATT_UUID_HID_BT_KB_INPUT 0x2A22 +#define ESP_GATT_UUID_HID_BT_KB_OUTPUT 0x2A32 +#define ESP_GATT_UUID_HID_BT_MOUSE_INPUT 0x2A33 + + /// Heart Rate Measurement +#define ESP_GATT_HEART_RATE_MEAS 0x2A37 +/// Body Sensor Location +#define ESP_GATT_BODY_SENSOR_LOCATION 0x2A38 +/// Heart Rate Control Point +#define ESP_GATT_HEART_RATE_CNTL_POINT 0x2A39 + +/* Battery Service characteristics */ +#define ESP_GATT_UUID_BATTERY_LEVEL 0x2A19 + +/* Sensor Service */ +#define ESP_GATT_UUID_SC_CONTROL_POINT 0x2A55 +#define ESP_GATT_UUID_SENSOR_LOCATION 0x2A5D + +/* Runners speed and cadence service */ +#define ESP_GATT_UUID_RSC_MEASUREMENT 0x2A53 +#define ESP_GATT_UUID_RSC_FEATURE 0x2A54 + +/* Cycling speed and cadence service */ +#define ESP_GATT_UUID_CSC_MEASUREMENT 0x2A5B +#define ESP_GATT_UUID_CSC_FEATURE 0x2A5C + +/* Scan ESP_Parameter characteristics */ +#define ESP_GATT_UUID_SCAN_INT_WINDOW 0x2A4F +#define ESP_GATT_UUID_SCAN_REFRESH 0x2A31 +/** + * @} + */ + +/* relate to BTA_GATT_PREP_WRITE_xxx in bta/bta_gatt_api.h */ +/// Attribute write data type from the client +typedef enum { + ESP_GATT_PREP_WRITE_CANCEL = 0x00, /*!< Prepare write cancel */ /* relate to BTA_GATT_PREP_WRITE_CANCEL in bta/bta_gatt_api.h */ + ESP_GATT_PREP_WRITE_EXEC = 0x01, /*!< Prepare write execute */ /* relate to BTA_GATT_PREP_WRITE_EXEC in bta/bta_gatt_api.h */ +} esp_gatt_prep_write_type; + +/* relate to BTA_GATT_xxx in bta/bta_gatt_api.h */ +/** + * @brief GATT success code and error codes + */ +typedef enum { + ESP_GATT_OK = 0x0, /* relate to BTA_GATT_OK in bta/bta_gatt_api.h */ + ESP_GATT_INVALID_HANDLE = 0x01, /* 0x0001 */ /* relate to BTA_GATT_INVALID_HANDLE in bta/bta_gatt_api.h */ + ESP_GATT_READ_NOT_PERMIT = 0x02, /* 0x0002 */ /* relate to BTA_GATT_READ_NOT_PERMIT in bta/bta_gatt_api.h */ + ESP_GATT_WRITE_NOT_PERMIT = 0x03, /* 0x0003 */ /* relate to BTA_GATT_WRITE_NOT_PERMIT in bta/bta_gatt_api.h */ + ESP_GATT_INVALID_PDU = 0x04, /* 0x0004 */ /* relate to BTA_GATT_INVALID_PDU in bta/bta_gatt_api.h */ + ESP_GATT_INSUF_AUTHENTICATION = 0x05, /* 0x0005 */ /* relate to BTA_GATT_INSUF_AUTHENTICATION in bta/bta_gatt_api.h */ + ESP_GATT_REQ_NOT_SUPPORTED = 0x06, /* 0x0006 */ /* relate to BTA_GATT_REQ_NOT_SUPPORTED in bta/bta_gatt_api.h */ + ESP_GATT_INVALID_OFFSET = 0x07, /* 0x0007 */ /* relate to BTA_GATT_INVALID_OFFSET in bta/bta_gatt_api.h */ + ESP_GATT_INSUF_AUTHORIZATION = 0x08, /* 0x0008 */ /* relate to BTA_GATT_INSUF_AUTHORIZATION in bta/bta_gatt_api.h */ + ESP_GATT_PREPARE_Q_FULL = 0x09, /* 0x0009 */ /* relate to BTA_GATT_PREPARE_Q_FULL in bta/bta_gatt_api.h */ + ESP_GATT_NOT_FOUND = 0x0a, /* 0x000a */ /* relate to BTA_GATT_NOT_FOUND in bta/bta_gatt_api.h */ + ESP_GATT_NOT_LONG = 0x0b, /* 0x000b */ /* relate to BTA_GATT_NOT_LONG in bta/bta_gatt_api.h */ + ESP_GATT_INSUF_KEY_SIZE = 0x0c, /* 0x000c */ /* relate to BTA_GATT_INSUF_KEY_SIZE in bta/bta_gatt_api.h */ + ESP_GATT_INVALID_ATTR_LEN = 0x0d, /* 0x000d */ /* relate to BTA_GATT_INVALID_ATTR_LEN in bta/bta_gatt_api.h */ + ESP_GATT_ERR_UNLIKELY = 0x0e, /* 0x000e */ /* relate to BTA_GATT_ERR_UNLIKELY in bta/bta_gatt_api.h */ + ESP_GATT_INSUF_ENCRYPTION = 0x0f, /* 0x000f */ /* relate to BTA_GATT_INSUF_ENCRYPTION in bta/bta_gatt_api.h */ + ESP_GATT_UNSUPPORT_GRP_TYPE = 0x10, /* 0x0010 */ /* relate to BTA_GATT_UNSUPPORT_GRP_TYPE in bta/bta_gatt_api.h */ + ESP_GATT_INSUF_RESOURCE = 0x11, /* 0x0011 */ /* relate to BTA_GATT_INSUF_RESOURCE in bta/bta_gatt_api.h */ + + ESP_GATT_NO_RESOURCES = 0x80, /* 0x80 */ /* relate to BTA_GATT_NO_RESOURCES in bta/bta_gatt_api.h */ + ESP_GATT_INTERNAL_ERROR = 0x81, /* 0x81 */ /* relate to BTA_GATT_INTERNAL_ERROR in bta/bta_gatt_api.h */ + ESP_GATT_WRONG_STATE = 0x82, /* 0x82 */ /* relate to BTA_GATT_WRONG_STATE in bta/bta_gatt_api.h */ + ESP_GATT_DB_FULL = 0x83, /* 0x83 */ /* relate to BTA_GATT_DB_FULL in bta/bta_gatt_api.h */ + ESP_GATT_BUSY = 0x84, /* 0x84 */ /* relate to BTA_GATT_BUSY in bta/bta_gatt_api.h */ + ESP_GATT_ERROR = 0x85, /* 0x85 */ /* relate to BTA_GATT_ERROR in bta/bta_gatt_api.h */ + ESP_GATT_CMD_STARTED = 0x86, /* 0x86 */ /* relate to BTA_GATT_CMD_STARTED in bta/bta_gatt_api.h */ + ESP_GATT_ILLEGAL_PARAMETER = 0x87, /* 0x87 */ /* relate to BTA_GATT_ILLEGAL_PARAMETER in bta/bta_gatt_api.h */ + ESP_GATT_PENDING = 0x88, /* 0x88 */ /* relate to BTA_GATT_PENDING in bta/bta_gatt_api.h */ + ESP_GATT_AUTH_FAIL = 0x89, /* 0x89 */ /* relate to BTA_GATT_AUTH_FAIL in bta/bta_gatt_api.h */ + ESP_GATT_MORE = 0x8a, /* 0x8a */ /* relate to BTA_GATT_MORE in bta/bta_gatt_api.h */ + ESP_GATT_INVALID_CFG = 0x8b, /* 0x8b */ /* relate to BTA_GATT_INVALID_CFG in bta/bta_gatt_api.h */ + ESP_GATT_SERVICE_STARTED = 0x8c, /* 0x8c */ /* relate to BTA_GATT_SERVICE_STARTED in bta/bta_gatt_api.h */ + ESP_GATT_ENCRYPED_MITM = ESP_GATT_OK, /* relate to BTA_GATT_ENCRYPED_MITM in bta/bta_gatt_api.h */ + ESP_GATT_ENCRYPED_NO_MITM = 0x8d, /* 0x8d */ /* relate to BTA_GATT_ENCRYPED_NO_MITM in bta/bta_gatt_api.h */ + ESP_GATT_NOT_ENCRYPTED = 0x8e, /* 0x8e */ /* relate to BTA_GATT_NOT_ENCRYPTED in bta/bta_gatt_api.h */ + ESP_GATT_CONGESTED = 0x8f, /* 0x8f */ /* relate to BTA_GATT_CONGESTED in bta/bta_gatt_api.h */ + ESP_GATT_DUP_REG = 0x90, /* 0x90 */ /* relate to BTA_GATT_DUP_REG in bta/bta_gatt_api.h */ + ESP_GATT_ALREADY_OPEN = 0x91, /* 0x91 */ /* relate to BTA_GATT_ALREADY_OPEN in bta/bta_gatt_api.h */ + ESP_GATT_CANCEL = 0x92, /* 0x92 */ /* relate to BTA_GATT_CANCEL in bta/bta_gatt_api.h */ + /* 0xE0 ~ 0xFC reserved for future use */ + ESP_GATT_STACK_RSP = 0xe0, /* 0xe0 */ /* relate to BTA_GATT_STACK_RSP in bta/bta_gatt_api.h */ + ESP_GATT_APP_RSP = 0xe1, /* 0xe1 */ /* relate to BTA_GATT_APP_RSP in bta/bta_gatt_api.h */ + //Error caused by customer application or stack bug + ESP_GATT_UNKNOWN_ERROR = 0xef, /* 0xef */ /* relate to BTA_GATT_UNKNOWN_ERROR in bta/bta_gatt_api.h */ + ESP_GATT_CCC_CFG_ERR = 0xfd, /* 0xFD Client Characteristic Configuration Descriptor Improperly Configured */ /* relate to BTA_GATT_CCC_CFG_ERR in bta/bta_gatt_api.h */ + ESP_GATT_PRC_IN_PROGRESS = 0xfe, /* 0xFE Procedure Already in progress */ /* relate to BTA_GATT_PRC_IN_PROGRESS in bta/bta_gatt_api.h */ + ESP_GATT_OUT_OF_RANGE = 0xff, /* 0xFFAttribute value out of range */ /* relate to BTA_GATT_OUT_OF_RANGE in bta/bta_gatt_api.h */ +} esp_gatt_status_t; + +/* relate to BTA_GATT_CONN_xxx in bta/bta_gatt_api.h */ +/** + * @brief Gatt Connection reason enum + */ +typedef enum { + ESP_GATT_CONN_UNKNOWN = 0, /*!< Gatt connection unknown */ /* relate to BTA_GATT_CONN_UNKNOWN in bta/bta_gatt_api.h */ + ESP_GATT_CONN_L2C_FAILURE = 1, /*!< General L2cap failure */ /* relate to BTA_GATT_CONN_L2C_FAILURE in bta/bta_gatt_api.h */ + ESP_GATT_CONN_TIMEOUT = 0x08, /*!< Connection timeout */ /* relate to BTA_GATT_CONN_TIMEOUT in bta/bta_gatt_api.h */ + ESP_GATT_CONN_TERMINATE_PEER_USER = 0x13, /*!< Connection terminate by peer user */ /* relate to BTA_GATT_CONN_TERMINATE_PEER_USER in bta/bta_gatt_api.h */ + ESP_GATT_CONN_TERMINATE_LOCAL_HOST = 0x16, /*!< Connection terminated by local host */ /* relate to BTA_GATT_CONN_TERMINATE_LOCAL_HOST in bta/bta_gatt_api.h */ + ESP_GATT_CONN_FAIL_ESTABLISH = 0x3e, /*!< Connection fail to establish */ /* relate to BTA_GATT_CONN_FAIL_ESTABLISH in bta/bta_gatt_api.h */ + ESP_GATT_CONN_LMP_TIMEOUT = 0x22, /*!< Connection fail for LMP response tout */ /* relate to BTA_GATT_CONN_LMP_TIMEOUT in bta/bta_gatt_api.h */ + ESP_GATT_CONN_CONN_CANCEL = 0x0100, /*!< L2CAP connection cancelled */ /* relate to BTA_GATT_CONN_CONN_CANCEL in bta/bta_gatt_api.h */ + ESP_GATT_CONN_NONE = 0x0101 /*!< No connection to cancel */ /* relate to BTA_GATT_CONN_NONE in bta/bta_gatt_api.h */ +} esp_gatt_conn_reason_t; + +/** + * @brief Gatt id, include uuid and instance id + */ +typedef struct { + esp_bt_uuid_t uuid; /*!< UUID */ + uint8_t inst_id; /*!< Instance id */ +} __attribute__((packed)) esp_gatt_id_t; + +/** + * @brief Gatt service id, include id + * (uuid and instance id) and primary flag + */ +typedef struct { + esp_gatt_id_t id; /*!< Gatt id, include uuid and instance */ + bool is_primary; /*!< This service is primary or not */ +} __attribute__((packed)) esp_gatt_srvc_id_t; + +/* relate to BTA_GATT_AUTH_REQ_xxx in bta/bta_gatt_api.h */ +/** + * @brief Gatt authentication request type + */ +typedef enum { + ESP_GATT_AUTH_REQ_NONE = 0, /* relate to BTA_GATT_AUTH_REQ_NONE in bta/bta_gatt_api.h */ + ESP_GATT_AUTH_REQ_NO_MITM = 1, /* unauthenticated encryption */ /* relate to BTA_GATT_AUTH_REQ_NO_MITM in bta/bta_gatt_api.h */ + ESP_GATT_AUTH_REQ_MITM = 2, /* authenticated encryption */ /* relate to BTA_GATT_AUTH_REQ_MITM in bta/bta_gatt_api.h */ + ESP_GATT_AUTH_REQ_SIGNED_NO_MITM = 3, /* relate to BTA_GATT_AUTH_REQ_SIGNED_NO_MITM in bta/bta_gatt_api.h */ + ESP_GATT_AUTH_REQ_SIGNED_MITM = 4, /* relate to BTA_GATT_AUTH_REQ_SIGNED_MITM in bta/bta_gatt_api.h */ +} esp_gatt_auth_req_t; + +/* relate to BTA_GATT_PERM_xxx in bta/bta_gatt_api.h */ +/** + * @brief Attribute permissions + */ +#define ESP_GATT_PERM_READ (1 << 0) /* bit 0 - 0x0001 */ /* relate to BTA_GATT_PERM_READ in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_READ_ENCRYPTED (1 << 1) /* bit 1 - 0x0002 */ /* relate to BTA_GATT_PERM_READ_ENCRYPTED in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_READ_ENC_MITM (1 << 2) /* bit 2 - 0x0004 */ /* relate to BTA_GATT_PERM_READ_ENC_MITM in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_WRITE (1 << 4) /* bit 4 - 0x0010 */ /* relate to BTA_GATT_PERM_WRITE in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_WRITE_ENCRYPTED (1 << 5) /* bit 5 - 0x0020 */ /* relate to BTA_GATT_PERM_WRITE_ENCRYPTED in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_WRITE_ENC_MITM (1 << 6) /* bit 6 - 0x0040 */ /* relate to BTA_GATT_PERM_WRITE_ENC_MITM in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_WRITE_SIGNED (1 << 7) /* bit 7 - 0x0080 */ /* relate to BTA_GATT_PERM_WRITE_SIGNED in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_WRITE_SIGNED_MITM (1 << 8) /* bit 8 - 0x0100 */ /* relate to BTA_GATT_PERM_WRITE_SIGNED_MITM in bta/bta_gatt_api.h */ +#define ESP_GATT_PERM_READ_AUTHORIZATION (1 << 9) /* bit 9 - 0x0200 */ +#define ESP_GATT_PERM_WRITE_AUTHORIZATION (1 << 10) /* bit 10 - 0x0400 */ +typedef uint16_t esp_gatt_perm_t; + +/* relate to BTA_GATT_CHAR_PROP_BIT_xxx in bta/bta_gatt_api.h */ +/* definition of characteristic properties */ +#define ESP_GATT_CHAR_PROP_BIT_BROADCAST (1 << 0) /* 0x01 */ /* relate to BTA_GATT_CHAR_PROP_BIT_BROADCAST in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_READ (1 << 1) /* 0x02 */ /* relate to BTA_GATT_CHAR_PROP_BIT_READ in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_WRITE_NR (1 << 2) /* 0x04 */ /* relate to BTA_GATT_CHAR_PROP_BIT_WRITE_NR in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_WRITE (1 << 3) /* 0x08 */ /* relate to BTA_GATT_CHAR_PROP_BIT_WRITE in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_NOTIFY (1 << 4) /* 0x10 */ /* relate to BTA_GATT_CHAR_PROP_BIT_NOTIFY in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_INDICATE (1 << 5) /* 0x20 */ /* relate to BTA_GATT_CHAR_PROP_BIT_INDICATE in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_AUTH (1 << 6) /* 0x40 */ /* relate to BTA_GATT_CHAR_PROP_BIT_AUTH in bta/bta_gatt_api.h */ +#define ESP_GATT_CHAR_PROP_BIT_EXT_PROP (1 << 7) /* 0x80 */ /* relate to BTA_GATT_CHAR_PROP_BIT_EXT_PROP in bta/bta_gatt_api.h */ +typedef uint8_t esp_gatt_char_prop_t; + +/// GATT maximum attribute length +#define ESP_GATT_MAX_ATTR_LEN 600 //as same as GATT_MAX_ATTR_LEN + +typedef enum { + ESP_GATT_SERVICE_FROM_REMOTE_DEVICE = 0, /* relate to BTA_GATTC_SERVICE_INFO_FROM_REMOTE_DEVICE in bta_gattc_int.h */ + ESP_GATT_SERVICE_FROM_NVS_FLASH = 1, /* relate to BTA_GATTC_SERVICE_INFO_FROM_NVS_FLASH in bta_gattc_int.h */ + ESP_GATT_SERVICE_FROM_UNKNOWN = 2, /* relate to BTA_GATTC_SERVICE_INFO_FROM_UNKNOWN in bta_gattc_int.h */ +} esp_service_source_t; + +/** + * @brief Attribute description (used to create database) + */ + typedef struct + { + uint16_t uuid_length; /*!< UUID length */ + uint8_t *uuid_p; /*!< UUID value */ + uint16_t perm; /*!< Attribute permission */ + uint16_t max_length; /*!< Maximum length of the element*/ + uint16_t length; /*!< Current length of the element*/ + uint8_t *value; /*!< Element value array*/ + } esp_attr_desc_t; + + +/** + * @brief attribute auto response flag + */ +typedef struct +{ +#define ESP_GATT_RSP_BY_APP 0 +#define ESP_GATT_AUTO_RSP 1 + /** + * @brief if auto_rsp set to ESP_GATT_RSP_BY_APP, means the response of Write/Read operation will by replied by application. + if auto_rsp set to ESP_GATT_AUTO_RSP, means the response of Write/Read operation will be replied by GATT stack automatically. + */ + uint8_t auto_rsp; +} esp_attr_control_t; + + +/** + * @brief attribute type added to the gatt server database + */ +typedef struct +{ + esp_attr_control_t attr_control; /*!< The attribute control type */ + esp_attr_desc_t att_desc; /*!< The attribute type */ +} esp_gatts_attr_db_t; + + +/** + * @brief set the attribute value type + */ +typedef struct +{ + uint16_t attr_max_len; /*!< attribute max value length */ + uint16_t attr_len; /*!< attribute current value length */ + uint8_t *attr_value; /*!< the pointer to attribute value */ +} esp_attr_value_t; + + +/** + * @brief Gatt include service entry element + */ +typedef struct +{ + uint16_t start_hdl; /*!< Gatt start handle value of included service */ + uint16_t end_hdl; /*!< Gatt end handle value of included service */ + uint16_t uuid; /*!< Gatt attribute value UUID of included service */ +} esp_gatts_incl_svc_desc_t; /*!< Gatt include service entry element */ + +/** + * @brief Gatt include 128 bit service entry element + */ +typedef struct +{ + uint16_t start_hdl; /*!< Gatt start handle value of included 128 bit service */ + uint16_t end_hdl; /*!< Gatt end handle value of included 128 bit service */ +} esp_gatts_incl128_svc_desc_t; /*!< Gatt include 128 bit service entry element */ + +/// Gatt attribute value +typedef struct { + uint8_t value[ESP_GATT_MAX_ATTR_LEN]; /*!< Gatt attribute value */ + uint16_t handle; /*!< Gatt attribute handle */ + uint16_t offset; /*!< Gatt attribute value offset */ + uint16_t len; /*!< Gatt attribute value length */ + uint8_t auth_req; /*!< Gatt authentication request */ +} esp_gatt_value_t; + +/// GATT remote read request response type +typedef union { + esp_gatt_value_t attr_value; /*!< Gatt attribute structure */ + uint16_t handle; /*!< Gatt attribute handle */ +} esp_gatt_rsp_t; + +/** + * @brief Gatt write type + */ +typedef enum { + ESP_GATT_WRITE_TYPE_NO_RSP = 1, /*!< Gatt write attribute need no response */ + ESP_GATT_WRITE_TYPE_RSP, /*!< Gatt write attribute need remote response */ +} esp_gatt_write_type_t; + +/** + * @brief Connection parameters information + */ +typedef struct { + uint16_t interval; /*!< connection interval */ + uint16_t latency; /*!< Slave latency for the connection in number of connection events. Range: 0x0000 to 0x01F3 */ + uint16_t timeout; /*!< Supervision timeout for the LE Link. Range: 0x000A to 0x0C80. + Mandatory Range: 0x000A to 0x0C80 Time = N * 10 msec + Time Range: 100 msec to 32 seconds */ +} esp_gatt_conn_params_t; + +#define ESP_GATT_IF_NONE 0xff /*!< If callback report gattc_if/gatts_if as this macro, means this event is not correspond to any app */ + +typedef uint8_t esp_gatt_if_t; /*!< Gatt interface type, different application on GATT client use different gatt_if */ + +/** + * @brief the type of attribute element + */ +typedef enum { + ESP_GATT_DB_PRIMARY_SERVICE, /*!< Gattc primary service attribute type in the cache */ + ESP_GATT_DB_SECONDARY_SERVICE, /*!< Gattc secondary service attribute type in the cache */ + ESP_GATT_DB_CHARACTERISTIC, /*!< Gattc characteristic attribute type in the cache */ + ESP_GATT_DB_DESCRIPTOR, /*!< Gattc characteristic descriptor attribute type in the cache */ + ESP_GATT_DB_INCLUDED_SERVICE, /*!< Gattc include service attribute type in the cache */ + ESP_GATT_DB_ALL, /*!< Gattc all the attribute (primary service & secondary service & include service & char & descriptor) type in the cache */ +} esp_gatt_db_attr_type_t; /*!< Gattc attribute type element */ + +/** + * @brief read multiple attribute + */ +typedef struct { + uint8_t num_attr; /*!< The number of the attribute */ + uint16_t handles[ESP_GATT_MAX_READ_MULTI_HANDLES]; /*!< The handles list */ +} esp_gattc_multi_t; /*!< The gattc multiple read element */ + +/** + * @brief data base attribute element + */ +typedef struct { + esp_gatt_db_attr_type_t type; /*!< The attribute type */ + uint16_t attribute_handle; /*!< The attribute handle, it's valid for all of the type */ + uint16_t start_handle; /*!< The service start handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE */ + uint16_t end_handle; /*!< The service end handle, it's valid only when the type = ESP_GATT_DB_PRIMARY_SERVICE or ESP_GATT_DB_SECONDARY_SERVICE */ + esp_gatt_char_prop_t properties; /*!< The characteristic properties, it's valid only when the type = ESP_GATT_DB_CHARACTERISTIC */ + esp_bt_uuid_t uuid; /*!< The attribute uuid, it's valid for all of the type */ +} esp_gattc_db_elem_t; /*!< The gattc service data base element in the cache */ + +/** + * @brief service element + */ +typedef struct { + bool is_primary; /*!< The service flag, true if the service is primary service, else is secondary service */ + uint16_t start_handle; /*!< The start handle of the service */ + uint16_t end_handle; /*!< The end handle of the service */ + esp_bt_uuid_t uuid; /*!< The uuid of the service */ +} esp_gattc_service_elem_t; /*!< The gattc service element */ + +/** + * @brief characteristic element + */ +typedef struct { + uint16_t char_handle; /*!< The characteristic handle */ + esp_gatt_char_prop_t properties; /*!< The characteristic properties */ + esp_bt_uuid_t uuid; /*!< The characteristic uuid */ +} esp_gattc_char_elem_t; /*!< The gattc characteristic element */ + +/** + * @brief descriptor element + */ +typedef struct { + uint16_t handle; /*!< The characteristic descriptor handle */ + esp_bt_uuid_t uuid; /*!< The characteristic descriptor uuid */ +} esp_gattc_descr_elem_t; /*!< The gattc descriptor type element */ + +/** + * @brief include service element + */ +typedef struct { + uint16_t handle; /*!< The include service current attribute handle */ + uint16_t incl_srvc_s_handle; /*!< The start handle of the service which has been included */ + uint16_t incl_srvc_e_handle; /*!< The end handle of the service which has been included */ + esp_bt_uuid_t uuid; /*!< The include service uuid */ +} esp_gattc_incl_svc_elem_t; /*!< The gattc include service element */ + + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GATT_DEFS_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gattc_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gattc_api.h new file mode 100644 index 00000000..70a9b153 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gattc_api.h @@ -0,0 +1,891 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_GATTC_API_H__ +#define __ESP_GATTC_API_H__ + +#include "esp_bt_defs.h" +#include "esp_gatt_defs.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// GATT Client callback function events +typedef enum { + ESP_GATTC_REG_EVT = 0, /*!< When GATT client is registered, the event comes */ + ESP_GATTC_UNREG_EVT = 1, /*!< When GATT client is unregistered, the event comes */ + ESP_GATTC_OPEN_EVT = 2, /*!< When GATT virtual connection is set up, the event comes */ + ESP_GATTC_READ_CHAR_EVT = 3, /*!< When GATT characteristic is read, the event comes */ + ESP_GATTC_WRITE_CHAR_EVT = 4, /*!< When GATT characteristic write operation completes, the event comes */ + ESP_GATTC_CLOSE_EVT = 5, /*!< When GATT virtual connection is closed, the event comes */ + ESP_GATTC_SEARCH_CMPL_EVT = 6, /*!< When GATT service discovery is completed, the event comes */ + ESP_GATTC_SEARCH_RES_EVT = 7, /*!< When GATT service discovery result is got, the event comes */ + ESP_GATTC_READ_DESCR_EVT = 8, /*!< When GATT characteristic descriptor read completes, the event comes */ + ESP_GATTC_WRITE_DESCR_EVT = 9, /*!< When GATT characteristic descriptor write completes, the event comes */ + ESP_GATTC_NOTIFY_EVT = 10, /*!< When GATT notification or indication arrives, the event comes */ + ESP_GATTC_PREP_WRITE_EVT = 11, /*!< When GATT prepare-write operation completes, the event comes */ + ESP_GATTC_EXEC_EVT = 12, /*!< When write execution completes, the event comes */ + ESP_GATTC_ACL_EVT = 13, /*!< When ACL connection is up, the event comes */ + ESP_GATTC_CANCEL_OPEN_EVT = 14, /*!< When GATT client ongoing connection is cancelled, the event comes */ + ESP_GATTC_SRVC_CHG_EVT = 15, /*!< When "service changed" occurs, the event comes */ + ESP_GATTC_ENC_CMPL_CB_EVT = 17, /*!< When encryption procedure completes, the event comes */ + ESP_GATTC_CFG_MTU_EVT = 18, /*!< When configuration of MTU completes, the event comes */ + ESP_GATTC_ADV_DATA_EVT = 19, /*!< When advertising of data, the event comes */ + ESP_GATTC_MULT_ADV_ENB_EVT = 20, /*!< When multi-advertising is enabled, the event comes */ + ESP_GATTC_MULT_ADV_UPD_EVT = 21, /*!< When multi-advertising parameters are updated, the event comes */ + ESP_GATTC_MULT_ADV_DATA_EVT = 22, /*!< When multi-advertising data arrives, the event comes */ + ESP_GATTC_MULT_ADV_DIS_EVT = 23, /*!< When multi-advertising is disabled, the event comes */ + ESP_GATTC_CONGEST_EVT = 24, /*!< When GATT connection congestion comes, the event comes */ + ESP_GATTC_BTH_SCAN_ENB_EVT = 25, /*!< When batch scan is enabled, the event comes */ + ESP_GATTC_BTH_SCAN_CFG_EVT = 26, /*!< When batch scan storage is configured, the event comes */ + ESP_GATTC_BTH_SCAN_RD_EVT = 27, /*!< When Batch scan read event is reported, the event comes */ + ESP_GATTC_BTH_SCAN_THR_EVT = 28, /*!< When Batch scan threshold is set, the event comes */ + ESP_GATTC_BTH_SCAN_PARAM_EVT = 29, /*!< When Batch scan parameters are set, the event comes */ + ESP_GATTC_BTH_SCAN_DIS_EVT = 30, /*!< When Batch scan is disabled, the event comes */ + ESP_GATTC_SCAN_FLT_CFG_EVT = 31, /*!< When Scan filter configuration completes, the event comes */ + ESP_GATTC_SCAN_FLT_PARAM_EVT = 32, /*!< When Scan filter parameters are set, the event comes */ + ESP_GATTC_SCAN_FLT_STATUS_EVT = 33, /*!< When Scan filter status is reported, the event comes */ + ESP_GATTC_ADV_VSC_EVT = 34, /*!< When advertising vendor spec content event is reported, the event comes */ + ESP_GATTC_REG_FOR_NOTIFY_EVT = 38, /*!< When register for notification of a service completes, the event comes */ + ESP_GATTC_UNREG_FOR_NOTIFY_EVT = 39, /*!< When unregister for notification of a service completes, the event comes */ + ESP_GATTC_CONNECT_EVT = 40, /*!< When the ble physical connection is set up, the event comes */ + ESP_GATTC_DISCONNECT_EVT = 41, /*!< When the ble physical connection disconnected, the event comes */ + ESP_GATTC_READ_MULTIPLE_EVT = 42, /*!< When the ble characteristic or descriptor multiple complete, the event comes */ + ESP_GATTC_QUEUE_FULL_EVT = 43, /*!< When the gattc command queue full, the event comes */ + ESP_GATTC_SET_ASSOC_EVT = 44, /*!< When the ble gattc set the associated address complete, the event comes */ + ESP_GATTC_GET_ADDR_LIST_EVT = 45, /*!< When the ble get gattc address list in cache finish, the event comes */ + ESP_GATTC_DIS_SRVC_CMPL_EVT = 46, /*!< When the ble discover service complete, the event comes */ +} esp_gattc_cb_event_t; + + +/** + * @brief Gatt client callback parameters union + */ +typedef union { + /** + * @brief ESP_GATTC_REG_EVT + */ + struct gattc_reg_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t app_id; /*!< Application id which input in register API */ + } reg; /*!< Gatt client callback param of ESP_GATTC_REG_EVT */ + + /** + * @brief ESP_GATTC_OPEN_EVT + */ + struct gattc_open_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + uint16_t mtu; /*!< MTU size */ + } open; /*!< Gatt client callback param of ESP_GATTC_OPEN_EVT */ + + /** + * @brief ESP_GATTC_CLOSE_EVT + */ + struct gattc_close_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + esp_gatt_conn_reason_t reason; /*!< The reason of gatt connection close */ + } close; /*!< Gatt client callback param of ESP_GATTC_CLOSE_EVT */ + + /** + * @brief ESP_GATTC_CFG_MTU_EVT + */ + struct gattc_cfg_mtu_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + uint16_t mtu; /*!< MTU size */ + } cfg_mtu; /*!< Gatt client callback param of ESP_GATTC_CFG_MTU_EVT */ + + /** + * @brief ESP_GATTC_SEARCH_CMPL_EVT + */ + struct gattc_search_cmpl_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + esp_service_source_t searched_service_source; /*!< The source of the service information */ + } search_cmpl; /*!< Gatt client callback param of ESP_GATTC_SEARCH_CMPL_EVT */ + + /** + * @brief ESP_GATTC_SEARCH_RES_EVT + */ + struct gattc_search_res_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint16_t start_handle; /*!< Service start handle */ + uint16_t end_handle; /*!< Service end handle */ + esp_gatt_id_t srvc_id; /*!< Service id, include service uuid and other information */ + bool is_primary; /*!< True if this is the primary service */ + } search_res; /*!< Gatt client callback param of ESP_GATTC_SEARCH_RES_EVT */ + + /** + * @brief ESP_GATTC_READ_CHAR_EVT, ESP_GATTC_READ_DESCR_EVT + */ + struct gattc_read_char_evt_param { + + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + uint16_t handle; /*!< Characteristic handle */ + uint8_t *value; /*!< Characteristic value */ + uint16_t value_len; /*!< Characteristic value length */ + } read; /*!< Gatt client callback param of ESP_GATTC_READ_CHAR_EVT */ + + /** + * @brief ESP_GATTC_WRITE_CHAR_EVT, ESP_GATTC_PREP_WRITE_EVT, ESP_GATTC_WRITE_DESCR_EVT + */ + struct gattc_write_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + uint16_t handle; /*!< The Characteristic or descriptor handle */ + uint16_t offset; /*!< The prepare write offset, this value is valid only when prepare write */ + } write; /*!< Gatt client callback param of ESP_GATTC_WRITE_DESCR_EVT */ + + /** + * @brief ESP_GATTC_EXEC_EVT + */ + struct gattc_exec_cmpl_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + } exec_cmpl; /*!< Gatt client callback param of ESP_GATTC_EXEC_EVT */ + + /** + * @brief ESP_GATTC_NOTIFY_EVT + */ + struct gattc_notify_evt_param { + uint16_t conn_id; /*!< Connection id */ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + uint16_t handle; /*!< The Characteristic or descriptor handle */ + uint16_t value_len; /*!< Notify attribute value */ + uint8_t *value; /*!< Notify attribute value */ + bool is_notify; /*!< True means notify, false means indicate */ + } notify; /*!< Gatt client callback param of ESP_GATTC_NOTIFY_EVT */ + + /** + * @brief ESP_GATTC_SRVC_CHG_EVT + */ + struct gattc_srvc_chg_evt_param { + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + } srvc_chg; /*!< Gatt client callback param of ESP_GATTC_SRVC_CHG_EVT */ + + /** + * @brief ESP_GATTC_CONGEST_EVT + */ + struct gattc_congest_evt_param { + uint16_t conn_id; /*!< Connection id */ + bool congested; /*!< Congested or not */ + } congest; /*!< Gatt client callback param of ESP_GATTC_CONGEST_EVT */ + /** + * @brief ESP_GATTC_REG_FOR_NOTIFY_EVT + */ + struct gattc_reg_for_notify_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t handle; /*!< The characteristic or descriptor handle */ + } reg_for_notify; /*!< Gatt client callback param of ESP_GATTC_REG_FOR_NOTIFY_EVT */ + + /** + * @brief ESP_GATTC_UNREG_FOR_NOTIFY_EVT + */ + struct gattc_unreg_for_notify_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t handle; /*!< The characteristic or descriptor handle */ + } unreg_for_notify; /*!< Gatt client callback param of ESP_GATTC_UNREG_FOR_NOTIFY_EVT */ + + /** + * @brief ESP_GATTC_CONNECT_EVT + */ + struct gattc_connect_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint8_t link_role; /*!< Link role : master role = 0 ; slave role = 1*/ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + esp_gatt_conn_params_t conn_params; /*!< current connection parameters */ + } connect; /*!< Gatt client callback param of ESP_GATTC_CONNECT_EVT */ + + /** + * @brief ESP_GATTC_DISCONNECT_EVT + */ + struct gattc_disconnect_evt_param { + esp_gatt_conn_reason_t reason; /*!< disconnection reason */ + uint16_t conn_id; /*!< Connection id */ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + } disconnect; /*!< Gatt client callback param of ESP_GATTC_DISCONNECT_EVT */ + /** + * @brief ESP_GATTC_SET_ASSOC_EVT + */ + struct gattc_set_assoc_addr_cmp_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + } set_assoc_cmp; /*!< Gatt client callback param of ESP_GATTC_SET_ASSOC_EVT */ + /** + * @brief ESP_GATTC_GET_ADDR_LIST_EVT + */ + struct gattc_get_addr_list_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint8_t num_addr; /*!< The number of address in the gattc cache address list */ + esp_bd_addr_t *addr_list; /*!< The pointer to the address list which has been get from the gattc cache */ + } get_addr_list; /*!< Gatt client callback param of ESP_GATTC_GET_ADDR_LIST_EVT */ + + /** + * @brief ESP_GATTC_QUEUE_FULL_EVT + */ + struct gattc_queue_full_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + bool is_full; /*!< The gattc command queue is full or not */ + } queue_full; /*!< Gatt client callback param of ESP_GATTC_QUEUE_FULL_EVT */ + + /** + * @brief ESP_GATTC_DIS_SRVC_CMPL_EVT + */ + struct gattc_dis_srvc_cmpl_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + } dis_srvc_cmpl; /*!< Gatt client callback param of ESP_GATTC_DIS_SRVC_CMPL_EVT */ + +} esp_ble_gattc_cb_param_t; /*!< GATT client callback parameter union type */ + +/** + * @brief GATT Client callback function type + * @param event : Event type + * @param gatts_if : GATT client access interface, normally + * different gattc_if correspond to different profile + * @param param : Point to callback parameter, currently is union type + */ +typedef void (* esp_gattc_cb_t)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param); + +/** + * @brief This function is called to register application callbacks + * with GATTC module. + * + * @param[in] callback : pointer to the application callback function. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_register_callback(esp_gattc_cb_t callback); + + +/** + * @brief This function is called to register application callbacks + * with GATTC module. + * + * @param[in] app_id : Application Identify (UUID), for different application + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_app_register(uint16_t app_id); + + +/** + * @brief This function is called to unregister an application + * from GATTC module. + * + * @param[in] gattc_if: Gatt client access interface. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_app_unregister(esp_gatt_if_t gattc_if); + +#if (BLE_42_FEATURE_SUPPORT == TRUE) +/** + * @brief Open a direct connection or add a background auto connection + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] remote_bda: remote device bluetooth device address. + * @param[in] remote_addr_type: remote device bluetooth device the address type. + * @param[in] is_direct: direct connection or background auto connection(by now, background auto connection is not supported). + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct); +#endif // #if (BLE_42_FEATURE_SUPPORT == TRUE) + +#if (BLE_50_FEATURE_SUPPORT == TRUE) +esp_err_t esp_ble_gattc_aux_open(esp_gatt_if_t gattc_if, esp_bd_addr_t remote_bda, esp_ble_addr_type_t remote_addr_type, bool is_direct); +#endif // #if (BLE_50_FEATURE_SUPPORT == TRUE) +/** + * @brief Close the virtual connection to the GATT server. gattc may have multiple virtual GATT server connections when multiple app_id registered, + * this API only close one virtual GATT server connection. if there exist other virtual GATT server connections, + * it does not disconnect the physical connection. + * if you want to disconnect the physical connection directly, you can use esp_ble_gap_disconnect(esp_bd_addr_t remote_device). + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID to be closed. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_close (esp_gatt_if_t gattc_if, uint16_t conn_id); + + +/** + * @brief Configure the MTU size in the GATT channel. This can be done + * only once per connection. Before using, use esp_ble_gatt_set_local_mtu() + * to configure the local MTU size. + * + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_send_mtu_req (esp_gatt_if_t gattc_if, uint16_t conn_id); + + +/** + * @brief This function is called to get service from local cache. + * This function report service search result by a callback + * event, and followed by a service search complete event. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID. + * @param[in] filter_uuid: a UUID of the service application is interested in. + * If Null, discover for all services. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_search_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *filter_uuid); + +/** + * @brief Find all the service with the given service uuid in the gattc cache, if the svc_uuid is NULL, find all the service. + * Note: It just get service from local cache, won't get from remote devices. If want to get it from remote device, need + * to used the esp_ble_gattc_search_service. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] svc_uuid: the pointer to the service uuid. + * @param[out] result: The pointer to the service which has been found in the gattc cache. + * @param[inout] count: input the number of service want to find, + * it will output the number of service has been found in the gattc cache with the given service uuid. + * @param[in] offset: Offset of the service position to get. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_service(esp_gatt_if_t gattc_if, uint16_t conn_id, esp_bt_uuid_t *svc_uuid, + esp_gattc_service_elem_t *result, uint16_t *count, uint16_t offset); + +/** + * @brief Find all the characteristic with the given service in the gattc cache + * Note: It just get characteristic from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] start_handle: the attribute start handle. + * @param[in] end_handle: the attribute end handle + * @param[out] result: The pointer to the characteristic in the service. + * @param[inout] count: input the number of characteristic want to find, + * it will output the number of characteristic has been found in the gattc cache with the given service. + * @param[in] offset: Offset of the characteristic position to get. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_all_char(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t start_handle, + uint16_t end_handle, + esp_gattc_char_elem_t *result, + uint16_t *count, uint16_t offset); + +/** + * @brief Find all the descriptor with the given characteristic in the gattc cache + * Note: It just get descriptor from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] char_handle: the given characteristic handle + * @param[out] result: The pointer to the descriptor in the characteristic. + * @param[inout] count: input the number of descriptor want to find, + * it will output the number of descriptor has been found in the gattc cache with the given characteristic. + * @param[in] offset: Offset of the descriptor position to get. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_all_descr(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t char_handle, + esp_gattc_descr_elem_t *result, + uint16_t *count, uint16_t offset); + + +/** + * @brief Find the characteristic with the given characteristic uuid in the gattc cache + * Note: It just get characteristic from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] start_handle: the attribute start handle + * @param[in] end_handle: the attribute end handle + * @param[in] char_uuid: the characteristic uuid + * @param[out] result: The pointer to the characteristic in the service. + * @param[inout] count: input the number of characteristic want to find, + * it will output the number of characteristic has been found in the gattc cache with the given service. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_char_by_uuid(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t start_handle, + uint16_t end_handle, + esp_bt_uuid_t char_uuid, + esp_gattc_char_elem_t *result, + uint16_t *count); + +/** + * @brief Find the descriptor with the given characteristic uuid in the gattc cache + * Note: It just get descriptor from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] start_handle: the attribute start handle + * @param[in] end_handle: the attribute end handle + * @param[in] char_uuid: the characteristic uuid. + * @param[in] descr_uuid: the descriptor uuid. + * @param[out] result: The pointer to the descriptor in the given characteristic. + * @param[inout] count: input the number of descriptor want to find, + * it will output the number of descriptor has been found in the gattc cache with the given characteristic. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_descr_by_uuid(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t start_handle, + uint16_t end_handle, + esp_bt_uuid_t char_uuid, + esp_bt_uuid_t descr_uuid, + esp_gattc_descr_elem_t *result, + uint16_t *count); + +/** + * @brief Find the descriptor with the given characteristic handle in the gattc cache + * Note: It just get descriptor from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] char_handle: the characteristic handle. + * @param[in] descr_uuid: the descriptor uuid. + * @param[out] result: The pointer to the descriptor in the given characteristic. + * @param[inout] count: input the number of descriptor want to find, + * it will output the number of descriptor has been found in the gattc cache with the given characteristic. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_descr_by_char_handle(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t char_handle, + esp_bt_uuid_t descr_uuid, + esp_gattc_descr_elem_t *result, + uint16_t *count); + +/** + * @brief Find the include service with the given service handle in the gattc cache + * Note: It just get include service from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] start_handle: the attribute start handle + * @param[in] end_handle: the attribute end handle + * @param[in] incl_uuid: the include service uuid + * @param[out] result: The pointer to the include service in the given service. + * @param[inout] count: input the number of include service want to find, + * it will output the number of include service has been found in the gattc cache with the given service. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_include_service(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t start_handle, + uint16_t end_handle, + esp_bt_uuid_t *incl_uuid, + esp_gattc_incl_svc_elem_t *result, + uint16_t *count); + + +/** + * @brief Find the attribute count with the given service or characteristic in the gattc cache + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id: connection ID which identify the server. + * @param[in] type: the attribute type. + * @param[in] start_handle: the attribute start handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore + * @param[in] end_handle: the attribute end handle, if the type is ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore + * @param[in] char_handle: the characteristic handle, this parameter valid when the type is ESP_GATT_DB_DESCRIPTOR. If the type + * isn't ESP_GATT_DB_DESCRIPTOR, this parameter should be ignore. + * @param[out] count: output the number of attribute has been found in the gattc cache with the given attribute type. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_attr_count(esp_gatt_if_t gattc_if, + uint16_t conn_id, + esp_gatt_db_attr_type_t type, + uint16_t start_handle, + uint16_t end_handle, + uint16_t char_handle, + uint16_t *count); + +/** + * @brief This function is called to get the GATT database. + * Note: It just get attribute data base from local cache, won't get from remote devices. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] start_handle: the attribute start handle + * @param[in] end_handle: the attribute end handle + * @param[in] conn_id: connection ID which identify the server. + * @param[in] db: output parameter which will contain the GATT database copy. + * Caller is responsible for freeing it. + * @param[in] count: number of elements in database. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_gatt_status_t esp_ble_gattc_get_db(esp_gatt_if_t gattc_if, uint16_t conn_id, uint16_t start_handle, uint16_t end_handle, + esp_gattc_db_elem_t *db, uint16_t *count); + +/** + * @brief This function is called to read a service's characteristics of + * the given characteristic handle + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] handle : characteritic handle to read. + * @param[in] auth_req : authenticate request type + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_read_char (esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + esp_gatt_auth_req_t auth_req); + +/** + * @brief This function is called to read a service's characteristics of + * the given characteristic UUID + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] start_handle : the attribute start handle. + * @param[in] end_handle : the attribute end handle + * @param[in] uuid : The UUID of attribute which will be read. + * @param[in] auth_req : authenticate request type + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_read_by_type (esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t start_handle, + uint16_t end_handle, + esp_bt_uuid_t *uuid, + esp_gatt_auth_req_t auth_req); + +/** + * @brief This function is called to read multiple characteristic or + * characteristic descriptors. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] read_multi : pointer to the read multiple parameter. + * @param[in] auth_req : authenticate request type + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_read_multiple(esp_gatt_if_t gattc_if, + uint16_t conn_id, esp_gattc_multi_t *read_multi, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to read a characteristics descriptor. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] handle : descriptor handle to read. + * @param[in] auth_req : authenticate request type + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_read_char_descr (esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to write characteristic value. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] handle : characteristic handle to write. + * @param[in] value_len: length of the value to be written. + * @param[in] value : the value to be written. + * @param[in] write_type : the type of attribute write operation. + * @param[in] auth_req : authentication request. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_write_char( esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + uint16_t value_len, + uint8_t *value, + esp_gatt_write_type_t write_type, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to write characteristic descriptor value. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID + * @param[in] handle : descriptor hadle to write. + * @param[in] value_len: length of the value to be written. + * @param[in] value : the value to be written. + * @param[in] write_type : the type of attribute write operation. + * @param[in] auth_req : authentication request. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_write_char_descr (esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + uint16_t value_len, + uint8_t *value, + esp_gatt_write_type_t write_type, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to prepare write a characteristic value. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] handle : characteristic handle to prepare write. + * @param[in] offset : offset of the write value. + * @param[in] value_len: length of the value to be written. + * @param[in] value : the value to be written. + * @param[in] auth_req : authentication request. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_prepare_write(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + uint16_t offset, + uint16_t value_len, + uint8_t *value, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to prepare write a characteristic descriptor value. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] handle : characteristic descriptor handle to prepare write. + * @param[in] offset : offset of the write value. + * @param[in] value_len: length of the value to be written. + * @param[in] value : the value to be written. + * @param[in] auth_req : authentication request. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_prepare_write_char_descr(esp_gatt_if_t gattc_if, + uint16_t conn_id, + uint16_t handle, + uint16_t offset, + uint16_t value_len, + uint8_t *value, + esp_gatt_auth_req_t auth_req); + + +/** + * @brief This function is called to execute write a prepare write sequence. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] conn_id : connection ID. + * @param[in] is_execute : execute or cancel. + * + * @return + * - ESP_OK: success + * - other: failed + * + */ +esp_err_t esp_ble_gattc_execute_write (esp_gatt_if_t gattc_if, uint16_t conn_id, bool is_execute); + + +/** + * @brief This function is called to register for notification of a service. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] server_bda : target GATT server. + * @param[in] handle : GATT characteristic handle. + * + * @return + * - ESP_OK: registration succeeds + * - other: failed + * + */ +esp_err_t esp_ble_gattc_register_for_notify (esp_gatt_if_t gattc_if, + esp_bd_addr_t server_bda, + uint16_t handle); + + +/** + * @brief This function is called to de-register for notification of a service. + * + * @param[in] gattc_if: Gatt client access interface. + * @param[in] server_bda : target GATT server. + * @param[in] handle : GATT characteristic handle. + * + * @return + * - ESP_OK: unregister succeeds + * - other: failed + * + */ +esp_err_t esp_ble_gattc_unregister_for_notify (esp_gatt_if_t gattc_if, + esp_bd_addr_t server_bda, + uint16_t handle); + + +/** +* @brief Refresh the server cache store in the gattc stack of the remote device. If +* the device is connected, this API will restart the discovery of service information of the remote device +* +* @param[in] remote_bda: remote device BD address. +* +* @return +* - ESP_OK: success +* - other: failed +* +*/ +esp_err_t esp_ble_gattc_cache_refresh(esp_bd_addr_t remote_bda); + +/** +* @brief Add or delete the associated address with the source address. +* Note: The role of this API is mainly when the client side has stored a server-side database, +* when it needs to connect another device, but the device's attribute database is the same +* as the server database stored on the client-side, calling this API can use the database +* that the device has stored used as the peer server database to reduce the attribute +* database search and discovery process and speed up the connection time. +* The associated address mains that device want to used the database has stored in the local cache. +* The source address mains that device want to share the database to the associated address device. +* +* @param[in] gattc_if: Gatt client access interface. +* @param[in] src_addr: the source address which provide the attribute table. +* @param[in] assoc_addr: the associated device address which went to share the attribute table with the source address. +* @param[in] is_assoc: true add the associated device address, false remove the associated device address. +* @return +* - ESP_OK: success +* - other: failed +* +*/ +esp_err_t esp_ble_gattc_cache_assoc(esp_gatt_if_t gattc_if, esp_bd_addr_t src_addr, + esp_bd_addr_t assoc_addr, bool is_assoc); +/** +* @brief Get the address list which has store the attribute table in the gattc cache. There will +* callback ESP_GATTC_GET_ADDR_LIST_EVT event when get address list complete. +* +* @param[in] gattc_if: Gatt client access interface. +* @return +* - ESP_OK: success +* - other: failed +* +*/ +esp_err_t esp_ble_gattc_cache_get_addr_list(esp_gatt_if_t gattc_if); + +/** +* @brief Clean the service cache of this device in the gattc stack, +* +* @param[in] remote_bda: remote device BD address. +* +* @return +* - ESP_OK: success +* - other: failed +* +*/ +esp_err_t esp_ble_gattc_cache_clean(esp_bd_addr_t remote_bda); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GATTC_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatts_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatts_api.h new file mode 100644 index 00000000..475ae08c --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_gatts_api.h @@ -0,0 +1,585 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_GATTS_API_H__ +#define __ESP_GATTS_API_H__ + +#include "esp_bt_defs.h" +#include "esp_gatt_defs.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// GATT Server callback function events +typedef enum { + ESP_GATTS_REG_EVT = 0, /*!< When register application id, the event comes */ + ESP_GATTS_READ_EVT = 1, /*!< When gatt client request read operation, the event comes */ + ESP_GATTS_WRITE_EVT = 2, /*!< When gatt client request write operation, the event comes */ + ESP_GATTS_EXEC_WRITE_EVT = 3, /*!< When gatt client request execute write, the event comes */ + ESP_GATTS_MTU_EVT = 4, /*!< When set mtu complete, the event comes */ + ESP_GATTS_CONF_EVT = 5, /*!< When receive confirm, the event comes */ + ESP_GATTS_UNREG_EVT = 6, /*!< When unregister application id, the event comes */ + ESP_GATTS_CREATE_EVT = 7, /*!< When create service complete, the event comes */ + ESP_GATTS_ADD_INCL_SRVC_EVT = 8, /*!< When add included service complete, the event comes */ + ESP_GATTS_ADD_CHAR_EVT = 9, /*!< When add characteristic complete, the event comes */ + ESP_GATTS_ADD_CHAR_DESCR_EVT = 10, /*!< When add descriptor complete, the event comes */ + ESP_GATTS_DELETE_EVT = 11, /*!< When delete service complete, the event comes */ + ESP_GATTS_START_EVT = 12, /*!< When start service complete, the event comes */ + ESP_GATTS_STOP_EVT = 13, /*!< When stop service complete, the event comes */ + ESP_GATTS_CONNECT_EVT = 14, /*!< When gatt client connect, the event comes */ + ESP_GATTS_DISCONNECT_EVT = 15, /*!< When gatt client disconnect, the event comes */ + ESP_GATTS_OPEN_EVT = 16, /*!< When connect to peer, the event comes */ + ESP_GATTS_CANCEL_OPEN_EVT = 17, /*!< When disconnect from peer, the event comes */ + ESP_GATTS_CLOSE_EVT = 18, /*!< When gatt server close, the event comes */ + ESP_GATTS_LISTEN_EVT = 19, /*!< When gatt listen to be connected the event comes */ + ESP_GATTS_CONGEST_EVT = 20, /*!< When congest happen, the event comes */ + /* following is extra event */ + ESP_GATTS_RESPONSE_EVT = 21, /*!< When gatt send response complete, the event comes */ + ESP_GATTS_CREAT_ATTR_TAB_EVT = 22, /*!< When gatt create table complete, the event comes */ + ESP_GATTS_SET_ATTR_VAL_EVT = 23, /*!< When gatt set attr value complete, the event comes */ + ESP_GATTS_SEND_SERVICE_CHANGE_EVT = 24, /*!< When gatt send service change indication complete, the event comes */ +} esp_gatts_cb_event_t; + +/** + * @brief Gatt server callback parameters union + */ +typedef union { + /** + * @brief ESP_GATTS_REG_EVT + */ + struct gatts_reg_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t app_id; /*!< Application id which input in register API */ + } reg; /*!< Gatt server callback param of ESP_GATTS_REG_EVT */ + + /** + * @brief ESP_GATTS_READ_EVT + */ + struct gatts_read_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint32_t trans_id; /*!< Transfer id */ + esp_bd_addr_t bda; /*!< The bluetooth device address which been read */ + uint16_t handle; /*!< The attribute handle */ + uint16_t offset; /*!< Offset of the value, if the value is too long */ + bool is_long; /*!< The value is too long or not */ + bool need_rsp; /*!< The read operation need to do response */ + } read; /*!< Gatt server callback param of ESP_GATTS_READ_EVT */ + + + /** + * @brief ESP_GATTS_WRITE_EVT + */ + struct gatts_write_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint32_t trans_id; /*!< Transfer id */ + esp_bd_addr_t bda; /*!< The bluetooth device address which been written */ + uint16_t handle; /*!< The attribute handle */ + uint16_t offset; /*!< Offset of the value, if the value is too long */ + bool need_rsp; /*!< The write operation need to do response */ + bool is_prep; /*!< This write operation is prepare write */ + uint16_t len; /*!< The write attribute value length */ + uint8_t *value; /*!< The write attribute value */ + } write; /*!< Gatt server callback param of ESP_GATTS_WRITE_EVT */ + + /** + * @brief ESP_GATTS_EXEC_WRITE_EVT + */ + struct gatts_exec_write_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint32_t trans_id; /*!< Transfer id */ + esp_bd_addr_t bda; /*!< The bluetooth device address which been written */ +#define ESP_GATT_PREP_WRITE_CANCEL 0x00 /*!< Prepare write flag to indicate cancel prepare write */ +#define ESP_GATT_PREP_WRITE_EXEC 0x01 /*!< Prepare write flag to indicate execute prepare write */ + uint8_t exec_write_flag; /*!< Execute write flag */ + } exec_write; /*!< Gatt server callback param of ESP_GATTS_EXEC_WRITE_EVT */ + + /** + * @brief ESP_GATTS_MTU_EVT + */ + struct gatts_mtu_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint16_t mtu; /*!< MTU size */ + } mtu; /*!< Gatt server callback param of ESP_GATTS_MTU_EVT */ + + /** + * @brief ESP_GATTS_CONF_EVT + */ + struct gatts_conf_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + uint16_t handle; /*!< attribute handle */ + uint16_t len; /*!< The indication or notification value length, len is valid when send notification or indication failed */ + uint8_t *value; /*!< The indication or notification value , value is valid when send notification or indication failed */ + } conf; /*!< Gatt server callback param of ESP_GATTS_CONF_EVT (confirm) */ + + /** + * @brief ESP_GATTS_UNREG_EVT + */ + + /** + * @brief ESP_GATTS_CREATE_EVT + */ + struct gatts_create_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t service_handle; /*!< Service attribute handle */ + esp_gatt_srvc_id_t service_id; /*!< Service id, include service uuid and other information */ + } create; /*!< Gatt server callback param of ESP_GATTS_CREATE_EVT */ + + /** + * @brief ESP_GATTS_ADD_INCL_SRVC_EVT + */ + struct gatts_add_incl_srvc_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t attr_handle; /*!< Included service attribute handle */ + uint16_t service_handle; /*!< Service attribute handle */ + } add_incl_srvc; /*!< Gatt server callback param of ESP_GATTS_ADD_INCL_SRVC_EVT */ + + /** + * @brief ESP_GATTS_ADD_CHAR_EVT + */ + struct gatts_add_char_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t attr_handle; /*!< Characteristic attribute handle */ + uint16_t service_handle; /*!< Service attribute handle */ + esp_bt_uuid_t char_uuid; /*!< Characteristic uuid */ + } add_char; /*!< Gatt server callback param of ESP_GATTS_ADD_CHAR_EVT */ + + /** + * @brief ESP_GATTS_ADD_CHAR_DESCR_EVT + */ + struct gatts_add_char_descr_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t attr_handle; /*!< Descriptor attribute handle */ + uint16_t service_handle; /*!< Service attribute handle */ + esp_bt_uuid_t descr_uuid; /*!< Characteristic descriptor uuid */ + } add_char_descr; /*!< Gatt server callback param of ESP_GATTS_ADD_CHAR_DESCR_EVT */ + + /** + * @brief ESP_GATTS_DELETE_EVT + */ + struct gatts_delete_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t service_handle; /*!< Service attribute handle */ + } del; /*!< Gatt server callback param of ESP_GATTS_DELETE_EVT */ + + /** + * @brief ESP_GATTS_START_EVT + */ + struct gatts_start_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t service_handle; /*!< Service attribute handle */ + } start; /*!< Gatt server callback param of ESP_GATTS_START_EVT */ + + /** + * @brief ESP_GATTS_STOP_EVT + */ + struct gatts_stop_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t service_handle; /*!< Service attribute handle */ + } stop; /*!< Gatt server callback param of ESP_GATTS_STOP_EVT */ + + /** + * @brief ESP_GATTS_CONNECT_EVT + */ + struct gatts_connect_evt_param { + uint16_t conn_id; /*!< Connection id */ + uint8_t link_role; /*!< Link role : master role = 0 ; slave role = 1*/ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + esp_gatt_conn_params_t conn_params; /*!< current Connection parameters */ + } connect; /*!< Gatt server callback param of ESP_GATTS_CONNECT_EVT */ + + /** + * @brief ESP_GATTS_DISCONNECT_EVT + */ + struct gatts_disconnect_evt_param { + uint16_t conn_id; /*!< Connection id */ + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + esp_gatt_conn_reason_t reason; /*!< Indicate the reason of disconnection */ + } disconnect; /*!< Gatt server callback param of ESP_GATTS_DISCONNECT_EVT */ + + /** + * @brief ESP_GATTS_OPEN_EVT + */ + struct gatts_open_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + } open; /*!< Gatt server callback param of ESP_GATTS_OPEN_EVT */ + + /** + * @brief ESP_GATTS_CANCEL_OPEN_EVT + */ + struct gatts_cancel_open_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + } cancel_open; /*!< Gatt server callback param of ESP_GATTS_CANCEL_OPEN_EVT */ + + /** + * @brief ESP_GATTS_CLOSE_EVT + */ + struct gatts_close_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t conn_id; /*!< Connection id */ + } close; /*!< Gatt server callback param of ESP_GATTS_CLOSE_EVT */ + + /** + * @brief ESP_GATTS_LISTEN_EVT + */ + /** + * @brief ESP_GATTS_CONGEST_EVT + */ + struct gatts_congest_evt_param { + uint16_t conn_id; /*!< Connection id */ + bool congested; /*!< Congested or not */ + } congest; /*!< Gatt server callback param of ESP_GATTS_CONGEST_EVT */ + + /** + * @brief ESP_GATTS_RESPONSE_EVT + */ + struct gatts_rsp_evt_param { + esp_gatt_status_t status; /*!< Operation status */ + uint16_t handle; /*!< Attribute handle which send response */ + } rsp; /*!< Gatt server callback param of ESP_GATTS_RESPONSE_EVT */ + + /** + * @brief ESP_GATTS_CREAT_ATTR_TAB_EVT + */ + struct gatts_add_attr_tab_evt_param{ + esp_gatt_status_t status; /*!< Operation status */ + esp_bt_uuid_t svc_uuid; /*!< Service uuid type */ + uint8_t svc_inst_id; /*!< Service id */ + uint16_t num_handle; /*!< The number of the attribute handle to be added to the gatts database */ + uint16_t *handles; /*!< The number to the handles */ + } add_attr_tab; /*!< Gatt server callback param of ESP_GATTS_CREAT_ATTR_TAB_EVT */ + + + /** + * @brief ESP_GATTS_SET_ATTR_VAL_EVT + */ + struct gatts_set_attr_val_evt_param{ + uint16_t srvc_handle; /*!< The service handle */ + uint16_t attr_handle; /*!< The attribute handle */ + esp_gatt_status_t status; /*!< Operation status*/ + } set_attr_val; /*!< Gatt server callback param of ESP_GATTS_SET_ATTR_VAL_EVT */ + + /** + * @brief ESP_GATTS_SEND_SERVICE_CHANGE_EVT + */ + struct gatts_send_service_change_evt_param{ + esp_gatt_status_t status; /*!< Operation status*/ + } service_change; /*!< Gatt server callback param of ESP_GATTS_SEND_SERVICE_CHANGE_EVT */ + +} esp_ble_gatts_cb_param_t; + +/** + * @brief GATT Server callback function type + * @param event : Event type + * @param gatts_if : GATT server access interface, normally + * different gatts_if correspond to different profile + * @param param : Point to callback parameter, currently is union type + */ +typedef void (* esp_gatts_cb_t)(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); + +/** + * @brief This function is called to register application callbacks + * with BTA GATTS module. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_register_callback(esp_gatts_cb_t callback); + +/** + * @brief This function is called to register application identifier + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_app_register(uint16_t app_id); + + + +/** + * @brief unregister with GATT Server. + * + * @param[in] gatts_if: GATT server access interface + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_app_unregister(esp_gatt_if_t gatts_if); + + +/** + * @brief Create a service. When service creation is done, a callback + * event ESP_GATTS_CREATE_EVT is called to report status + * and service ID to the profile. The service ID obtained in + * the callback function needs to be used when adding included + * service and characteristics/descriptors into the service. + * + * @param[in] gatts_if: GATT server access interface + * @param[in] service_id: service ID. + * @param[in] num_handle: number of handle requested for this service. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_create_service(esp_gatt_if_t gatts_if, + esp_gatt_srvc_id_t *service_id, uint16_t num_handle); + + +/** + * @brief Create a service attribute tab. + * @param[in] gatts_attr_db: the pointer to the service attr tab + * @param[in] gatts_if: GATT server access interface + * @param[in] max_nb_attr: the number of attribute to be added to the service database. + * @param[in] srvc_inst_id: the instance id of the service + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_create_attr_tab(const esp_gatts_attr_db_t *gatts_attr_db, + esp_gatt_if_t gatts_if, + uint8_t max_nb_attr, + uint8_t srvc_inst_id); +/** + * @brief This function is called to add an included service. This function have to be called between + * 'esp_ble_gatts_create_service' and 'esp_ble_gatts_add_char'. After included + * service is included, a callback event ESP_GATTS_ADD_INCL_SRVC_EVT + * is reported the included service ID. + * + * @param[in] service_handle: service handle to which this included service is to + * be added. + * @param[in] included_service_handle: the service ID to be included. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_add_included_service(uint16_t service_handle, uint16_t included_service_handle); + + + +/** + * @brief This function is called to add a characteristic into a service. + * + * @param[in] service_handle: service handle to which this included service is to + * be added. + * @param[in] char_uuid : Characteristic UUID. + * @param[in] perm : Characteristic value declaration attribute permission. + * @param[in] property : Characteristic Properties + * @param[in] char_val : Characteristic value + * @param[in] control : attribute response control byte + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_add_char(uint16_t service_handle, esp_bt_uuid_t *char_uuid, + esp_gatt_perm_t perm, esp_gatt_char_prop_t property, esp_attr_value_t *char_val, + esp_attr_control_t *control); + + +/** + * @brief This function is called to add characteristic descriptor. When + * it's done, a callback event ESP_GATTS_ADD_DESCR_EVT is called + * to report the status and an ID number for this descriptor. + * + * @param[in] service_handle: service handle to which this characteristic descriptor is to + * be added. + * @param[in] perm: descriptor access permission. + * @param[in] descr_uuid: descriptor UUID. + * @param[in] char_descr_val : Characteristic descriptor value + * @param[in] control : attribute response control byte + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_add_char_descr (uint16_t service_handle, + esp_bt_uuid_t *descr_uuid, + esp_gatt_perm_t perm, esp_attr_value_t *char_descr_val, + esp_attr_control_t *control); + + + +/** + * @brief This function is called to delete a service. When this is done, + * a callback event ESP_GATTS_DELETE_EVT is report with the status. + * + * @param[in] service_handle: service_handle to be deleted. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_delete_service(uint16_t service_handle); + + + +/** + * @brief This function is called to start a service. + * + * @param[in] service_handle: the service handle to be started. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_start_service(uint16_t service_handle); + + + +/** + * @brief This function is called to stop a service. + * + * @param[in] service_handle - service to be topped. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_stop_service(uint16_t service_handle); + + + +/** + * @brief Send indicate or notify to GATT client. + * Set param need_confirm as false will send notification, otherwise indication. + * + * @param[in] gatts_if: GATT server access interface + * @param[in] conn_id - connection id to indicate. + * @param[in] attr_handle - attribute handle to indicate. + * @param[in] value_len - indicate value length. + * @param[in] value: value to indicate. + * @param[in] need_confirm - Whether a confirmation is required. + * false sends a GATT notification, true sends a GATT indication. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_send_indicate(esp_gatt_if_t gatts_if, uint16_t conn_id, uint16_t attr_handle, + uint16_t value_len, uint8_t *value, bool need_confirm); + + +/** + * @brief This function is called to send a response to a request. + * + * @param[in] gatts_if: GATT server access interface + * @param[in] conn_id - connection identifier. + * @param[in] trans_id - transfer id + * @param[in] status - response status + * @param[in] rsp - response data. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_send_response(esp_gatt_if_t gatts_if, uint16_t conn_id, uint32_t trans_id, + esp_gatt_status_t status, esp_gatt_rsp_t *rsp); + + +/** + * @brief This function is called to set the attribute value by the application + * + * @param[in] attr_handle: the attribute handle which to be set + * @param[in] length: the value length + * @param[in] value: the pointer to the attribute value + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_set_attr_value(uint16_t attr_handle, uint16_t length, const uint8_t *value); + +/** + * @brief Retrieve attribute value + * + * @param[in] attr_handle: Attribute handle. + * @param[out] length: pointer to the attribute value length + * @param[out] value: Pointer to attribute value payload, the value cannot be modified by user + * + * @return + * - ESP_GATT_OK : success + * - other : failed + * + */ +esp_gatt_status_t esp_ble_gatts_get_attr_value(uint16_t attr_handle, uint16_t *length, const uint8_t **value); + + +/** + * @brief Open a direct open connection or add a background auto connection + * + * @param[in] gatts_if: GATT server access interface + * @param[in] remote_bda: remote device bluetooth device address. + * @param[in] is_direct: direct connection or background auto connection + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_open(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda, bool is_direct); + +/** + * @brief Close a connection a remote device. + * + * @param[in] gatts_if: GATT server access interface + * @param[in] conn_id: connection ID to be closed. + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_close(esp_gatt_if_t gatts_if, uint16_t conn_id); + +/** + * @brief Send service change indication + * + * @param[in] gatts_if: GATT server access interface + * @param[in] remote_bda: remote device bluetooth device address. + * If remote_bda is NULL then it will send service change + * indication to all the connected devices and if not then + * to a specific device + * + * @return + * - ESP_OK : success + * - other : failed + * + */ +esp_err_t esp_ble_gatts_send_service_change_indication(esp_gatt_if_t gatts_if, esp_bd_addr_t remote_bda); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_GATTS_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h new file mode 100644 index 00000000..53849ba8 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_ag_api.h @@ -0,0 +1,612 @@ +// Copyright 2019 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. + +#ifndef __ESP_HF_AG_API_H__ +#define __ESP_HF_AG_API_H__ + +#include "esp_err.h" +#include "esp_bt_defs.h" +#include "esp_hf_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* features masks of HF AG */ +#define ESP_HF_PEER_FEAT_3WAY 0x01 /* Three-way calling */ +#define ESP_HF_PEER_FEAT_ECNR 0x02 /* Echo cancellation and/or noise reduction */ +#define ESP_HF_PEER_FEAT_VREC 0x04 /* Voice recognition */ +#define ESP_HF_PEER_FEAT_INBAND 0x08 /* In-band ring tone */ +#define ESP_HF_PEER_FEAT_VTAG 0x10 /* Attach a phone number to a voice tag */ +#define ESP_HF_PEER_FEAT_REJECT 0x20 /* Ability to reject incoming call */ +#define ESP_HF_PEER_FEAT_ECS 0x40 /* Enhanced Call Status */ +#define ESP_HF_PEER_FEAT_ECC 0x80 /* Enhanced Call Control */ +#define ESP_HF_PEER_FEAT_EXTERR 0x100 /* Extended error codes */ +#define ESP_HF_PEER_FEAT_CODEC 0x200 /* Codec Negotiation */ + +/* CHLD feature masks of HF AG */ +#define ESP_HF_CHLD_FEAT_REL 0x01 /* 0 Release waiting call or held calls */ +#define ESP_HF_CHLD_FEAT_REL_ACC 0x02 /* 1 Release active calls and accept other waiting or held call */ +#define ESP_HF_CHLD_FEAT_REL_X 0x04 /* 1x Release specified active call only */ +#define ESP_HF_CHLD_FEAT_HOLD_ACC 0x08 /* 2 Active calls on hold and accept other waiting or held call */ +#define ESP_HF_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold) */ +#define ESP_HF_CHLD_FEAT_MERGE 0x20 /* 3 Add held call to multiparty */ +#define ESP_HF_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnect from multiparty) */ + +/// HF callback events +typedef enum +{ + ESP_HF_CONNECTION_STATE_EVT = 0, /*!< Connection state changed event */ + ESP_HF_AUDIO_STATE_EVT, /*!< Audio connection state change event */ + ESP_HF_BVRA_RESPONSE_EVT, /*!< Voice recognition state change event */ + ESP_HF_VOLUME_CONTROL_EVT, /*!< Audio volume control command from HF Client, provided by +VGM or +VGS message */ + + ESP_HF_UNAT_RESPONSE_EVT, /*!< Unknown AT cmd Response*/ + ESP_HF_IND_UPDATE_EVT, /*!< Indicator Update Event*/ + ESP_HF_CIND_RESPONSE_EVT, /*!< Call And Device Indicator Response*/ + ESP_HF_COPS_RESPONSE_EVT, /*!< Current operator information */ + ESP_HF_CLCC_RESPONSE_EVT, /*!< List of current calls notification */ + ESP_HF_CNUM_RESPONSE_EVT, /*!< Subscriber information response from HF Client */ + ESP_HF_VTS_RESPONSE_EVT, /*!< Enable or not DTMF */ + ESP_HF_NREC_RESPONSE_EVT, /*!< Enable or not NREC */ + + ESP_HF_ATA_RESPONSE_EVT, /*!< Answer an Incoming Call */ + ESP_HF_CHUP_RESPONSE_EVT, /*!< Reject an Incoming Call */ + ESP_HF_DIAL_EVT, /*!< Origin an outgoing call with specific number or the dial the last number */ + ESP_HF_WBS_RESPONSE_EVT, /*!< Codec Status */ + ESP_HF_BCS_RESPONSE_EVT, /*!< Final Codec Choice */ +} esp_hf_cb_event_t; + +/// HFP AG callback parameters +typedef union +{ + /** + * @brief ESP_HS_CONNECTION_STATE_EVT + */ + struct hf_conn_stat_param { + esp_bd_addr_t remote_bda; /*!< Remote bluetooth device address */ + esp_hf_connection_state_t state; /*!< Connection state */ + uint32_t peer_feat; /*!< HF supported features */ + uint32_t chld_feat; /*!< AG supported features on call hold and multiparty services */ + } conn_stat; /*!< AG callback param of ESP_HF_CONNECTION_STATE_EVT */ + + /** + * @brief ESP_HF_AUDIO_STATE_EVT + */ + struct hf_audio_stat_param { + esp_bd_addr_t remote_addr; /*!< Remote bluetooth device address */ + esp_hf_audio_state_t state; /*!< Audio connection state */ + } audio_stat; /*!< AG callback param of ESP_HF_AUDIO_STATE_EVT */ + + /** + * @brief ESP_HF_BVRA_RESPONSE_EVT + */ + struct hf_vra_rep_param { + esp_bd_addr_t remote_addr; /*!< Remote bluetooth device address */ + esp_hf_vr_state_t value; /*!< Voice recognition state */ + } vra_rep; /*!< AG callback param of ESP_HF_BVRA_RESPONSE_EVT */ + + /** + * @brief ESP_HF_VOLUME_CONTROL_EVT + */ + struct hf_volume_control_param { + esp_hf_volume_type_t type; /*!< Volume control target, speaker or microphone */ + int volume; /*!< Gain, ranges from 0 to 15 */ + } volume_control; /*!< AG callback param of ESP_HF_VOLUME_CONTROL_EVT */ + + /** + * @brief ESP_HF_UNAT_RESPOSNE_EVT + */ + struct hf_unat_rep_param { + char *unat; /*!< Unknown AT command string */ + }unat_rep; /*!< AG callback param of ESP_HF_UNAT_RESPONSE_EVT */ + + /** + * @brief ESP_HF_CIND_RESPONSE_EVT + */ + struct hf_cind_param { + esp_hf_call_status_t call_status; /*!< call status indicator */ + esp_hf_call_setup_status_t call_setup_status; /*!< call setup status indicator */ + esp_hf_network_state_t svc; /*!< bluetooth proprietary call hold status indicator */ + int signal_strength; /*!< bluetooth proprietary call hold status indicator */ + esp_hf_roaming_status_t roam; /*!< bluetooth proprietary call hold status indicator */ + int battery_level; /*!< battery charge value, ranges from 0 to 5 */ + esp_hf_call_held_status_t call_held_status; /*!< bluetooth proprietary call hold status indicator */ + } cind; /*!< AG callback param of ESP_HF_CIND_RESPONSE_EVT */ + + /** + * @brief ESP_HF_DIAL_EVT + */ + struct hf_out_call_param { + esp_bd_addr_t remote_addr; /*!< remote bluetooth device address */ + char *num_or_loc; /*!< location in phone memory */ + } out_call; /*!< AG callback param of ESP_HF_DIAL_EVT */ + + /** + * @brief ESP_HF_VTS_RESPOSNE_EVT + */ + struct hf_vts_rep_param { + char *code; /*!< MTF code from HF Client */ + }vts_rep; /*!< AG callback param of ESP_HF_VTS_RESPONSE_EVT */ + + /** + * @brief ESP_HF_NREC_RESPOSNE_EVT + */ + struct hf_nrec_param { + esp_hf_nrec_t state; /*!< NREC enabled or disabled */ + } nrec; /*!< AG callback param of ESP_HF_NREC_RESPONSE_EVT */ + + /** + * @brief ESP_HF_WBS_RESPONSE_EVT + */ + struct hf_wbs_rep_param { + esp_hf_wbs_config_t codec; /*!< codec mode CVSD or mSBC */ + } wbs_rep; /*!< AG callback param of ESP_HF_WBS_RESPONSE_EVT */ + + /** + * @brief ESP_HF_BCS_RESPONSE_EVT + */ + struct hf_bcs_rep_param { + esp_hf_wbs_config_t mode; /*!< codec mode CVSD or mSBC */ + } bcs_rep; /*!< AG callback param of ESP_HF_BCS_RESPONSE_EVT */ + +} esp_hf_cb_param_t; /*!< HFP AG callback param compound*/ + +/** + * @brief AG incoming data callback function, the callback is useful in case of + * Voice Over HCI. + * + * @param[in] buf : pointer to incoming data(payload of HCI synchronous data packet), the + * buffer is allocated inside bluetooth protocol stack and will be released after + * invoke of the callback is finished. + * + * @param[in] len : size(in bytes) in buf + */ +typedef void (* esp_hf_incoming_data_cb_t)(const uint8_t *buf, uint32_t len); + +/** + * @brief AG outgoing data callback function, the callback is useful in case of + * Voice Over HCI. Once audio connection is set up and the application layer has + * prepared data to send, the lower layer will call this function to read data + * and then send. This callback is supposed to be implemented as non-blocking, + * and if data is not enough, return value 0 is supposed. + * + * @param[in] buf : pointer to incoming data(payload of HCI synchronous data packet), the + * buffer is allocated inside bluetooth protocol stack and will be released after + * invoke of the callback is finished. + * + * @param[in] len : size(in bytes) in buf + * + * @param[out] length of data successfully read + */ +typedef uint32_t (* esp_hf_outgoing_data_cb_t) (uint8_t *buf, uint32_t len); + +/** + * @brief HF AG callback function type + * + * @param event : Event type + * + * @param param : Pointer to callback parameter + */ +typedef void (* esp_hf_cb_t) (esp_hf_cb_event_t event, esp_hf_cb_param_t *param); + +/************************************************************************************ +** ESP HF API +************************************************************************************/ +/** + * @brief Register application callback function to HFP AG module. + * This function should be called only after esp_bluedroid_enable() completes successfully. + * + * @param[in] callback: HFP AG event callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_bt_hf_register_callback(esp_hf_cb_t callback); + +/** + * + * @brief Initialize the bluetooth HF AG module. + * This function should be called after esp_bluedroid_enable() completes successfully. + * + * @param[in] remote_addr: remote bluetooth device address + * + * @return + * - ESP_OK: if the initialization request is sent successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_init(esp_bd_addr_t remote_addr); + +/** + * + * @brief De-initialize for HF AG module. + * This function should be called only after esp_bluedroid_enable() completes successfully. + * + * @param[in] remote_addr: remote bluetooth device address + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_deinit(esp_bd_addr_t remote_addr); + +/** + * + * @brief To establish a Service Level Connection to remote bluetooth HFP client device. + * This function must be called after esp_bt_hf_init() and before esp_bt_hf_deinit(). + * + * @param[in] remote_bda: remote bluetooth HFP client device address + * + * @return + * - ESP_OK: connect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_connect(esp_bd_addr_t remote_bda); + +/** + * + * @brief Disconnect from the remote HFP client. This function must be called + * after esp_bt_hf_init() and before esp_bt_hf_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_disconnect(esp_bd_addr_t remote_bda); + +/** + * + * @brief Create audio connection with remote HFP client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_connect_audio(esp_bd_addr_t remote_bda); + +/** + * + * @brief Release the established audio connection with remote HFP client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_disconnect_audio(esp_bd_addr_t remote_bda); + +/** + * + * @brief Response of Volume Recognition Command(AT+VRA) from HFP client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_bda: the device address of voice recognization initiator + * + * @param[in] value: 0 - voice recognition disabled, 1- voice recognition enabled + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_vra(esp_bd_addr_t remote_bda, esp_hf_vr_state_t value); + +/** + * + * @brief Volume synchronization with HFP client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_bda: remote bluetooth device address + * + * @param[in] type: volume control target, speaker or microphone + * + * @param[in] volume: gain of the speaker of microphone, ranges 0 to 15 + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_volume_control(esp_bd_addr_t remote_bda, esp_hf_volume_control_target_t type, int volume); + + /** + * + * @brief Handle Unknown AT command from HFP Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * + * @param[in] unat: User AT command response to HF Client. + * It will response "ERROR" by default if unat is NULL. + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_unat_response(esp_bd_addr_t remote_addr, char *unat); + + /** + * + * @brief Unsolicited send extend AT error code to HFP Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_bda: remote bluetooth device address + * @param[in] response_code: AT command response code + * @param[in] error_code: CME error code + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_cmee_response(esp_bd_addr_t remote_bda, esp_hf_at_response_code_t response_code, esp_hf_cme_err_t error_code); + + /** + * + * @brief Usolicited send device status notificationto HFP Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] ntk_state: network service state + * @param[in] signal: signal strength from 0 to 5 + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_indchange_notification(esp_bd_addr_t remote_addr, esp_hf_call_status_t call_state, + esp_hf_call_setup_status_t call_setup_state, + esp_hf_network_state_t ntk_state, int signal); + + /** + * + * @brief Response to device individual indicatiors to HFP Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] ntk_state: network service state + * @param[in] signal: signal strength from 0 to 5 + * @param[in] roam: roam state + * @param[in] batt_lev: batery level from 0 to 5 + * @param[in] call_held_status: call held status + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_cind_response(esp_bd_addr_t remote_addr, + esp_hf_call_status_t call_state, + esp_hf_call_setup_status_t call_setup_state, + esp_hf_network_state_t ntk_state, int signal, esp_hf_roaming_status_t roam, int batt_lev, + esp_hf_call_held_status_t call_held_status); + +/** + * + * @brief Reponse for AT+COPS command from HF Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] name: current operator name + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_cops_response(esp_bd_addr_t remote_addr, char *name); + +/** + * + * @brief Response to AT+CLCC command from HFP Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] index: the index of current call + * @param[in] dir: call direction (incoming/outgoing) + * @param[in] current_call_state: current call state + * @param[in] mode: current call mode (voice/data/fax) + * @param[in] mpty: single or multi type + * @param[in] number: current call number + * @param[in] type: international type or unknow + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_clcc_response(esp_bd_addr_t remote_addr, int index, esp_hf_current_call_direction_t dir, + esp_hf_current_call_status_t current_call_state, esp_hf_current_call_mode_t mode, + esp_hf_current_call_mpty_type_t mpty, char *number, esp_hf_call_addr_type_t type); + +/** + * + * @brief Response for AT+CNUM command from HF Client. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] number: registration number + * @param[in] type: service type (unknown/voice/fax) + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_cnum_response(esp_bd_addr_t remote_addr, char *number, esp_hf_subscriber_service_type_t type); + +/** + * + * @brief Inform HF Client that AG Provided in-band ring tone or not. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] state: in-band ring tone state + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_bsir(esp_bd_addr_t remote_addr, esp_hf_in_band_ring_state_t state); + +/** + * + * @brief Answer Incoming Call from AG. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] num_active: the number of active call + * @param[in] num_held: the number of held call + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] number: number of the incoming call + * @param[in] call_addr_type: call address type + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_answer_call(esp_bd_addr_t remote_addr, int num_active, int num_held, + esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, + char *number, esp_hf_call_addr_type_t call_addr_type); + +/** + * + * @brief Reject Incoming Call from AG. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] num_active: the number of active call + * @param[in] num_held: the number of held call + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] number: number of the incoming call + * @param[in] call_addr_type: call address type + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_reject_call(esp_bd_addr_t remote_addr, int num_active, int num_held, + esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, + char *number, esp_hf_call_addr_type_t call_addr_type); + +/** + * + * @brief Initiate a call from AG. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] num_active: the number of active call + * @param[in] num_held: the number of held call + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] number: number of the outgoing call + * @param[in] call_addr_type: call address type + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_out_call(esp_bd_addr_t remote_addr, int num_active, int num_held, + esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, + char *number, esp_hf_call_addr_type_t call_addr_type); + +/** + * + * @brief End an ongoing call. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * + * @param[in] remote_addr: remote bluetooth device address + * @param[in] num_active: the number of active call + * @param[in] num_held: the number of held call + * @param[in] call_state: call state + * @param[in] call_setup_state: call setup state + * @param[in] number: number of the call + * @param[in] call_addr_type: call address type + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_bt_hf_end_call(esp_bd_addr_t remote_addr, int num_active, int num_held, + esp_hf_call_status_t call_state, esp_hf_call_setup_status_t call_setup_state, + char *number, esp_hf_call_addr_type_t call_addr_type); + +/** + * @brief Register AG data output function. + * The callback is only used in the case that Voice Over HCI is enabled. + * + * @param[in] recv: HFP client incoming data callback function + * @param[in] send: HFP client outgoing data callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_bt_hf_register_data_callback(esp_hf_incoming_data_cb_t recv, esp_hf_outgoing_data_cb_t send); + + +/** + * @brief Trigger the lower-layer to fetch and send audio data. + * + * This function is only used in the case that Voice Over HCI is enabled. + * As a precondition to use this API, Service Level Connection shall exist with HFP client. + * After this function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data + * + */ +void esp_hf_outgoing_data_ready(void); + +#ifdef __cplusplus +} +#endif + +#endif //__ESP_HF_AG_API_H__ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_client_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_client_api.h new file mode 100644 index 00000000..31a8fce3 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_client_api.h @@ -0,0 +1,664 @@ +// Copyright 2018 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. + +#ifndef __ESP_HF_CLIENT_API_H__ +#define __ESP_HF_CLIENT_API_H__ + +#include "esp_err.h" +#include "esp_bt_defs.h" +#include "esp_hf_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_BT_HF_CLIENT_NUMBER_LEN (32) +#define ESP_BT_HF_CLIENT_OPERATOR_NAME_LEN (16) + +/// Bluetooth HFP RFCOMM connection and service level connection status +typedef enum { + ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTED = 0, /*!< RFCOMM data link channel released */ + ESP_HF_CLIENT_CONNECTION_STATE_CONNECTING, /*!< connecting remote device on the RFCOMM data link*/ + ESP_HF_CLIENT_CONNECTION_STATE_CONNECTED, /*!< RFCOMM connection established */ + ESP_HF_CLIENT_CONNECTION_STATE_SLC_CONNECTED, /*!< service level connection established */ + ESP_HF_CLIENT_CONNECTION_STATE_DISCONNECTING, /*!< disconnecting with remote device on the RFCOMM dat link*/ +} esp_hf_client_connection_state_t; + +/// Bluetooth HFP audio connection status +typedef enum { + ESP_HF_CLIENT_AUDIO_STATE_DISCONNECTED = 0, /*!< audio connection released */ + ESP_HF_CLIENT_AUDIO_STATE_CONNECTING, /*!< audio connection has been initiated */ + ESP_HF_CLIENT_AUDIO_STATE_CONNECTED, /*!< audio connection is established */ + ESP_HF_CLIENT_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is established */ +} esp_hf_client_audio_state_t; + +/// in-band ring tone state +typedef enum { + ESP_HF_CLIENT_IN_BAND_RINGTONE_NOT_PROVIDED = 0, + ESP_HF_CLIENT_IN_BAND_RINGTONE_PROVIDED, +} esp_hf_client_in_band_ring_state_t; + +/* features masks of AG */ +#define ESP_HF_CLIENT_PEER_FEAT_3WAY 0x01 /* Three-way calling */ +#define ESP_HF_CLIENT_PEER_FEAT_ECNR 0x02 /* Echo cancellation and/or noise reduction */ +#define ESP_HF_CLIENT_PEER_FEAT_VREC 0x04 /* Voice recognition */ +#define ESP_HF_CLIENT_PEER_FEAT_INBAND 0x08 /* In-band ring tone */ +#define ESP_HF_CLIENT_PEER_FEAT_VTAG 0x10 /* Attach a phone number to a voice tag */ +#define ESP_HF_CLIENT_PEER_FEAT_REJECT 0x20 /* Ability to reject incoming call */ +#define ESP_HF_CLIENT_PEER_FEAT_ECS 0x40 /* Enhanced Call Status */ +#define ESP_HF_CLIENT_PEER_FEAT_ECC 0x80 /* Enhanced Call Control */ +#define ESP_HF_CLIENT_PEER_FEAT_EXTERR 0x100 /* Extended error codes */ +#define ESP_HF_CLIENT_PEER_FEAT_CODEC 0x200 /* Codec Negotiation */ + +/* CHLD feature masks of AG */ +#define ESP_HF_CLIENT_CHLD_FEAT_REL 0x01 /* 0 Release waiting call or held calls */ +#define ESP_HF_CLIENT_CHLD_FEAT_REL_ACC 0x02 /* 1 Release active calls and accept other waiting or held call */ +#define ESP_HF_CLIENT_CHLD_FEAT_REL_X 0x04 /* 1x Release specified active call only */ +#define ESP_HF_CLIENT_CHLD_FEAT_HOLD_ACC 0x08 /* 2 Active calls on hold and accept other waiting or held call */ +#define ESP_HF_CLIENT_CHLD_FEAT_PRIV_X 0x10 /* 2x Request private mode with specified call(put the rest on hold) */ +#define ESP_HF_CLIENT_CHLD_FEAT_MERGE 0x20 /* 3 Add held call to multiparty */ +#define ESP_HF_CLIENT_CHLD_FEAT_MERGE_DETACH 0x40 /* 4 Connect two calls and leave(disconnect from multiparty) */ + +/// HF CLIENT callback events +typedef enum { + ESP_HF_CLIENT_CONNECTION_STATE_EVT = 0, /*!< connection state changed event */ + ESP_HF_CLIENT_AUDIO_STATE_EVT, /*!< audio connection state change event */ + ESP_HF_CLIENT_BVRA_EVT, /*!< voice recognition state change event */ + ESP_HF_CLIENT_CIND_CALL_EVT, /*!< call indication */ + ESP_HF_CLIENT_CIND_CALL_SETUP_EVT, /*!< call setup indication */ + ESP_HF_CLIENT_CIND_CALL_HELD_EVT, /*!< call held indication */ + ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT, /*!< network service availability indication */ + ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT, /*!< signal strength indication */ + ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT, /*!< roaming status indication */ + ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT, /*!< battery level indication */ + ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT, /*!< current operator information */ + ESP_HF_CLIENT_BTRH_EVT, /*!< call response and hold event */ + ESP_HF_CLIENT_CLIP_EVT, /*!< Calling Line Identification notification */ + ESP_HF_CLIENT_CCWA_EVT, /*!< call waiting notification */ + ESP_HF_CLIENT_CLCC_EVT, /*!< list of current calls notification */ + ESP_HF_CLIENT_VOLUME_CONTROL_EVT, /*!< audio volume control command from AG, provided by +VGM or +VGS message */ + ESP_HF_CLIENT_AT_RESPONSE_EVT, /*!< AT command response event */ + ESP_HF_CLIENT_CNUM_EVT, /*!< subscriber information response from AG */ + ESP_HF_CLIENT_BSIR_EVT, /*!< setting of in-band ring tone */ + ESP_HF_CLIENT_BINP_EVT, /*!< requested number of last voice tag from AG */ + ESP_HF_CLIENT_RING_IND_EVT, /*!< ring indication event */ +} esp_hf_client_cb_event_t; + +/// HFP client callback parameters +typedef union { + /** + * @brief ESP_HF_CLIENT_CONNECTION_STATE_EVT + */ + struct hf_client_conn_stat_param { + esp_hf_client_connection_state_t state; /*!< HF connection state */ + uint32_t peer_feat; /*!< AG supported features */ + uint32_t chld_feat; /*!< AG supported features on call hold and multiparty services */ + esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ + } conn_stat; /*!< HF callback param of ESP_HF_CLIENT_CONNECTION_STATE_EVT */ + + /** + * @brief ESP_HF_CLIENT_AUDIO_STATE_EVT + */ + struct hf_client_audio_stat_param { + esp_hf_client_audio_state_t state; /*!< audio connection state */ + esp_bd_addr_t remote_bda; /*!< remote bluetooth device address */ + } audio_stat; /*!< HF callback param of ESP_HF_CLIENT_AUDIO_STATE_EVT */ + + /** + * @brief ESP_HF_CLIENT_BVRA_EVT + */ + struct hf_client_bvra_param { + esp_hf_vr_state_t value; /*!< voice recognition state */ + } bvra; /*!< HF callback param of ESP_HF_CLIENT_BVRA_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT + */ + struct hf_client_service_availability_param { + esp_hf_network_state_t status; /*!< service availability status */ + } service_availability; /*!< HF callback param of ESP_HF_CLIENT_CIND_SERVICE_AVAILABILITY_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT + */ + struct hf_client_network_roaming_param { + esp_hf_roaming_status_t status; /*!< roaming status */ + } roaming; /*!< HF callback param of ESP_HF_CLIENT_CIND_ROAMING_STATUS_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT + */ + struct hf_client_signal_strength_ind_param { + int value; /*!< signal strength value, ranges from 0 to 5 */ + } signal_strength; /*!< HF callback param of ESP_HF_CLIENT_CIND_SIGNAL_STRENGTH_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT + */ + struct hf_client_battery_level_ind_param { + int value; /*!< battery charge value, ranges from 0 to 5 */ + } battery_level; /*!< HF callback param of ESP_HF_CLIENT_CIND_BATTERY_LEVEL_EVT */ + + /** + * @brief ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT + */ + struct hf_client_current_operator_param { + const char *name; /*!< name of the network operator */ + } cops; /*!< HF callback param of ESP_HF_CLIENT_COPS_CURRENT_OPERATOR_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_CALL_EVT + */ + struct hf_client_call_ind_param { + esp_hf_call_status_t status; /*!< call status indicator */ + } call; /*!< HF callback param of ESP_HF_CLIENT_CIND_CALL_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_CALL_SETUP_EVT + */ + struct hf_client_call_setup_ind_param { + esp_hf_call_setup_status_t status; /*!< call setup status indicator */ + } call_setup; /*!< HF callback param of ESP_HF_CLIENT_BVRA_EVT */ + + /** + * @brief ESP_HF_CLIENT_CIND_CALL_HELD_EVT + */ + struct hf_client_call_held_ind_param { + esp_hf_call_held_status_t status; /*!< bluetooth proprietary call hold status indicator */ + } call_held; /*!< HF callback param of ESP_HF_CLIENT_CIND_CALL_HELD_EVT */ + + /** + * @brief ESP_HF_CLIENT_BTRH_EVT + */ + struct hf_client_btrh_param { + esp_hf_btrh_status_t status; /*!< call hold and response status result code */ + } btrh; /*!< HF callback param of ESP_HF_CLIENT_BRTH_EVT */ + + /** + * @brief ESP_HF_CLIENT_CLIP_EVT + */ + struct hf_client_clip_param { + const char *number; /*!< phone number string of call */ + } clip; /*!< HF callback param of ESP_HF_CLIENT_CLIP_EVT */ + + /** + * @brief ESP_HF_CLIENT_CCWA_EVT + */ + struct hf_client_ccwa_param { + const char *number; /*!< phone number string of waiting call */ + } ccwa; /*!< HF callback param of ESP_HF_CLIENT_BVRA_EVT */ + + /** + * @brief ESP_HF_CLIENT_CLCC_EVT + */ + struct hf_client_clcc_param { + int idx; /*!< numbering(starting with 1) of the call */ + esp_hf_current_call_direction_t dir; /*!< direction of the call */ + esp_hf_current_call_status_t status; /*!< status of the call */ + esp_hf_current_call_mpty_type_t mpty; /*!< multi-party flag */ + char *number; /*!< phone number(optional) */ + } clcc; /*!< HF callback param of ESP_HF_CLIENT_CLCC_EVT */ + + /** + * @brief ESP_HF_CLIENT_VOLUME_CONTROL_EVT + */ + struct hf_client_volume_control_param { + esp_hf_volume_control_target_t type; /*!< volume control target, speaker or microphone */ + int volume; /*!< gain, ranges from 0 to 15 */ + } volume_control; /*!< HF callback param of ESP_HF_CLIENT_VOLUME_CONTROL_EVT */ + + /** + * @brief ESP_HF_CLIENT_AT_RESPONSE_EVT + */ + struct hf_client_at_response_param { + esp_hf_at_response_code_t code; /*!< AT response code */ + esp_hf_cme_err_t cme; /*!< Extended Audio Gateway Error Result Code */ + } at_response; /*!< HF callback param of ESP_HF_CLIENT_AT_RESPONSE_EVT */ + + /** + * @brief ESP_HF_CLIENT_CNUM_EVT + */ + struct hf_client_cnum_param { + const char *number; /*!< phone number string */ + esp_hf_subscriber_service_type_t type; /*!< service type that the phone number relates to */ + } cnum; /*!< HF callback param of ESP_HF_CLIENT_CNUM_EVT */ + + /** + * @brief ESP_HF_CLIENT_BSIR_EVT + */ + struct hf_client_bsirparam { + esp_hf_client_in_band_ring_state_t state; /*!< setting state of in-band ring tone */ + } bsir; /*!< HF callback param of ESP_HF_CLIENT_BSIR_EVT */ + + /** + * @brief ESP_HF_CLIENT_BINP_EVT + */ + struct hf_client_binp_param { + const char *number; /*!< phone number corresponding to the last voice tag in the HF */ + } binp; /*!< HF callback param of ESP_HF_CLIENT_BINP_EVT */ + +} esp_hf_client_cb_param_t; /*!< HFP client callback parameters */ + +/** + * @brief HFP client incoming data callback function, the callback is useful in case of + * Voice Over HCI. + * @param[in] buf : pointer to incoming data(payload of HCI synchronous data packet), the + * buffer is allocated inside bluetooth protocol stack and will be released after + * invoke of the callback is finished. + * @param[in] len : size(in bytes) in buf + */ +typedef void (* esp_hf_client_incoming_data_cb_t)(const uint8_t *buf, uint32_t len); + +/** + * @brief HFP client outgoing data callback function, the callback is useful in case of + * Voice Over HCI. Once audio connection is set up and the application layer has + * prepared data to send, the lower layer will call this function to read data + * and then send. This callback is supposed to be implemented as non-blocking, + * and if data is not enough, return value 0 is supposed. + * + * @param[in] buf : pointer to incoming data(payload of HCI synchronous data packet), the + * buffer is allocated inside bluetooth protocol stack and will be released after + * invoke of the callback is finished. + * + * @param[in] len : size(in bytes) in buf + * + * @param[out] length of data successfully read + * + */ +typedef uint32_t (* esp_hf_client_outgoing_data_cb_t)(uint8_t *buf, uint32_t len); + +/** + * @brief HFP client callback function type + * + * @param event : Event type + * + * @param param : Pointer to callback parameter + */ +typedef void (* esp_hf_client_cb_t)(esp_hf_client_cb_event_t event, esp_hf_client_cb_param_t *param); + +/** + * @brief Register application callback function to HFP client module. + * This function should be called only after esp_bluedroid_enable() completes successfully. + * + * @param[in] callback: HFP client event callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_hf_client_register_callback(esp_hf_client_cb_t callback); + +/** + * + * @brief Initialize the bluetooth HFP client module. + * This function should be called after esp_bluedroid_enable() completes successfully. + * + * @return + * - ESP_OK: if the initialization request is sent successfully + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_init(void); + +/** + * + * @brief De-initialize for HFP client module. + * This function should be called only after esp_bluedroid_enable() completes successfully. + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_deinit(void); + +/** + * + * @brief Establish a Service Level Connection to remote bluetooth HFP audio gateway(AG) device. + * This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: connect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_connect(esp_bd_addr_t remote_bda); + +/** + * + * @brief Disconnect from the remote HFP audio gateway. + * This function must be called after esp_hf_client_init() and before esp_hf_client_deinit(). + * + * @param[in] remote_bda: remote bluetooth device address + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_disconnect(esp_bd_addr_t remote_bda); + +/** + * + * @brief Create audio connection with remote HFP AG. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] remote_bda: remote bluetooth device address + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_connect_audio(esp_bd_addr_t remote_bda); + +/** + * + * @brief Release the established audio connection with remote HFP AG. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] remote_bda: remote bluetooth device address + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_disconnect_audio(esp_bd_addr_t remote_bda); + +/** + * + * @brief Enable voice recognition in the AG. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_start_voice_recognition(void); + +/** + * + * @brief Disable voice recognition in the AG. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_stop_voice_recognition(void); + +/** + * + * @brief Volume synchronization with AG. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] type: volume control target, speaker or microphone + * @param[in] volume: gain of the speaker of microphone, ranges 0 to 15 + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_volume_update(esp_hf_volume_control_target_t type, int volume); + +/** + * + * @brief Place a call with a specified number, if number is NULL, last called number is called. + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] number: number string of the call. If NULL, the last number is called(aka re-dial) + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_dial(const char *number); + +/** + * + * @brief Place a call with number specified by location(speed dial). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] location: location of the number in the memory + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ + +esp_err_t esp_hf_client_dial_memory(int location); + +/** + * + * @brief Send call hold and multiparty commands, or enhanced call control commands(Use AT+CHLD). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] chld: AT+CHLD call hold and multiparty handling AT command. + * @param[in] idx: used in Enhanced Call Control Mechanisms, used if chld is + * ESP_HF_CHLD_TYPE_REL_X or ESP_HF_CHLD_TYPE_PRIV_X + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_send_chld_cmd(esp_hf_chld_type_t chld, int idx); + +/** + * + * @brief Send response and hold action command(Send AT+BTRH command) + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] btrh: response and hold action to send + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_send_btrh_cmd(esp_hf_btrh_cmd_t btrh); + +/** + * + * @brief Answer an incoming call(send ATA command). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_answer_call(void); + +/** + * + * @brief Reject an incoming call(send AT+CHUP command). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_reject_call(void); + +/** + * + * @brief Query list of current calls in AG(send AT+CLCC command). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_query_current_calls(void); + +/** + * + * @brief Query the name of currently selected network operator in AG(use AT+COPS commands). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_query_current_operator_name(void); + +/** + * + * @brief Get subscriber information number from AG(send AT+CNUM command) + * As a precondition to use this API, Service Level Connection shall exist with AG + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_retrieve_subscriber_info(void); + +/** + * + * @brief Transmit DTMF codes during an ongoing call(use AT+VTS commands) + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @param[in] code: dtmf code, single ascii character in the set 0-9, #, *, A-D + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_send_dtmf(char code); + +/** + * + * @brief Request a phone number from AG corresponding to last voice tag recorded (send AT+BINP command). + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + * @return + * - ESP_OK: disconnect request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_request_last_voice_tag_number(void); + +/** + * + * @brief Disable echo cancellation and noise reduction in the AG (use AT+NREC=0 command). + * As a precondition to use this API, Service Level Connection shall exist with AG + * + * @return + * - ESP_OK: NREC=0 request is sent to lower layer + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: others + * + */ +esp_err_t esp_hf_client_send_nrec(void); + + +/** + * @brief Register HFP client data output function; the callback is only used in + * the case that Voice Over HCI is enabled. + * + * @param[in] recv: HFP client incoming data callback function + * + * @param[in] send: HFP client outgoing data callback function + * + * @return + * - ESP_OK: success + * - ESP_INVALID_STATE: if bluetooth stack is not yet enabled + * - ESP_FAIL: if callback is a NULL function pointer + * + */ +esp_err_t esp_hf_client_register_data_callback(esp_hf_client_incoming_data_cb_t recv, + esp_hf_client_outgoing_data_cb_t send); + +/** + * @brief Trigger the lower-layer to fetch and send audio data. + * This function is only only used in the case that Voice Over HCI is enabled. After this + * function is called, lower layer will invoke esp_hf_client_outgoing_data_cb_t to fetch data. + * + * As a precondition to use this API, Service Level Connection shall exist with AG. + * + */ +void esp_hf_client_outgoing_data_ready(void); + + +/** + * @brief Initialize the down sampling converter. This is a utility function that can + * only be used in the case that Voice Over HCI is enabled. + * + * @param[in] src_sps: original samples per second(source audio data, i.e. 48000, 32000, + * 16000, 44100, 22050, 11025) + * @param[in] bits: number of bits per pcm sample (16) + * + * @param[in] channels: number of channels (i.e. mono(1), stereo(2)...) + */ +void esp_hf_client_pcm_resample_init(uint32_t src_sps, uint32_t bits, uint32_t channels); + +/** + * @brief Deinitialize the down sampling converter. + */ +void esp_hf_client_pcm_resample_deinit(void); + +/** + * @brief Down sampling utility to convert high sampling rate into 8K/16bits 1-channel mode PCM + * samples. This can only be used in the case that Voice Over HCI is enabled. + * + * @param[in] src: pointer to the buffer where the original sampling PCM are stored + * + * @param[in] in_bytes: length of the input PCM sample buffer in byte + * + * @param[in] dst: pointer to the buffer which is to be used to store the converted PCM samples + * + * @return number of samples converted + */ +int32_t esp_hf_client_pcm_resample(void *src, uint32_t in_bytes, void *dst); + +#ifdef __cplusplus +} +#endif + + +#endif /* __ESP_HF_CLIENT_API_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_defs.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_defs.h new file mode 100644 index 00000000..5e3e3cfa --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_hf_defs.h @@ -0,0 +1,348 @@ +// Copyright 2018 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. + +#ifndef __ESP_HF_DEFS_H__ +#define __ESP_HF_DEFS_H__ + +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_BT_HF_NUMBER_LEN (32) +#define ESP_BT_HF_OPERATOR_NAME_LEN (16) + +#ifndef BTC_HSAG_SERVICE_NAME +#define BTC_HSAG_SERVICE_NAME ("Headset Gateway") +#endif + +#ifndef BTC_HFAG_SERVICE_NAME +#define BTC_HFAG_SERVICE_NAME ("Handsfree Gateway") +#endif + +#ifndef BTC_HF_SERVICES +#define BTC_HF_SERVICES (BTA_HSP_SERVICE_MASK | BTA_HFP_SERVICE_MASK ) +#endif + +#ifndef BTC_HF_SERVICE_NAMES +#define BTC_HF_SERVICE_NAMES {BTC_HSAG_SERVICE_NAME , BTC_HFAG_SERVICE_NAME} +#endif + +#ifndef BTC_HF_SECURITY +#define BTC_HF_SECURITY (BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT) +#endif + +#define BTC_HF_CALL_END_TIMEOUT 6 + +#define BTC_HF_INVALID_IDX -1 + +/// in-band ring tone state +typedef enum { + ESP_HF_IN_BAND_RINGTONE_NOT_PROVIDED = 0, + ESP_HF_IN_BAND_RINGTONE_PROVIDED, +} esp_hf_in_band_ring_state_t; + +/// voice recognition state +typedef enum { + ESP_HF_VR_STATE_DISABLED = 0, /*!< voice recognition disabled */ + ESP_HF_VR_STATE_ENABLED, /*!< voice recognition enabled */ +} esp_hf_vr_state_t; + +/// Bluetooth HFP audio volume control target +typedef enum { + ESP_HF_VOLUME_CONTROL_TARGET_SPK = 0, /*!< speaker */ + ESP_HF_VOLUME_CONTROL_TARGET_MIC, /*!< microphone */ +} esp_hf_volume_control_target_t; + +/// Bluetooth HFP audio connection status +typedef enum { + ESP_HF_AUDIO_STATE_DISCONNECTED = 0, /*!< audio connection released */ + ESP_HF_AUDIO_STATE_CONNECTING, /*!< audio connection has been initiated */ + ESP_HF_AUDIO_STATE_CONNECTED, /*!< audio connection is established */ + ESP_HF_AUDIO_STATE_CONNECTED_MSBC, /*!< mSBC audio connection is established */ +} esp_hf_audio_state_t; + +typedef enum { + ESP_HF_VOLUME_TYPE_SPK = 0, + ESP_HF_VOLUME_TYPE_MIC +} esp_hf_volume_type_t; + +/// +CIND network service availability status +typedef enum +{ + ESP_HF_NETWORK_STATE_NOT_AVAILABLE = 0, + ESP_HF_NETWORK_STATE_AVAILABLE +} esp_hf_network_state_t; + +/** +CIEV Service type */ +typedef enum +{ + ESP_HF_SERVICE_TYPE_HOME = 0, + ESP_HF_SERVICE_TYPE_ROAMING +} esp_hf_service_type_t; + +/// +CIND call status indicator values +typedef enum { + ESP_HF_CALL_STATUS_NO_CALLS = 0, /*!< no call in progress */ + ESP_HF_CALL_STATUS_CALL_IN_PROGRESS = 1, /*!< call is present(active or held) */ +} esp_hf_call_status_t; + +/// +CIND call setup status indicator values +typedef enum { + ESP_HF_CALL_SETUP_STATUS_IDLE = 0, /*!< no call setup in progress */ + ESP_HF_CALL_SETUP_STATUS_INCOMING = 1, /*!< incoming call setup in progress */ + ESP_HF_CALL_SETUP_STATUS_OUTGOING_DIALING = 2, /*!< outgoing call setup in dialing state */ + ESP_HF_CALL_SETUP_STATUS_OUTGOING_ALERTING = 3, /*!< outgoing call setup in alerting state */ +} esp_hf_call_setup_status_t; + +/// +CIND roaming status indicator values +typedef enum { + ESP_HF_ROAMING_STATUS_INACTIVE = 0, /*!< roaming is not active */ + ESP_HF_ROAMING_STATUS_ACTIVE, /*!< a roaming is active */ +} esp_hf_roaming_status_t; + +/// +CIND call held indicator values +typedef enum { + ESP_HF_CALL_HELD_STATUS_NONE = 0, /*!< no calls held */ + ESP_HF_CALL_HELD_STATUS_HELD_AND_ACTIVE = 1, /*!< both active and held call */ + ESP_HF_CALL_HELD_STATUS_HELD = 2, /*!< call on hold, no active call*/ +} esp_hf_call_held_status_t; + +/// +CLCC status of the call +typedef enum { + ESP_HF_CURRENT_CALL_STATUS_ACTIVE = 0, /*!< active */ + ESP_HF_CURRENT_CALL_STATUS_HELD = 1, /*!< held */ + ESP_HF_CURRENT_CALL_STATUS_DIALING = 2, /*!< dialing (outgoing calls only) */ + ESP_HF_CURRENT_CALL_STATUS_ALERTING = 3, /*!< alerting (outgoing calls only) */ + ESP_HF_CURRENT_CALL_STATUS_INCOMING = 4, /*!< incoming (incoming calls only) */ + ESP_HF_CURRENT_CALL_STATUS_WAITING = 5, /*!< waiting (incoming calls only) */ + ESP_HF_CURRENT_CALL_STATUS_HELD_BY_RESP_HOLD = 6, /*!< call held by response and hold */ +} esp_hf_current_call_status_t; + +/// +CLCC direction of the call +typedef enum { + ESP_HF_CURRENT_CALL_DIRECTION_OUTGOING = 0, /*!< outgoing */ + ESP_HF_CURRENT_CALL_DIRECTION_INCOMING = 1, /*!< incoming */ +} esp_hf_current_call_direction_t; + +/// +CLCC multi-party call flag +typedef enum { + ESP_HF_CURRENT_CALL_MPTY_TYPE_SINGLE = 0, /*!< not a member of a multi-party call */ + ESP_HF_CURRENT_CALL_MPTY_TYPE_MULTI = 1, /*!< member of a multi-party call */ +} esp_hf_current_call_mpty_type_t; + +/// +CLCC call mode +typedef enum { + ESP_HF_CURRENT_CALL_MODE_VOICE = 0, + ESP_HF_CURRENT_CALL_MODE_DATA = 1, + ESP_HF_CURRENT_CALL_MODE_FAX = 2, +} esp_hf_current_call_mode_t; + +/// +CLCC address type +typedef enum { + ESP_HF_CALL_ADDR_TYPE_UNKNOWN = 0x81, /*!< unkown address type */ + ESP_HF_CALL_ADDR_TYPE_INTERNATIONAL = 0x91, /*!< international address */ +} esp_hf_call_addr_type_t; + +/// +CNUM service type of the phone number +typedef enum { + ESP_HF_SUBSCRIBER_SERVICE_TYPE_UNKNOWN = 0, /*!< unknown */ + ESP_HF_SUBSCRIBER_SERVICE_TYPE_VOICE, /*!< voice service */ + ESP_HF_SUBSCRIBER_SERVICE_TYPE_FAX, /*!< fax service */ +} esp_hf_subscriber_service_type_t; + +/// +BTRH response and hold result code +typedef enum { + ESP_HF_BTRH_STATUS_HELD = 0, /*!< incoming call is put on held in AG */ + ESP_HF_BTRH_STATUS_ACCEPTED, /*!< held incoming call is accepted in AG */ + ESP_HF_BTRH_STATUS_REJECTED, /*!< held incoming call is rejected in AG */ +} esp_hf_btrh_status_t; + +/// AT+BTRH response and hold action code +typedef enum { + ESP_HF_BTRH_CMD_HOLD = 0, /*!< put the incoming call on hold */ + ESP_HF_BTRH_CMD_ACCEPT = 1, /*!< accept a held incoming call */ + ESP_HF_BTRH_CMD_REJECT = 2, /*!< reject a held incoming call */ +} esp_hf_btrh_cmd_t; + +/* +NREC */ +typedef enum +{ + ESP_HF_NREC_STOP = 0, + ESP_HF_NREC_START +} esp_hf_nrec_t; + +///+CCWA resposne status +typedef enum { + ESP_HF_CALL_WAITING_INACTIVE, + ESP_HF_CALL_WAITING_ACTIVE, +} esp_hf_call_waiting_status_t; + +/* WBS codec setting */ +typedef enum +{ + ESP_HF_WBS_NONE, + ESP_HF_WBS_NO, + ESP_HF_WBS_YES +}esp_hf_wbs_config_t; + +/// Bluetooth HFP RFCOMM connection and service level connection status +typedef enum { + ESP_HF_CONNECTION_STATE_DISCONNECTED = 0, /*!< RFCOMM data link channel released */ + ESP_HF_CONNECTION_STATE_CONNECTING, /*!< connecting remote device on the RFCOMM data link*/ + ESP_HF_CONNECTION_STATE_CONNECTED, /*!< RFCOMM connection established */ + ESP_HF_CONNECTION_STATE_SLC_CONNECTED, /*!< service level connection established */ + ESP_HF_CONNECTION_STATE_DISCONNECTING, /*!< disconnecting with remote device on the RFCOMM data link*/ +} esp_hf_connection_state_t; + +/// AT+CHLD command values +typedef enum { + ESP_HF_CHLD_TYPE_REL = 0, /*!< <0>, Terminate all held or set UDUB("busy") to a waiting call */ + ESP_HF_CHLD_TYPE_REL_ACC, /*!< <1>, Terminate all active calls and accepts a waiting/held call */ + ESP_HF_CHLD_TYPE_HOLD_ACC, /*!< <2>, Hold all active calls and accepts a waiting/held call */ + ESP_HF_CHLD_TYPE_MERGE, /*!< <3>, Add all held calls to a conference */ + ESP_HF_CHLD_TYPE_MERGE_DETACH, /*!< <4>, connect the two calls and disconnects the subscriber from both calls */ + ESP_HF_CHLD_TYPE_REL_X, /*!< <1x>, releases specified calls only */ + ESP_HF_CHLD_TYPE_PRIV_X, /*!< <2x>, request private consultation mode with specified call */ +} esp_hf_chld_type_t; + +/* AT response code - OK/Error */ +typedef enum { + ESP_HF_AT_RESPONSE_CODE_OK = 0, /*!< acknowledges execution of a command line */ + ESP_HF_AT_RESPONSE_CODE_ERR, /*!< command not accepted */ + ESP_HF_AT_RESPONSE_CODE_NO_CARRIER, /*!< connection terminated */ + ESP_HF_AT_RESPONSE_CODE_BUSY, /*!< busy signal detected */ + ESP_HF_AT_RESPONSE_CODE_NO_ANSWER, /*!< connection completion timeout */ + ESP_HF_AT_RESPONSE_CODE_DELAYED, /*!< delayed */ + ESP_HF_AT_RESPONSE_CODE_BLACKLISTED, /*!< blacklisted */ + ESP_HF_AT_RESPONSE_CODE_CME, /*!< CME error */ +} esp_hf_at_response_code_t; + +/* AT response code - OK/Error */ +typedef enum { + ESP_HF_AT_RESPONSE_ERROR = 0, + ESP_HF_AT_RESPONSE_OK +} esp_hf_at_response_t; + +/// Extended Audio Gateway Error Result Code Response +typedef enum { + ESP_HF_CME_AG_FAILURE = 0, /*!< ag failure */ + ESP_HF_CME_NO_CONNECTION_TO_PHONE = 1, /*!< no connection to phone */ + ESP_HF_CME_OPERATION_NOT_ALLOWED = 3, /*!< operation not allowed */ + ESP_HF_CME_OPERATION_NOT_SUPPORTED = 4, /*!< operation not supported */ + ESP_HF_CME_PH_SIM_PIN_REQUIRED = 5, /*!< PH-SIM PIN Required */ + ESP_HF_CME_SIM_NOT_INSERTED = 10, /*!< SIM not inserted */ + ESP_HF_CME_SIM_PIN_REQUIRED = 11, /*!< SIM PIN required */ + ESP_HF_CME_SIM_PUK_REQUIRED = 12, /*!< SIM PUK required */ + ESP_HF_CME_SIM_FAILURE = 13, /*!< SIM failure */ + ESP_HF_CME_SIM_BUSY = 14, /*!< SIM busy */ + ESP_HF_CME_INCORRECT_PASSWORD = 16, /*!< incorrect password */ + ESP_HF_CME_SIM_PIN2_REQUIRED = 17, /*!< SIM PIN2 required */ + ESP_HF_CME_SIM_PUK2_REQUIRED = 18, /*!< SIM PUK2 required */ + ESP_HF_CME_MEMEORY_FULL = 20, /*!< memory full */ + ESP_HF_CME_INVALID_INDEX = 21, /*!< invalid index */ + ESP_HF_CME_MEMEORY_FAILURE = 23, /*!< memory failure */ + ESP_HF_CME_TEXT_STRING_TOO_LONG = 24, /*!< test string too long */ + ESP_HF_CME_INVALID_CHARACTERS_IN_TEXT_STRING = 25, /*!< invalid characters in text string */ + ESP_HF_CME_DIAL_STRING_TOO_LONG = 26, /*!< dial string too long*/ + ESP_HF_CME_INVALID_CHARACTERS_IN_DIAL_STRING = 27, /*!< invalid characters in dial string */ + ESP_HF_CME_NO_NETWORK_SERVICE = 30, /*!< no network service */ + ESP_HF_CME_NETWORK_TIMEOUT = 31, /*!< network timeout */ + ESP_HF_CME_NETWORK_NOT_ALLOWED = 32, /*!< network not allowed --emergency calls only */ +} esp_hf_cme_err_t; + +/** Callback for connection state change. + * state will have one of the values from BtHfConnectionState + */ +typedef void (* esp_hf_connection_state_callback)(esp_hf_connection_state_t state, esp_bd_addr_t *bd_addr); + +/** Callback for audio connection state change. + * state will have one of the values from BtHfAudioState + */ +typedef void (* esp_hf_audio_state_callback)(esp_hf_audio_state_t state, esp_bd_addr_t *bd_addr); + +/** Callback for VR connection state change. + * state will have one of the values from BtHfVRState + */ +typedef void (* esp_hf_vr_cmd_callback)(esp_hf_vr_state_t state, esp_bd_addr_t *bd_addr); + +/** Callback for answer incoming call (ATA) + */ +typedef void (* esp_hf_answer_call_cmd_callback)(esp_bd_addr_t *bd_addr); + +/** Callback for disconnect call (AT+CHUP) + */ +typedef void (* esp_hf_hangup_call_cmd_callback)(esp_bd_addr_t *bd_addr); + +/** Callback for disconnect call (AT+CHUP) + * type will denote Speaker/Mic gain (BtHfVolumeControl). + */ +typedef void (* esp_hf_volume_cmd_callback)(esp_hf_volume_control_target_t type, int volume, esp_bd_addr_t *bd_addr); + +/** Callback for dialing an outgoing call + * If number is NULL, redial + */ +typedef void (* esp_hf_dial_call_cmd_callback)(char *number, esp_bd_addr_t *bd_addr); + +/** Callback for sending DTMF tones + * tone contains the dtmf character to be sent + */ +typedef void (* esp_hf_dtmf_cmd_callback)(char tone, esp_bd_addr_t *bd_addr); + +/** Callback for enabling/disabling noise reduction/echo cancellation + * value will be 1 to enable, 0 to disable + */ +typedef void (* esp_hf_nrec_cmd_callback)(esp_hf_nrec_t nrec, esp_bd_addr_t *bd_addr); + +/** Callback for AT+BCS and event from BAC + * WBS enable, WBS disable + */ +typedef void (* esp_hf_wbs_callback)(esp_hf_wbs_config_t wbs, esp_bd_addr_t *bd_addr); + +/** Callback for call hold handling (AT+CHLD) + * value will contain the call hold command (0, 1, 2, 3) + */ +typedef void (* esp_hf_chld_cmd_callback)(esp_hf_chld_type_t chld, esp_bd_addr_t *bd_addr); + +/** Callback for CNUM (subscriber number) + */ +typedef void (* esp_hf_cnum_cmd_callback)(esp_bd_addr_t *bd_addr); + +/** Callback for indicators (CIND) + */ +typedef void (* esp_hf_cind_cmd_callback)(esp_bd_addr_t *bd_addr); + +/** Callback for operator selection (COPS) + */ +typedef void (* esp_hf_cops_cmd_callback)(esp_bd_addr_t *bd_addr); + +/** Callback for call list (AT+CLCC) + */ +typedef void (* esp_hf_clcc_cmd_callback) (esp_bd_addr_t *bd_addr); + +/** Callback for unknown AT command recd from AG + * at_string will contain the unparsed AT string + */ +typedef void (* esp_hf_unknown_at_cmd_callback)(char *at_string, esp_bd_addr_t *bd_addr); + +/** Callback for keypressed (HSP) event. + */ +typedef void (* esp_hf_key_pressed_cmd_callback)(esp_bd_addr_t *bd_addr); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_HF_DEFS_H__ */ diff --git a/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_spp_api.h b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_spp_api.h new file mode 100644 index 00000000..9df1e58a --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/host/bluedroid/api/include/api/esp_spp_api.h @@ -0,0 +1,372 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_SPP_API_H__ +#define __ESP_SPP_API_H__ + +#include "esp_err.h" +#include "esp_bt_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ESP_SPP_SUCCESS = 0, /*!< Successful operation. */ + ESP_SPP_FAILURE, /*!< Generic failure. */ + ESP_SPP_BUSY, /*!< Temporarily can not handle this request. */ + ESP_SPP_NO_DATA, /*!< No data */ + ESP_SPP_NO_RESOURCE, /*!< No more resource */ + ESP_SPP_NEED_INIT, /*!< SPP module shall init first */ + ESP_SPP_NEED_DEINIT, /*!< SPP module shall deinit first */ + ESP_SPP_NO_CONNECTION, /*!< Connection may have been closed */ + ESP_SPP_NO_SERVER, /*!< No SPP server */ +} esp_spp_status_t; + +/* Security Setting Mask +Use these three mask mode: +1. ESP_SPP_SEC_NONE +2. ESP_SPP_SEC_AUTHENTICATE +3. (ESP_SPP_SEC_ENCRYPT|ESP_SPP_SEC_AUTHENTICATE) +*/ +#define ESP_SPP_SEC_NONE 0x0000 /*!< No security. relate to BTA_SEC_NONE in bta/bta_api.h */ +#define ESP_SPP_SEC_AUTHORIZE 0x0001 /*!< Authorization required (only needed for out going connection ) relate to BTA_SEC_AUTHORIZE in bta/bta_api.h*/ +#define ESP_SPP_SEC_AUTHENTICATE 0x0012 /*!< Authentication required. relate to BTA_SEC_AUTHENTICATE in bta/bta_api.h*/ +#define ESP_SPP_SEC_ENCRYPT 0x0024 /*!< Encryption required. relate to BTA_SEC_ENCRYPT in bta/bta_api.h*/ +#define ESP_SPP_SEC_MODE4_LEVEL4 0x0040 /*!< Mode 4 level 4 service, i.e. incoming/outgoing MITM and P-256 encryption relate to BTA_SEC_MODE4_LEVEL4 in bta/bta_api.h*/ +#define ESP_SPP_SEC_MITM 0x3000 /*!< Man-In-The_Middle protection relate to BTA_SEC_MITM in bta/bta_api.h*/ +#define ESP_SPP_SEC_IN_16_DIGITS 0x4000 /*!< Min 16 digit for pin code relate to BTA_SEC_IN_16_DIGITS in bta/bta_api.h*/ +typedef uint16_t esp_spp_sec_t; + +typedef enum { + ESP_SPP_ROLE_MASTER = 0, /*!< Role: master */ + ESP_SPP_ROLE_SLAVE = 1, /*!< Role: slave */ +} esp_spp_role_t; + +typedef enum { + ESP_SPP_MODE_CB = 0, /*!< When data is coming, a callback will come with data */ + ESP_SPP_MODE_VFS = 1, /*!< Use VFS to write/read data */ +} esp_spp_mode_t; + +#define ESP_SPP_MAX_MTU (3*330) /*!< SPP max MTU */ +#define ESP_SPP_MAX_SCN 31 /*!< SPP max SCN */ +/** + * @brief SPP callback function events + */ +typedef enum { + ESP_SPP_INIT_EVT = 0, /*!< When SPP is inited, the event comes */ + ESP_SPP_UNINIT_EVT = 1, /*!< When SPP is uninited, the event comes */ + ESP_SPP_DISCOVERY_COMP_EVT = 8, /*!< When SDP discovery complete, the event comes */ + ESP_SPP_OPEN_EVT = 26, /*!< When SPP Client connection open, the event comes */ + ESP_SPP_CLOSE_EVT = 27, /*!< When SPP connection closed, the event comes */ + ESP_SPP_START_EVT = 28, /*!< When SPP server started, the event comes */ + ESP_SPP_CL_INIT_EVT = 29, /*!< When SPP client initiated a connection, the event comes */ + ESP_SPP_DATA_IND_EVT = 30, /*!< When SPP connection received data, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_CONG_EVT = 31, /*!< When SPP connection congestion status changed, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_WRITE_EVT = 33, /*!< When SPP write operation completes, the event comes, only for ESP_SPP_MODE_CB */ + ESP_SPP_SRV_OPEN_EVT = 34, /*!< When SPP Server connection open, the event comes */ + ESP_SPP_SRV_STOP_EVT = 35, /*!< When SPP server stopped, the event comes */ +} esp_spp_cb_event_t; + + +/** + * @brief SPP callback parameters union + */ +typedef union { + /** + * @brief SPP_INIT_EVT + */ + struct spp_init_evt_param { + esp_spp_status_t status; /*!< status */ + } init; /*!< SPP callback param of SPP_INIT_EVT */ + + /** + * @brief SPP_UNINIT_EVT + */ + struct spp_uninit_evt_param { + esp_spp_status_t status; /*!< status */ + } uninit; /*!< SPP callback param of SPP_UNINIT_EVT */ + + /** + * @brief SPP_DISCOVERY_COMP_EVT + */ + struct spp_discovery_comp_evt_param { + esp_spp_status_t status; /*!< status */ + uint8_t scn_num; /*!< The num of scn_num */ + uint8_t scn[ESP_SPP_MAX_SCN]; /*!< channel # */ + const char *service_name[ESP_SPP_MAX_SCN]; /*!< service_name */ + } disc_comp; /*!< SPP callback param of SPP_DISCOVERY_COMP_EVT */ + + /** + * @brief ESP_SPP_OPEN_EVT + */ + struct spp_open_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ + esp_bd_addr_t rem_bda; /*!< The peer address */ + } open; /*!< SPP callback param of ESP_SPP_OPEN_EVT */ + + /** + * @brief ESP_SPP_SRV_OPEN_EVT + */ + struct spp_srv_open_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + uint32_t new_listen_handle; /*!< The new listen handle */ + int fd; /*!< The file descriptor only for ESP_SPP_MODE_VFS */ + esp_bd_addr_t rem_bda; /*!< The peer address */ + } srv_open; /*!< SPP callback param of ESP_SPP_SRV_OPEN_EVT */ + /** + * @brief ESP_SPP_CLOSE_EVT + */ + struct spp_close_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t port_status; /*!< PORT status */ + uint32_t handle; /*!< The connection handle */ + bool async; /*!< FALSE, if local initiates disconnect */ + } close; /*!< SPP callback param of ESP_SPP_CLOSE_EVT */ + + /** + * @brief ESP_SPP_START_EVT + */ + struct spp_start_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + uint8_t sec_id; /*!< security ID used by this server */ + uint8_t scn; /*!< Server channel number */ + bool use_co; /*!< TRUE to use co_rfc_data */ + } start; /*!< SPP callback param of ESP_SPP_START_EVT */ + + /** + * @brief ESP_SPP_SRV_STOP_EVT + */ + struct spp_srv_stop_evt_param { + esp_spp_status_t status; /*!< status */ + uint8_t scn; /*!< Server channel number */ + } srv_stop; /*!< SPP callback param of ESP_SPP_SRV_STOP_EVT */ + + /** + * @brief ESP_SPP_CL_INIT_EVT + */ + struct spp_cl_init_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + uint8_t sec_id; /*!< security ID used by this server */ + bool use_co; /*!< TRUE to use co_rfc_data */ + } cl_init; /*!< SPP callback param of ESP_SPP_CL_INIT_EVT */ + + /** + * @brief ESP_SPP_WRITE_EVT + */ + struct spp_write_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + int len; /*!< The length of the data written. */ + bool cong; /*!< congestion status */ + } write; /*!< SPP callback param of ESP_SPP_WRITE_EVT */ + + /** + * @brief ESP_SPP_DATA_IND_EVT + */ + struct spp_data_ind_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + uint16_t len; /*!< The length of data */ + uint8_t *data; /*!< The data received */ + } data_ind; /*!< SPP callback param of ESP_SPP_DATA_IND_EVT */ + + /** + * @brief ESP_SPP_CONG_EVT + */ + struct spp_cong_evt_param { + esp_spp_status_t status; /*!< status */ + uint32_t handle; /*!< The connection handle */ + bool cong; /*!< TRUE, congested. FALSE, uncongested */ + } cong; /*!< SPP callback param of ESP_SPP_CONG_EVT */ +} esp_spp_cb_param_t; /*!< SPP callback parameter union type */ + +/** + * @brief SPP callback function type. + * When handle ESP_SPP_DATA_IND_EVT, it is strongly recommended to cache incoming data, and process them in + * other lower priority application task rather than in this callback directly. + * + * @param event: Event type + * @param param: Point to callback parameter, currently is union type + */ +typedef void (esp_spp_cb_t)(esp_spp_cb_event_t event, esp_spp_cb_param_t *param); + +/** + * @brief This function is called to init callbacks with SPP module. + * + * @param[in] callback: pointer to the init callback function. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_register_callback(esp_spp_cb_t callback); + +/** + * @brief This function is called to init SPP module. + * When the operation is completed, the callback function will be called with ESP_SPP_INIT_EVT. + * This function should be called after esp_bluedroid_enable() completes successfully. + * + * @param[in] mode: Choose the mode of SPP, ESP_SPP_MODE_CB or ESP_SPP_MODE_VFS. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_init(esp_spp_mode_t mode); + +/** + * @brief This function is called to uninit SPP module. + * The operation will close all active SPP connection first, then the callback function will be called + * with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. + * When the operation is completed, the callback function will be called with ESP_SPP_UNINIT_EVT. + * This function should be called after esp_spp_init() completes successfully. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_deinit(void); + + +/** + * @brief This function is called to performs service discovery for the services provided by the given peer device. + * When the operation is completed, the callback function will be called with ESP_SPP_DISCOVERY_COMP_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @param[in] bd_addr: Remote device bluetooth device address. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_start_discovery(esp_bd_addr_t bd_addr); + +/** + * @brief This function makes an SPP connection to a remote BD Address. + * When the connection is initiated or failed to initiate, the callback is called with ESP_SPP_CL_INIT_EVT. + * When the connection is established or failed, the callback is called with ESP_SPP_OPEN_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @param[in] sec_mask: Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. + * @param[in] role: Master or slave. + * @param[in] remote_scn: Remote device bluetooth device SCN. + * @param[in] peer_bd_addr: Remote device bluetooth device address. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_connect(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t remote_scn, esp_bd_addr_t peer_bd_addr); + +/** + * @brief This function closes an SPP connection. + * When the operation is completed, the callback function will be called with ESP_SPP_CLOSE_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @param[in] handle: The connection handle. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_disconnect(uint32_t handle); + +/** + * @brief This function create a SPP server and starts listening for an + * SPP connection request from a remote Bluetooth device. + * When the server is started successfully, the callback is called with ESP_SPP_START_EVT. + * When the connection is established, the callback is called with ESP_SPP_SRV_OPEN_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @param[in] sec_mask: Security Setting Mask. Suggest to use ESP_SPP_SEC_NONE, ESP_SPP_SEC_AUTHORIZE or ESP_SPP_SEC_AUTHENTICATE only. + * @param[in] role: Master or slave. + * @param[in] local_scn: The specific channel you want to get. + * If channel is 0, means get any channel. + * @param[in] name: Server's name. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_start_srv(esp_spp_sec_t sec_mask, esp_spp_role_t role, uint8_t local_scn, const char *name); + +/** + * @brief This function stops all SPP servers. + * The operation will close all active SPP connection first, then the callback function will be called + * with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. + * When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @return + * - ESP_OK: success + * - other: failed + */ + +esp_err_t esp_spp_stop_srv(void); + +/** + * @brief This function stops a specific SPP server. + * The operation will close all active SPP connection first on the specific SPP server, then the callback function will be called + * with ESP_SPP_CLOSE_EVT, and the number of ESP_SPP_CLOSE_EVT is equal to the number of connection. + * When the operation is completed, the callback is called with ESP_SPP_SRV_STOP_EVT. + * This funciton must be called after esp_spp_init() successful and before esp_spp_deinit(). + * + * @param[in] scn: Server channel number. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_stop_srv_scn(uint8_t scn); + +/** + * @brief This function is used to write data, only for ESP_SPP_MODE_CB. + * When this function need to be called repeatedly, it is strongly recommended to call this function again after + * the previous event ESP_SPP_WRITE_EVT is received and the parameter 'cong' is equal to false. If the previous event + * ESP_SPP_WRITE_EVT with parameter 'cong' is equal to true, the function can only be called again when the event + * ESP_SPP_CONG_EVT with parameter 'cong' equal to false is received. + * This funciton must be called after an connection between initiator and acceptor has been established. + * + * @param[in] handle: The connection handle. + * @param[in] len: The length of the data written. + * @param[in] p_data: The data written. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_write(uint32_t handle, int len, uint8_t *p_data); + + +/** + * @brief This function is used to register VFS. + * For now, SPP only supports write, read and close. + * + * @return + * - ESP_OK: success + * - other: failed + */ +esp_err_t esp_spp_vfs_register(void); + +#ifdef __cplusplus +} +#endif + +#endif ///__ESP_SPP_API_H__ diff --git a/tools/sdk/esp32c3/include/bt/include/esp32c3/include/esp_bt.h b/tools/sdk/esp32c3/include/bt/include/esp32c3/include/esp_bt.h new file mode 100644 index 00000000..7a33d605 --- /dev/null +++ b/tools/sdk/esp32c3/include/bt/include/esp32c3/include/esp_bt.h @@ -0,0 +1,513 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_BT_H__ +#define __ESP_BT_H__ + +#include +#include +#include "esp_err.h" +#include "sdkconfig.h" +#include "esp_task.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_BT_CTRL_CONFIG_MAGIC_VAL 0x5A5AA5A5 +#define ESP_BT_CTRL_CONFIG_VERSION 0x02103080 + +#define ESP_BT_HCI_TL_MAGIC_VALUE 0xfadebead +#define ESP_BT_HCI_TL_VERSION 0x00010000 + +/** + * @brief Bluetooth mode for controller enable/disable + */ +typedef enum { + ESP_BT_MODE_IDLE = 0x00, /*!< Bluetooth is not running */ + ESP_BT_MODE_BLE = 0x01, /*!< Run BLE mode */ + ESP_BT_MODE_CLASSIC_BT = 0x02, /*!< Run Classic BT mode */ + ESP_BT_MODE_BTDM = 0x03, /*!< Run dual mode */ +} esp_bt_mode_t; + +/** + * @brief Type of controller HCI transport layer + */ +typedef enum { + ESP_BT_CTRL_HCI_TL_UART = 0, /*!< HCI UART h4 transport layer */ + ESP_BT_CTRL_HCI_TL_VHCI = 1, /*!< VHCI interface */ +} esp_bt_ctrl_hci_tl_t; + +/** + * @breif type of BLE connection event length computation + */ +typedef enum { + ESP_BLE_CE_LEN_TYPE_ORIG = 0, /*!< original */ + ESP_BLE_CE_LEN_TYPE_CE = 1, /*!< use CE_LEN parameter from HCI commands */ + ESP_BLE_CE_LEN_TYPE_SD = 1, /*!< Espressif vendor defined */ +} esp_ble_ce_len_t; + +/** + * @brief Bluetooth sleep mode + */ +typedef enum { + ESP_BT_SLEEP_MODE_NONE = 0, /*!< Bluetooth sleep mode disabled */ + ESP_BT_SLEEP_MODE_1 = 1, /*!< Bluetooth sleep mode 1 */ +} esp_bt_sleep_mode_t; + +/** + * @brief Bluetooth sleep clock + */ +typedef enum { + ESP_BT_SLEEP_CLOCK_NONE = 0, /*!< Sleep clock not configured */ + ESP_BT_SLEEP_CLOCK_MAIN_XTAL = 1, /*!< SoC main crystal */ + ESP_BT_SLEEP_CLOCK_EXT_32K_XTAL = 2, /*!< External 32.768kHz crystal */ + ESP_BT_SLEEP_CLOCK_RTC_SLOW = 3, /*!< Internal 150kHz RC oscillator */ + ESP_BT_SLEEP_CLOCK_FPGA_32K = 4, /*!< Hardwired 32KHz clock temporarily used for FPGA */ +} esp_bt_sleep_clock_t; + +/** + * @brief antenna index used for bluetooth + */ +enum { + ESP_BT_ANT_IDX_0 = 0, /*!< anntena NO 0 */ + ESP_BT_ANT_IDX_1 = 1, /*!< anntena NO 1 */ +}; + +/** + * @brief Maximum Tx/Rx time limit on Coded-PHY connection + */ +enum { + ESP_BT_COEX_PHY_CODED_TX_RX_TIME_LIMIT_FORCE_DISABLE = 0, /*!< Disable the limit */ + ESP_BT_COEX_PHY_CODED_TX_RX_TIME_LIMIT_FORCE_ENABLE, /*!< Always Enable the limit */ +}; + +#ifdef CONFIG_BT_ENABLED + +#define BT_CTRL_BLE_MAX_ACT_LIMIT 10 //Maximum BLE activity limitation + +#ifdef CONFIG_BT_CTRL_SCAN_DUPL_TYPE +#define SCAN_DUPLICATE_TYPE_VALUE CONFIG_BT_CTRL_SCAN_DUPL_TYPE +#else +#define SCAN_DUPLICATE_TYPE_VALUE 0 +#endif + +/* normal adv cache size */ +#ifdef CONFIG_BT_CTRL_SCAN_DUPL_CACHE_SIZE +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE CONFIG_BT_CTRL_SCAN_DUPL_CACHE_SIZE +#else +#define NORMAL_SCAN_DUPLICATE_CACHE_SIZE 20 +#endif + +#ifndef CONFIG_BT_CTRL_BLE_MESH_SCAN_DUPL_EN +#define CONFIG_BT_CTRL_BLE_MESH_SCAN_DUPL_EN FALSE +#endif + +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY 0 +#define SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV 1 + +#if CONFIG_BT_CTRL_BLE_MESH_SCAN_DUPL_EN + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_MESH_ADV + #ifdef CONFIG_BT_CTRL_MESH_DUPL_SCAN_CACHE_SIZE + #define MESH_DUPLICATE_SCAN_CACHE_SIZE CONFIG_BT_CTRL_MESH_DUPL_SCAN_CACHE_SIZE + #else + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 50 + #endif +#else + #define SCAN_DUPLICATE_MODE SCAN_DUPLICATE_MODE_NORMAL_ADV_ONLY + #define MESH_DUPLICATE_SCAN_CACHE_SIZE 0 +#endif + +#define CFG_MASK_BIT_SCAN_DUPLICATE_OPTION (1<<0) + +#define CFG_NASK CFG_MASK_BIT_SCAN_DUPLICATE_OPTION + +#define BLE_HW_TARGET_CODE_ESP32C3_CHIP_ECO0 (0x01010000) + +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() { \ + .magic = ESP_BT_CTRL_CONFIG_MAGIC_VAL, \ + .version = ESP_BT_CTRL_CONFIG_VERSION, \ + .controller_task_stack_size = ESP_TASK_BT_CONTROLLER_STACK, \ + .controller_task_prio = ESP_TASK_BT_CONTROLLER_PRIO, \ + .controller_task_run_cpu = CONFIG_BT_CTRL_PINNED_TO_CORE, \ + .bluetooth_mode = CONFIG_BT_CTRL_MODE_EFF, \ + .ble_max_act = CONFIG_BT_CTRL_BLE_MAX_ACT_EFF, \ + .sleep_mode = CONFIG_BT_CTRL_SLEEP_MODE_EFF, \ + .sleep_clock = CONFIG_BT_CTRL_SLEEP_CLOCK_EFF, \ + .ble_st_acl_tx_buf_nb = CONFIG_BT_CTRL_BLE_STATIC_ACL_TX_BUF_NB, \ + .ble_hw_cca_check = CONFIG_BT_CTRL_HW_CCA_EFF, \ + .ble_adv_dup_filt_max = CONFIG_BT_CTRL_ADV_DUP_FILT_MAX, \ + .ce_len_type = CONFIG_BT_CTRL_CE_LENGTH_TYPE_EFF, \ + .hci_tl_type = CONFIG_BT_CTRL_HCI_TL_EFF, \ + .hci_tl_funcs = NULL, \ + .txant_dft = CONFIG_BT_CTRL_TX_ANTENNA_INDEX_EFF, \ + .rxant_dft = CONFIG_BT_CTRL_RX_ANTENNA_INDEX_EFF, \ + .txpwr_dft = CONFIG_BT_CTRL_DFT_TX_POWER_LEVEL_EFF, \ + .cfg_mask = CFG_NASK, \ + .scan_duplicate_mode = SCAN_DUPLICATE_MODE, \ + .scan_duplicate_type = SCAN_DUPLICATE_TYPE_VALUE, \ + .normal_adv_size = NORMAL_SCAN_DUPLICATE_CACHE_SIZE, \ + .mesh_adv_size = MESH_DUPLICATE_SCAN_CACHE_SIZE, \ + .coex_phy_coded_tx_rx_time_limit = CONFIG_BT_CTRL_COEX_PHY_CODED_TX_RX_TLIM_EFF, \ + .hw_target_code = BLE_HW_TARGET_CODE_ESP32C3_CHIP_ECO0, \ +}; + +#else +#define BT_CONTROLLER_INIT_CONFIG_DEFAULT() {0}; _Static_assert(0, "please enable bluetooth in menuconfig to use bt.h"); +#endif + +/** + * @brief Controller HCI transport layer function structure + * This structure shall be registered when HCI transport layer is UART + */ +typedef struct { + uint32_t _magic; /* Magic number */ + uint32_t _version; /* version number of the defined structure */ + uint32_t _reserved; /* reserved for future use */ + int (* _open)(void); /* hci tl open */ + void (* _close)(void); /* hci tl close */ + void (* _finish_transfers)(void); /* hci tl finish trasnfers */ + void (* _recv)(uint8_t *buf, uint32_t len, void (*callback) (void*, uint8_t), void* dummy); /* hci tl recv */ + void (* _send)(uint8_t *buf, uint32_t len, void (*callback) (void*, uint8_t), void* dummy); /* hci tl send */ + bool (* _flow_off)(void); /* hci tl flow off */ + void (* _flow_on)(void); /* hci tl flow on */ +} esp_bt_hci_tl_t; + +/** + * @brief Controller config options, depend on config mask. + * Config mask indicate which functions enabled, this means + * some options or parameters of some functions enabled by config mask. + */ +typedef struct { + /* + * Following parameters can not be configured runtime when call esp_bt_controller_init() + * They will be overwritten by constant values from menuconfig options or from macros. + * So, do not modify the value when esp_bt_controller_init() + */ + uint32_t magic; /*!< Magic number */ + uint32_t version; /*!< version number of the defined structure */ + /* + * Following parameters can be configured runtime, when call esp_bt_controller_init() + */ + uint16_t controller_task_stack_size; /*!< Bluetooth controller task stack size */ + uint8_t controller_task_prio; /*!< Bluetooth controller task priority */ + uint8_t controller_task_run_cpu; /*!< CPU num that Bluetooth controller task runs on */ + uint8_t bluetooth_mode; /*!< Controller mode: BR/EDR, BLE or Dual Mode */ + uint8_t ble_max_act; /*!< BLE maximum number of air activities */ + uint8_t sleep_mode; /*!< controller sleep mode */ + uint8_t sleep_clock; /*!< controller sleep clock */ + uint8_t ble_st_acl_tx_buf_nb; /*!< controller static ACL TX BUFFER number */ + uint8_t ble_hw_cca_check; /*!< controller hardware triggered CCA check */ + uint16_t ble_adv_dup_filt_max; /*!< maxinum number of duplicate scan filter */ + bool coex_param_en; /*!< deprecated */ + uint8_t ce_len_type; /*!< connection event length computation method */ + bool coex_use_hooks; /*!< deprecated */ + uint8_t hci_tl_type; /*!< HCI transport layer, UART, VHCI, etc */ + esp_bt_hci_tl_t *hci_tl_funcs; /*!< hci transport functions used, must be set when hci_tl_type is UART */ + uint8_t txant_dft; /*!< default Tx antenna */ + uint8_t rxant_dft; /*!< default Rx antenna */ + uint8_t txpwr_dft; /*!< default Tx power */ + uint32_t cfg_mask; + uint8_t scan_duplicate_mode; /*!< scan duplicate mode */ + uint8_t scan_duplicate_type; /*!< scan duplicate type */ + uint16_t normal_adv_size; /*!< Normal adv size for scan duplicate */ + uint16_t mesh_adv_size; /*!< Mesh adv size for scan duplicate */ + uint8_t coex_phy_coded_tx_rx_time_limit; /*!< limit on max tx/rx time in case of connection using CODED-PHY with Wi-Fi coexistence */ + uint32_t hw_target_code; /*!< hardware target */ +} esp_bt_controller_config_t; + +/** + * @brief Bluetooth controller enable/disable/initialised/de-initialised status + */ +typedef enum { + ESP_BT_CONTROLLER_STATUS_IDLE = 0, + ESP_BT_CONTROLLER_STATUS_INITED, + ESP_BT_CONTROLLER_STATUS_ENABLED, + ESP_BT_CONTROLLER_STATUS_NUM, +} esp_bt_controller_status_t; + +/** + * @brief BLE tx power type + * ESP_BLE_PWR_TYPE_CONN_HDL0-8: for each connection, and only be set after connection completed. + * when disconnect, the correspond TX power is not effected. + * ESP_BLE_PWR_TYPE_ADV : for advertising/scan response. + * ESP_BLE_PWR_TYPE_SCAN : for scan. + * ESP_BLE_PWR_TYPE_DEFAULT : if each connection's TX power is not set, it will use this default value. + * if neither in scan mode nor in adv mode, it will use this default value. + * If none of power type is set, system will use ESP_PWR_LVL_P3 as default for ADV/SCAN/CONN0-9. + */ +typedef enum { + ESP_BLE_PWR_TYPE_CONN_HDL0 = 0, /*!< For connection handle 0 */ + ESP_BLE_PWR_TYPE_CONN_HDL1 = 1, /*!< For connection handle 1 */ + ESP_BLE_PWR_TYPE_CONN_HDL2 = 2, /*!< For connection handle 2 */ + ESP_BLE_PWR_TYPE_CONN_HDL3 = 3, /*!< For connection handle 3 */ + ESP_BLE_PWR_TYPE_CONN_HDL4 = 4, /*!< For connection handle 4 */ + ESP_BLE_PWR_TYPE_CONN_HDL5 = 5, /*!< For connection handle 5 */ + ESP_BLE_PWR_TYPE_CONN_HDL6 = 6, /*!< For connection handle 6 */ + ESP_BLE_PWR_TYPE_CONN_HDL7 = 7, /*!< For connection handle 7 */ + ESP_BLE_PWR_TYPE_CONN_HDL8 = 8, /*!< For connection handle 8 */ + ESP_BLE_PWR_TYPE_ADV = 9, /*!< For advertising */ + ESP_BLE_PWR_TYPE_SCAN = 10, /*!< For scan */ + ESP_BLE_PWR_TYPE_DEFAULT = 11, /*!< For default, if not set other, it will use default value */ + ESP_BLE_PWR_TYPE_NUM = 12, /*!< TYPE numbers */ +} esp_ble_power_type_t; + +/** + * @brief Bluetooth TX power level(index), it's just a index corresponding to power(dbm). + */ +typedef enum { + ESP_PWR_LVL_N27 = 0, /*!< Corresponding to -27dbm */ + ESP_PWR_LVL_N24 = 1, /*!< Corresponding to -24dbm */ + ESP_PWR_LVL_N21 = 2, /*!< Corresponding to -21dbm */ + ESP_PWR_LVL_N18 = 3, /*!< Corresponding to -18dbm */ + ESP_PWR_LVL_N15 = 4, /*!< Corresponding to -15dbm */ + ESP_PWR_LVL_N12 = 5, /*!< Corresponding to -12dbm */ + ESP_PWR_LVL_N9 = 6, /*!< Corresponding to -9dbm */ + ESP_PWR_LVL_N6 = 7, /*!< Corresponding to -6dbm */ + ESP_PWR_LVL_N3 = 8, /*!< Corresponding to -3dbm */ + ESP_PWR_LVL_N0 = 9, /*!< Corresponding to 0dbm */ + ESP_PWR_LVL_P3 = 10, /*!< Corresponding to +3dbm */ + ESP_PWR_LVL_P6 = 11, /*!< Corresponding to +6dbm */ + ESP_PWR_LVL_P9 = 12, /*!< Corresponding to +9dbm */ + ESP_PWR_LVL_P12 = 13, /*!< Corresponding to +12dbm */ + ESP_PWR_LVL_P15 = 14, /*!< Corresponding to +15dbm */ + ESP_PWR_LVL_P18 = 15, /*!< Corresponding to +18dbm */ + ESP_PWR_LVL_INVALID = 0xFF, /*!< Indicates an invalid value */ +} esp_power_level_t; + +/** + * @brief Set BLE TX power + * Connection Tx power should only be set after connection created. + * @param power_type : The type of which tx power, could set Advertising/Connection/Default and etc + * @param power_level: Power level(index) corresponding to absolute value(dbm) + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_ble_tx_power_set(esp_ble_power_type_t power_type, esp_power_level_t power_level); + +/** + * @brief Get BLE TX power + * Connection Tx power should only be get after connection created. + * @param power_type : The type of which tx power, could set Advertising/Connection/Default and etc + * @return >= 0 - Power level, < 0 - Invalid + */ +esp_power_level_t esp_ble_tx_power_get(esp_ble_power_type_t power_type); + +/** + * @brief Initialize BT controller to allocate task and other resource. + * This function should be called only once, before any other BT functions are called. + * @param cfg: Initial configuration of BT controller. Different from previous version, there's a mode and some + * connection configuration in "cfg" to configure controller work mode and allocate the resource which is needed. + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_controller_init(esp_bt_controller_config_t *cfg); + +/** + * @brief De-initialize BT controller to free resource and delete task. + * + * This function should be called only once, after any other BT functions are called. + * This function is not whole completed, esp_bt_controller_init cannot called after this function. + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_controller_deinit(void); + +/** + * @brief Enable BT controller. + * Due to a known issue, you cannot call esp_bt_controller_enable() a second time + * to change the controller mode dynamically. To change controller mode, call + * esp_bt_controller_disable() and then call esp_bt_controller_enable() with the new mode. + * @param mode : the mode(BLE/BT/BTDM) to enable. For compatible of API, retain this argument. This mode must be + * equal as the mode in "cfg" of esp_bt_controller_init(). + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_controller_enable(esp_bt_mode_t mode); + +/** + * @brief Disable BT controller + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_controller_disable(void); + +/** + * @brief Get BT controller is initialised/de-initialised/enabled/disabled + * @return status value + */ +esp_bt_controller_status_t esp_bt_controller_get_status(void); + +uint16_t esp_bt_get_tx_buf_num(void); + +/** @brief esp_vhci_host_callback + * used for vhci call host function to notify what host need to do + */ +typedef struct esp_vhci_host_callback { + void (*notify_host_send_available)(void); /*!< callback used to notify that the host can send packet to controller */ + int (*notify_host_recv)(uint8_t *data, uint16_t len); /*!< callback used to notify that the controller has a packet to send to the host*/ +} esp_vhci_host_callback_t; + +/** @brief esp_vhci_host_check_send_available + * used for check actively if the host can send packet to controller or not. + * @return true for ready to send, false means cannot send packet + */ +bool esp_vhci_host_check_send_available(void); + +/** @brief esp_vhci_host_send_packet + * host send packet to controller + * + * Should not call this function from within a critical section + * or when the scheduler is suspended. + * + * @param data the packet point + * @param len the packet length + */ +void esp_vhci_host_send_packet(uint8_t *data, uint16_t len); + +/** @brief esp_vhci_host_register_callback + * register the vhci reference callback + * struct defined by vhci_host_callback structure. + * @param callback esp_vhci_host_callback type variable + * @return ESP_OK - success, ESP_FAIL - failed + */ +esp_err_t esp_vhci_host_register_callback(const esp_vhci_host_callback_t *callback); + +/** @brief esp_bt_controller_mem_release + * release the controller memory as per the mode + * + * This function releases the BSS, data and other sections of the controller to heap. The total size is about 70k bytes. + * + * esp_bt_controller_mem_release(mode) should be called only before esp_bt_controller_init() + * or after esp_bt_controller_deinit(). + * + * Note that once BT controller memory is released, the process cannot be reversed. It means you cannot use the bluetooth + * mode which you have released by this function. + * + * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) + * then do not call this function. + * + * If the app calls esp_bt_controller_enable(ESP_BT_MODE_BLE) to use BLE only then it is safe to call + * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT) at initialization time to free unused BT Classic memory. + * + * If the mode is ESP_BT_MODE_BTDM, then it may be useful to call API esp_bt_mem_release(ESP_BT_MODE_BTDM) instead, + * which internally calls esp_bt_controller_mem_release(ESP_BT_MODE_BTDM) and additionally releases the BSS and data + * consumed by the BT/BLE host stack to heap. For more details about usage please refer to the documentation of + * esp_bt_mem_release() function + * + * @param mode : the mode want to release memory + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_controller_mem_release(esp_bt_mode_t mode); + +/** @brief esp_bt_mem_release + * release controller memory and BSS and data section of the BT/BLE host stack as per the mode + * + * This function first releases controller memory by internally calling esp_bt_controller_mem_release(). + * Additionally, if the mode is set to ESP_BT_MODE_BTDM, it also releases the BSS and data consumed by the BT/BLE host stack to heap + * + * Note that once BT memory is released, the process cannot be reversed. It means you cannot use the bluetooth + * mode which you have released by this function. + * + * If your firmware will later upgrade the Bluetooth controller mode (BLE -> BT Classic or disabled -> enabled) + * then do not call this function. + * + * If you never intend to use bluetooth in a current boot-up cycle, you can call esp_bt_mem_release(ESP_BT_MODE_BTDM) + * before esp_bt_controller_init or after esp_bt_controller_deinit. + * + * For example, if a user only uses bluetooth for setting the WiFi configuration, and does not use bluetooth in the rest of the product operation". + * In such cases, after receiving the WiFi configuration, you can disable/deinit bluetooth and release its memory. + * Below is the sequence of APIs to be called for such scenarios: + * + * esp_bluedroid_disable(); + * esp_bluedroid_deinit(); + * esp_bt_controller_disable(); + * esp_bt_controller_deinit(); + * esp_bt_mem_release(ESP_BT_MODE_BTDM); + * + * @param mode : the mode whose memory is to be released + * @return ESP_OK - success, other - failed + */ +esp_err_t esp_bt_mem_release(esp_bt_mode_t mode); + +/** + * @brief enable bluetooth to enter modem sleep + * + * Note that this function shall not be invoked before esp_bt_controller_enable() + * + * There are currently two options for bluetooth modem sleep, one is ORIG mode, and another is EVED Mode. EVED Mode is intended for BLE only. + * + * For ORIG mode: + * Bluetooth modem sleep is enabled in controller start up by default if CONFIG_BTDM_CONTROLLER_MODEM_SLEEP is set and "ORIG mode" is selected. In ORIG modem sleep mode, bluetooth controller will switch off some components and pause to work every now and then, if there is no event to process; and wakeup according to the scheduled interval and resume the work. It can also wakeup earlier upon external request using function "esp_bt_controller_wakeup_request". + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_bt_sleep_enable(void); + + +/** + * @brief disable bluetooth modem sleep + * + * Note that this function shall not be invoked before esp_bt_controller_enable() + * + * If esp_bt_sleep_disable() is called, bluetooth controller will not be allowed to enter modem sleep; + * + * If ORIG modem sleep mode is in use, if this function is called, bluetooth controller may not immediately wake up if it is dormant then. + * In this case, esp_bt_controller_wakeup_request() can be used to shorten the time for wakeup. + * + * @return + * - ESP_OK : success + * - other : failed + */ +esp_err_t esp_bt_sleep_disable(void); + +/** + * @brief to check whether bluetooth controller is sleeping at the instant, if modem sleep is enabled + * + * Note that this function shall not be invoked before esp_bt_controller_enable() + * This function is supposed to be used ORIG mode of modem sleep + * + * @return true if in modem sleep state, false otherwise + */ +bool esp_bt_controller_is_sleeping(void); + +/** + * @brief request controller to wakeup from sleeping state during sleep mode + * + * Note that this function shall not be invoked before esp_bt_controller_enable() + * Note that this function is supposed to be used ORIG mode of modem sleep + * Note that after this request, bluetooth controller may again enter sleep as long as the modem sleep is enabled + * + * Profiling shows that it takes several milliseconds to wakeup from modem sleep after this request. + * Generally it takes longer if 32kHz XTAL is used than the main XTAL, due to the lower frequency of the former as the bluetooth low power clock source. + */ +void esp_bt_controller_wakeup_request(void); + +/** + * @brief notify bluetooth controller task to process the event upon Tx or Rx done + * + * Note that this function shall not be invoked before esp_bt_controller_enable() + * This function can be called in both ISR and non-ISR context + * + */ +int esp_bt_h4tl_eif_io_event_notify(int event); + +/** + * @brief Get BT MAC address. + * @return Array pointer of length 6 storing MAC address value. + */ +uint8_t* esp_bt_get_mac(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_BT_H__ */ diff --git a/tools/sdk/esp32c3/include/cbor/port/include/cbor.h b/tools/sdk/esp32c3/include/cbor/port/include/cbor.h new file mode 100644 index 00000000..c8e6ccf4 --- /dev/null +++ b/tools/sdk/esp32c3/include/cbor/port/include/cbor.h @@ -0,0 +1,2 @@ +#include "../../tinycbor/src/cbor.h" +#include "../../tinycbor/src/cborjson.h" diff --git a/tools/sdk/esp32c3/include/cmock/CMock/src/cmock.h b/tools/sdk/esp32c3/include/cmock/CMock/src/cmock.h new file mode 100644 index 00000000..21123e92 --- /dev/null +++ b/tools/sdk/esp32c3/include/cmock/CMock/src/cmock.h @@ -0,0 +1,41 @@ +/* ========================================== + CMock Project - Automatic Mock Generation for C + Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef CMOCK_FRAMEWORK_H +#define CMOCK_FRAMEWORK_H + +#include "cmock_internals.h" + +#define CMOCK_VERSION_MAJOR 2 +#define CMOCK_VERSION_MINOR 5 +#define CMOCK_VERSION_BUILD 2 +#define CMOCK_VERSION ((CMOCK_VERSION_MAJOR << 16) | (CMOCK_VERSION_MINOR << 8) | CMOCK_VERSION_BUILD) + +/* should be big enough to index full range of CMOCK_MEM_MAX */ +#ifndef CMOCK_MEM_INDEX_TYPE +#include +#define CMOCK_MEM_INDEX_TYPE size_t +#endif + +#define CMOCK_GUTS_NONE (0) + +/*------------------------------------------------------- + * Memory API + *-------------------------------------------------------*/ +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNew(CMOCK_MEM_INDEX_TYPE size); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemChain(CMOCK_MEM_INDEX_TYPE root_index, CMOCK_MEM_INDEX_TYPE obj_index); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemNext(CMOCK_MEM_INDEX_TYPE previous_item_index); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemEndOfChain(CMOCK_MEM_INDEX_TYPE root_index); + +void* CMock_Guts_GetAddressFor(CMOCK_MEM_INDEX_TYPE index); + +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesCapacity(void); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesFree(void); +CMOCK_MEM_INDEX_TYPE CMock_Guts_MemBytesUsed(void); +void CMock_Guts_MemFreeAll(void); +void CMock_Guts_MemFreeFinal(void); + +#endif /* end of CMOCK_FRAMEWORK_H */ diff --git a/tools/sdk/esp32c3/include/cmock/CMock/src/cmock_internals.h b/tools/sdk/esp32c3/include/cmock/CMock/src/cmock_internals.h new file mode 100644 index 00000000..56fb33b1 --- /dev/null +++ b/tools/sdk/esp32c3/include/cmock/CMock/src/cmock_internals.h @@ -0,0 +1,91 @@ +/* ========================================== + CMock Project - Automatic Mock Generation for C + Copyright (c) 2007 Mike Karlesky, Mark VanderVoord, Greg Williams + [Released under MIT License. Please refer to license.txt for details] +========================================== */ + +#ifndef CMOCK_FRAMEWORK_INTERNALS_H +#define CMOCK_FRAMEWORK_INTERNALS_H + +#include "unity.h" + +/* These are constants that the generated mocks have access to */ +extern const char* CMockStringOutOfMemory; +extern const char* CMockStringCalledMore; +extern const char* CMockStringCalledLess; +extern const char* CMockStringCalledEarly; +extern const char* CMockStringCalledLate; +extern const char* CMockStringCallOrder; +extern const char* CMockStringIgnPreExp; +extern const char* CMockStringPtrPreExp; +extern const char* CMockStringPtrIsNULL; +extern const char* CMockStringExpNULL; +extern const char* CMockStringMismatch; + +/* define CMOCK_MEM_DYNAMIC to grab memory as needed with malloc + * when you do that, CMOCK_MEM_SIZE is used for incremental size instead of total */ +#ifdef CMOCK_MEM_STATIC +#undef CMOCK_MEM_DYNAMIC +#endif + +#ifdef CMOCK_MEM_DYNAMIC +#include +#endif + +/* this is used internally during pointer arithmetic. make sure this type is the same size as the target's pointer type */ +#ifndef CMOCK_MEM_PTR_AS_INT +#ifdef UNITY_POINTER_WIDTH +#ifdef UNITY_INT_WIDTH +#if UNITY_POINTER_WIDTH == UNITY_INT_WIDTH +#define CMOCK_MEM_PTR_AS_INT unsigned int +#endif +#endif +#endif +#endif + +#ifndef CMOCK_MEM_PTR_AS_INT +#ifdef UNITY_POINTER_WIDTH +#ifdef UNITY_LONG_WIDTH +#if UNITY_POINTER_WIDTH == UNITY_LONG_WIDTH +#define CMOCK_MEM_PTR_AS_INT unsigned long +#endif +#if UNITY_POINTER_WIDTH > UNITY_LONG_WIDTH +#define CMOCK_MEM_PTR_AS_INT unsigned long long +#endif +#endif +#endif +#endif + +#ifndef CMOCK_MEM_PTR_AS_INT +#define CMOCK_MEM_PTR_AS_INT unsigned long +#endif + +/* 0 for no alignment, 1 for 16-bit, 2 for 32-bit, 3 for 64-bit */ +#ifndef CMOCK_MEM_ALIGN + #ifdef UNITY_LONG_WIDTH + #if (UNITY_LONG_WIDTH == 16) + #define CMOCK_MEM_ALIGN (1) + #elif (UNITY_LONG_WIDTH == 32) + #define CMOCK_MEM_ALIGN (2) + #elif (UNITY_LONG_WIDTH == 64) + #define CMOCK_MEM_ALIGN (3) + #else + #define CMOCK_MEM_ALIGN (2) + #endif + #else + #define CMOCK_MEM_ALIGN (2) + #endif +#endif + +/* amount of memory to allow cmock to use in its internal heap */ +#ifndef CMOCK_MEM_SIZE +#define CMOCK_MEM_SIZE (32768) +#endif + +/* automatically calculated defs for easier reading */ +#define CMOCK_MEM_ALIGN_SIZE (CMOCK_MEM_INDEX_TYPE)(1u << CMOCK_MEM_ALIGN) +#define CMOCK_MEM_ALIGN_MASK (CMOCK_MEM_INDEX_TYPE)(CMOCK_MEM_ALIGN_SIZE - 1) +#define CMOCK_MEM_INDEX_SIZE (CMOCK_MEM_INDEX_TYPE)(CMOCK_MEM_PTR_AS_INT)((sizeof(CMOCK_MEM_INDEX_TYPE) > CMOCK_MEM_ALIGN_SIZE) ? sizeof(CMOCK_MEM_INDEX_TYPE) : CMOCK_MEM_ALIGN_SIZE) + + +#endif /* end of CMOCK_FRAMEWORK_INTERNALS_H */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/address.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/address.h new file mode 100644 index 00000000..a51236d5 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/address.h @@ -0,0 +1,177 @@ +/* + * address.h -- representation of network addresses + * + * Copyright (C) 2010-2011,2015-2016 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file address.h + * @brief Representation of network addresses + */ + +#ifndef COAP_ADDRESS_H_ +#define COAP_ADDRESS_H_ + +#include +#include +#include +#include +#include "libcoap.h" + +#if defined(WITH_LWIP) + +#include + +typedef struct coap_address_t { + uint16_t port; + ip_addr_t addr; +} coap_address_t; + +#define _coap_address_equals_impl(A, B) \ + ((A)->port == (B)->port \ + && (!!ip_addr_cmp(&(A)->addr,&(B)->addr))) + +#define _coap_address_isany_impl(A) ip_addr_isany(&(A)->addr) + +#define _coap_is_mcast_impl(Address) ip_addr_ismulticast(&(Address)->addr) + +#elif defined(WITH_CONTIKI) + +#include "uip.h" + +typedef struct coap_address_t { + uip_ipaddr_t addr; + uint16_t port; +} coap_address_t; + +#define _coap_address_equals_impl(A,B) \ + ((A)->port == (B)->port \ + && uip_ipaddr_cmp(&((A)->addr),&((B)->addr))) + +/** @todo implementation of _coap_address_isany_impl() for Contiki */ +#define _coap_address_isany_impl(A) 0 + +#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr)) + +#else /* WITH_LWIP || WITH_CONTIKI */ + + /** multi-purpose address abstraction */ +typedef struct coap_address_t { + socklen_t size; /**< size of addr */ + union { + struct sockaddr sa; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; + } addr; +} coap_address_t; + +/** + * Compares given address objects @p a and @p b. This function returns @c 1 if + * addresses are equal, @c 0 otherwise. The parameters @p a and @p b must not be + * @c NULL; + */ +int coap_address_equals(const coap_address_t *a, const coap_address_t *b); + +COAP_STATIC_INLINE int +_coap_address_isany_impl(const coap_address_t *a) { + /* need to compare only relevant parts of sockaddr_in6 */ + switch (a->addr.sa.sa_family) { + case AF_INET: + return a->addr.sin.sin_addr.s_addr == INADDR_ANY; + case AF_INET6: + return memcmp(&in6addr_any, + &a->addr.sin6.sin6_addr, + sizeof(in6addr_any)) == 0; + default: + ; + } + + return 0; +} +#endif /* WITH_LWIP || WITH_CONTIKI */ + +/** + * Resets the given coap_address_t object @p addr to its default values. In + * particular, the member size must be initialized to the available size for + * storing addresses. + * + * @param addr The coap_address_t object to initialize. + */ +COAP_STATIC_INLINE void +coap_address_init(coap_address_t *addr) { + assert(addr); + memset(addr, 0, sizeof(coap_address_t)); +#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) + /* lwip and Contiki have constant address sizes and doesn't need the .size part */ + addr->size = sizeof(addr->addr); +#endif +} + +/* Convenience function to copy IPv6 addresses without garbage. */ + +COAP_STATIC_INLINE void +coap_address_copy( coap_address_t *dst, const coap_address_t *src ) { +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) + memcpy( dst, src, sizeof( coap_address_t ) ); +#else + memset( dst, 0, sizeof( coap_address_t ) ); + dst->size = src->size; + if ( src->addr.sa.sa_family == AF_INET6 ) { + dst->addr.sin6.sin6_family = src->addr.sin6.sin6_family; + dst->addr.sin6.sin6_addr = src->addr.sin6.sin6_addr; + dst->addr.sin6.sin6_port = src->addr.sin6.sin6_port; + dst->addr.sin6.sin6_scope_id = src->addr.sin6.sin6_scope_id; + } else if ( src->addr.sa.sa_family == AF_INET ) { + dst->addr.sin = src->addr.sin; + } else { + memcpy( &dst->addr, &src->addr, src->size ); + } +#endif +} + +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) +/** + * Compares given address objects @p a and @p b. This function returns @c 1 if + * addresses are equal, @c 0 otherwise. The parameters @p a and @p b must not be + * @c NULL; + */ +COAP_STATIC_INLINE int +coap_address_equals(const coap_address_t *a, const coap_address_t *b) { + assert(a); assert(b); + return _coap_address_equals_impl(a, b); +} +#endif + +/** + * Checks if given address object @p a denotes the wildcard address. This + * function returns @c 1 if this is the case, @c 0 otherwise. The parameters @p + * a must not be @c NULL; + */ +COAP_STATIC_INLINE int +coap_address_isany(const coap_address_t *a) { + assert(a); + return _coap_address_isany_impl(a); +} + +#if !defined(WITH_LWIP) && !defined(WITH_CONTIKI) + +/** + * Checks if given address @p a denotes a multicast address. This function + * returns @c 1 if @p a is multicast, @c 0 otherwise. + */ +int coap_is_mcast(const coap_address_t *a); +#else /* !WITH_LWIP && !WITH_CONTIKI */ +/** + * Checks if given address @p a denotes a multicast address. This function + * returns @c 1 if @p a is multicast, @c 0 otherwise. + */ +COAP_STATIC_INLINE int +coap_is_mcast(const coap_address_t *a) { + return a && _coap_is_mcast_impl(a); +} +#endif /* !WITH_LWIP && !WITH_CONTIKI */ + +#endif /* COAP_ADDRESS_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/async.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/async.h new file mode 100644 index 00000000..e3999296 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/async.h @@ -0,0 +1,148 @@ +/* + * async.h -- state management for asynchronous messages + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file async.h + * @brief State management for asynchronous messages + */ + +#ifndef COAP_ASYNC_H_ +#define COAP_ASYNC_H_ + +#include "net.h" + +#ifndef WITHOUT_ASYNC + +/** + * @defgroup coap_async Asynchronous Messaging + * @{ + * Structure for managing asynchronous state of CoAP resources. A + * coap_resource_t object holds a list of coap_async_state_t objects that can be + * used to generate a separate response in case a result of an operation cannot + * be delivered in time, or the resource has been explicitly subscribed to with + * the option @c observe. + */ +typedef struct coap_async_state_t { + unsigned char flags; /**< holds the flags to control behaviour */ + + /** + * Holds the internal time when the object was registered with a + * resource. This field will be updated whenever + * coap_register_async() is called for a specific resource. + */ + coap_tick_t created; + + /** + * This field can be used to register opaque application data with the + * asynchronous state object. + */ + void *appdata; + coap_session_t *session; /**< transaction session */ + coap_tid_t id; /**< transaction id */ + struct coap_async_state_t *next; /**< internally used for linking */ + size_t tokenlen; /**< length of the token */ + uint8_t token[8]; /**< the token to use in a response */ +} coap_async_state_t; + +/* Definitions for Async Status Flags These flags can be used to control the + * behaviour of asynchronous response generation. + */ +#define COAP_ASYNC_CONFIRM 0x01 /**< send confirmable response */ +#define COAP_ASYNC_SEPARATE 0x02 /**< send separate response */ +#define COAP_ASYNC_OBSERVED 0x04 /**< the resource is being observed */ + +/** release application data on destruction */ +#define COAP_ASYNC_RELEASE_DATA 0x08 + +/** + * Allocates a new coap_async_state_t object and fills its fields according to + * the given @p request. The @p flags are used to control generation of empty + * ACK responses to stop retransmissions and to release registered @p data when + * the resource is deleted by coap_free_async(). This function returns a pointer + * to the registered coap_async_t object or @c NULL on error. Note that this + * function will return @c NULL in case that an object with the same identifier + * is already registered. + * + * @param context The context to use. + * @param session The session that is used for asynchronous transmissions. + * @param request The request that is handled asynchronously. + * @param flags Flags to control state management. + * @param data Opaque application data to register. Note that the + * storage occupied by @p data is released on destruction + * only if flag COAP_ASYNC_RELEASE_DATA is set. + * + * @return A pointer to the registered coap_async_state_t object or @c + * NULL in case of an error. + */ +coap_async_state_t * +coap_register_async(coap_context_t *context, + coap_session_t *session, + coap_pdu_t *request, + unsigned char flags, + void *data); + +/** + * Removes the state object identified by @p id from @p context. The removed + * object is returned in @p s, if found. Otherwise, @p s is undefined. This + * function returns @c 1 if the object was removed, @c 0 otherwise. Note that + * the storage allocated for the stored object is not released by this + * functions. You will have to call coap_free_async() to do so. + * + * @param context The context where the async object is registered. + * @param session The session that is used for asynchronous transmissions. + * @param id The identifier of the asynchronous transaction. + * @param s Will be set to the object identified by @p id after removal. + * + * @return @c 1 if object was removed and @p s updated, or @c 0 if no + * object was found with the given id. @p s is valid only if the + * return value is @c 1. + */ +int coap_remove_async(coap_context_t *context, + coap_session_t *session, + coap_tid_t id, + coap_async_state_t **s); + +/** + * Releases the memory that was allocated by coap_async_state_init() for the + * object @p s. The registered application data will be released automatically + * if COAP_ASYNC_RELEASE_DATA is set. + * + * @param state The object to delete. + */ +void +coap_free_async(coap_async_state_t *state); + +/** + * Retrieves the object identified by @p id from the list of asynchronous + * transactions that are registered with @p context. This function returns a + * pointer to that object or @c NULL if not found. + * + * @param context The context where the asynchronous objects are registered + * with. + * @param session The session that is used for asynchronous transmissions. + * @param id The id of the object to retrieve. + * + * @return A pointer to the object identified by @p id or @c NULL if + * not found. + */ +coap_async_state_t *coap_find_async(coap_context_t *context, coap_session_t *session, coap_tid_t id); + +/** + * Updates the time stamp of @p s. + * + * @param s The state object to update. + */ +COAP_STATIC_INLINE void +coap_touch_async(coap_async_state_t *s) { coap_ticks(&s->created); } + +/** @} */ + +#endif /* WITHOUT_ASYNC */ + +#endif /* COAP_ASYNC_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/bits.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/bits.h new file mode 100644 index 00000000..3b187148 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/bits.h @@ -0,0 +1,78 @@ +/* + * bits.h -- bit vector manipulation + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file bits.h + * @brief Bit vector manipulation + */ + +#ifndef COAP_BITS_H_ +#define COAP_BITS_H_ + +#include + +/** + * Sets the bit @p bit in bit-vector @p vec. This function returns @c 1 if bit + * was set or @c -1 on error (i.e. when the given bit does not fit in the + * vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to set in @p vec. + * + * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise. + */ +COAP_STATIC_INLINE int +bits_setb(uint8_t *vec, size_t size, uint8_t bit) { + if (size <= ((size_t)bit >> 3)) + return -1; + + *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07)); + return 1; +} + +/** + * Clears the bit @p bit from bit-vector @p vec. This function returns @c 1 if + * bit was cleared or @c -1 on error (i.e. when the given bit does not fit in + * the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to clear from @p vec. + * + * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise. + */ +COAP_STATIC_INLINE int +bits_clrb(uint8_t *vec, size_t size, uint8_t bit) { + if (size <= ((size_t)bit >> 3)) + return -1; + + *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07))); + return 1; +} + +/** + * Gets the status of bit @p bit from bit-vector @p vec. This function returns + * @c 1 if the bit is set, @c 0 otherwise (even in case of an error). + * + * @param vec The bit-vector to read from. + * @param size The size of @p vec in bytes. + * @param bit The bit to get from @p vec. + * + * @return @c 1 if the bit is set, @c 0 otherwise. + */ +COAP_STATIC_INLINE int +bits_getb(const uint8_t *vec, size_t size, uint8_t bit) { + if (size <= ((size_t)bit >> 3)) + return -1; + + return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0; +} + +#endif /* COAP_BITS_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/block.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/block.h new file mode 100644 index 00000000..84889763 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/block.h @@ -0,0 +1,173 @@ +/* + * block.h -- block transfer + * + * Copyright (C) 2010-2012,2014-2015 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_BLOCK_H_ +#define COAP_BLOCK_H_ + +#include "encode.h" +#include "option.h" +#include "pdu.h" + +struct coap_resource_t; +struct coap_session_t; + +/** + * @defgroup block Block Transfer + * API functions for handling PDUs using CoAP BLOCK options + * @{ + */ + +#ifndef COAP_MAX_BLOCK_SZX +/** + * The largest value for the SZX component in a Block option. + */ +#define COAP_MAX_BLOCK_SZX 6 +#endif /* COAP_MAX_BLOCK_SZX */ + +/** + * Structure of Block options. + */ +typedef struct { + unsigned int num; /**< block number */ + unsigned int m:1; /**< 1 if more blocks follow, 0 otherwise */ + unsigned int szx:3; /**< block size */ +} coap_block_t; + +/** + * Returns the value of the least significant byte of a Block option @p opt. + * For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST + * returns @c NULL. + */ +#define COAP_OPT_BLOCK_LAST(opt) \ + (coap_opt_length(opt) ? (coap_opt_value(opt) + (coap_opt_length(opt)-1)) : 0) + +/** Returns the value of the More-bit of a Block option @p opt. */ +#define COAP_OPT_BLOCK_MORE(opt) \ + (coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0) + +/** Returns the value of the SZX-field of a Block option @p opt. */ +#define COAP_OPT_BLOCK_SZX(opt) \ + (coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0) + +/** + * Returns the value of field @c num in the given block option @p block_opt. + */ +unsigned int coap_opt_block_num(const coap_opt_t *block_opt); + +/** + * Checks if more than @p num blocks are required to deliver @p data_len + * bytes of data for a block size of 1 << (@p szx + 4). + */ +COAP_STATIC_INLINE int +coap_more_blocks(size_t data_len, unsigned int num, uint16_t szx) { + return ((num+1) << (szx + 4)) < data_len; +} + +#if 0 +/** Sets the More-bit in @p block_opt */ +COAP_STATIC_INLINE void +coap_opt_block_set_m(coap_opt_t *block_opt, int m) { + if (m) + *(coap_opt_value(block_opt) + (coap_opt_length(block_opt) - 1)) |= 0x08; + else + *(coap_opt_value(block_opt) + (coap_opt_length(block_opt) - 1)) &= ~0x08; +} +#endif + +/** + * Initializes @p block from @p pdu. @p type must be either COAP_OPTION_BLOCK1 + * or COAP_OPTION_BLOCK2. When option @p type was found in @p pdu, @p block is + * initialized with values from this option and the function returns the value + * @c 1. Otherwise, @c 0 is returned. + * + * @param pdu The pdu to search for option @p type. + * @param type The option to search for (must be COAP_OPTION_BLOCK1 or + * COAP_OPTION_BLOCK2). + * @param block The block structure to initilize. + * + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_get_block(coap_pdu_t *pdu, uint16_t type, coap_block_t *block); + +/** + * Writes a block option of type @p type to message @p pdu. If the requested + * block size is too large to fit in @p pdu, it is reduced accordingly. An + * exception is made for the final block when less space is required. The actual + * length of the resource is specified in @p data_length. + * + * This function may change *block to reflect the values written to @p pdu. As + * the function takes into consideration the remaining space @p pdu, no more + * options should be added after coap_write_block_opt() has returned. + * + * @param block The block structure to use. On return, this object is + * updated according to the values that have been written to + * @p pdu. + * @param type COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2. + * @param pdu The message where the block option should be written. + * @param data_length The length of the actual data that will be added the @p + * pdu by calling coap_add_block(). + * + * @return @c 1 on success, or a negative value on error. + */ +int coap_write_block_opt(coap_block_t *block, + uint16_t type, + coap_pdu_t *pdu, + size_t data_length); + +/** + * Adds the @p block_num block of size 1 << (@p block_szx + 4) from source @p + * data to @p pdu. + * + * @param pdu The message to add the block. + * @param len The length of @p data. + * @param data The source data to fill the block with. + * @param block_num The actual block number. + * @param block_szx Encoded size of block @p block_number. + * + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_add_block(coap_pdu_t *pdu, + unsigned int len, + const uint8_t *data, + unsigned int block_num, + unsigned char block_szx); + +/** + * Adds the appropriate part of @p data to the @p response pdu. If blocks are + * required, then the appropriate block will be added to the PDU and sent. + * Adds a ETAG option that is the hash of the entire data if the data is to be + * split into blocks + * Used by a GET request handler. + * + * @param resource The resource the data is associated with. + * @param session The coap session. + * @param request The requesting pdu. + * @param response The response pdu. + * @param token The token taken from the (original) requesting pdu. + * @param media_type The format of the data. + * @param maxage The maxmimum life of the data. If @c -1, then there + * is no maxage. + * @param length The total length of the data. + * @param data The entire data block to transmit. + * + */ +void +coap_add_data_blocked_response(struct coap_resource_t *resource, + struct coap_session_t *session, + coap_pdu_t *request, + coap_pdu_t *response, + const coap_binary_t *token, + uint16_t media_type, + int maxage, + size_t length, + const uint8_t* data); + +/**@}*/ + +#endif /* COAP_BLOCK_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_debug.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_debug.h new file mode 100644 index 00000000..e4631b71 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_debug.h @@ -0,0 +1,209 @@ +/* + * coap_debug.h -- debug utilities + * + * Copyright (C) 2010-2011,2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_DEBUG_H_ +#define COAP_DEBUG_H_ + +/** + * @defgroup logging Logging Support + * API functions for logging support + * @{ + */ + +#ifndef COAP_DEBUG_FD +/** + * Used for output for @c LOG_DEBUG to @c LOG_ERR. + */ +#define COAP_DEBUG_FD stdout +#endif + +#ifndef COAP_ERR_FD +/** + * Used for output for @c LOG_CRIT to @c LOG_EMERG. + */ +#define COAP_ERR_FD stderr +#endif + +#ifdef HAVE_SYSLOG_H +#include +/** + * Logging type. One of LOG_* from @b syslog. + */ +typedef short coap_log_t; +#else +/** Pre-defined log levels akin to what is used in \b syslog. */ +typedef enum { + LOG_EMERG=0, /**< Emergency */ + LOG_ALERT, /**< Alert */ + LOG_CRIT, /**< Critical */ + LOG_ERR, /**< Error */ + LOG_WARNING, /**< Warning */ + LOG_NOTICE, /**< Notice */ + LOG_INFO, /**< Information */ + LOG_DEBUG /**< Debug */ +} coap_log_t; +#endif + +/** + * Get the current logging level. + * + * @return One of the LOG_* values. + */ +coap_log_t coap_get_log_level(void); + +/** + * Sets the log level to the specified value. + * + * @param level One of the LOG_* values. + */ +void coap_set_log_level(coap_log_t level); + +/** + * Logging call-back handler definition. + * + * @param level One of the LOG_* values. + * @param message Zero-terminated string message to log. + */ +typedef void (*coap_log_handler_t) (coap_log_t level, const char *message); + +/** + * Add a custom log callback handler. + * + * @param handler The logging handler to use or @p NULL to use default handler. + */ +void coap_set_log_handler(coap_log_handler_t handler); + +/** + * Get the library package name. + * + * @return Zero-terminated string with the name of this library. + */ +const char *coap_package_name(void); + +/** + * Get the library package version. + * + * @return Zero-terminated string with the library version. + */ +const char *coap_package_version(void); + +/** + * Writes the given text to @c COAP_ERR_FD (for @p level <= @c LOG_CRIT) or @c + * COAP_DEBUG_FD (for @p level >= @c LOG_ERR). The text is output only when + * @p level is below or equal to the log level that set by coap_set_log_level(). + * + * Internal function. + * + * @param level One of the LOG_* values. + & @param format The format string to use. + */ +#if (defined(__GNUC__)) +void coap_log_impl(coap_log_t level, + const char *format, ...) __attribute__ ((format(printf, 2, 3))); +#else +void coap_log_impl(coap_log_t level, const char *format, ...); +#endif + +#ifndef coap_log +/** + * Logging function. + * Writes the given text to @c COAP_ERR_FD (for @p level <= @c LOG_CRIT) or @c + * COAP_DEBUG_FD (for @p level >= @c LOG_ERR). The text is output only when + * @p level is below or equal to the log level that set by coap_set_log_level(). + * + * @param level One of the LOG_* values. + */ +#define coap_log(level, ...) do { \ + if ((int)((level))<=(int)coap_get_log_level()) \ + coap_log_impl((level), __VA_ARGS__); \ +} while(0) +#endif + +#include "pdu.h" + +/** + * Defines the output mode for the coap_show_pdu() function. + * + * @param use_fprintf @p 1 if the output is to use fprintf() (the default) + * @p 0 if the output is to use coap_log(). + */ +void coap_set_show_pdu_output(int use_fprintf); + +/** + * Display the contents of the specified @p pdu. + * Note: The output method of coap_show_pdu() is dependent on the setting of + * coap_set_show_pdu_output(). + * + * @param level The required minimum logging level. + * @param pdu The PDU to decode. + */ +void coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu); + +/** + * Display the current (D)TLS library linked with and built for version. + * + * @param level The required minimum logging level. + */ +void coap_show_tls_version(coap_log_t level); + +/** + * Build a string containing the current (D)TLS library linked with and + * built for version. + * + * @param buffer The buffer to put the string into. + * @param bufsize The size of the buffer to put the string into. + * + * @return A pointer to the provided buffer. + */ +char *coap_string_tls_version(char *buffer, size_t bufsize); + +struct coap_address_t; + +/** + * Print the address into the defined buffer. + * + * Internal Function. + * + * @param address The address to print. + * @param buffer The buffer to print into. + * @param size The size of the buffer to print into. + * + * @return The amount written into the buffer. + */ +size_t coap_print_addr(const struct coap_address_t *address, + unsigned char *buffer, size_t size); + +/** @} */ + +/** + * Set the packet loss level for testing. This can be in one of two forms. + * + * Percentage : 0% to 100%. Use the specified probability. + * 0% is send all packets, 100% is drop all packets. + * + * List: A comma separated list of numbers or number ranges that are the + * packets to drop. + * + * @param loss_level The defined loss level (percentage or list). + * + * @return @c 1 If loss level set, @c 0 if there is an error. + */ +int coap_debug_set_packet_loss(const char *loss_level); + +/** + * Check to see whether a packet should be sent or not. + * + * Internal function + * + * @return @c 1 if packet is to be sent, @c 0 if packet is to be dropped. + */ +int coap_debug_send_packet(void); + + +#endif /* COAP_DEBUG_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_dtls.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_dtls.h new file mode 100644 index 00000000..f0554f3d --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_dtls.h @@ -0,0 +1,611 @@ +/* + * coap_dtls.h -- (Datagram) Transport Layer Support for libcoap + * + * Copyright (C) 2016 Olaf Bergmann + * Copyright (C) 2017 Jean-Claude Michelou + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_DTLS_H_ +#define COAP_DTLS_H_ + +#include "coap_time.h" + +struct coap_context_t; +struct coap_session_t; +struct coap_dtls_pki_t; + +/** + * @defgroup dtls DTLS Support + * API functions for interfacing with DTLS libraries. + * @{ + */ + +/** + * Check whether DTLS is available. + * + * @return @c 1 if support for DTLS is enabled, or @c 0 otherwise. + */ +int coap_dtls_is_supported(void); + +/** + * Check whether TLS is available. + * + * @return @c 1 if support for TLS is enabled, or @c 0 otherwise. + */ +int coap_tls_is_supported(void); + +#define COAP_TLS_LIBRARY_NOTLS 0 /**< No DTLS library */ +#define COAP_TLS_LIBRARY_TINYDTLS 1 /**< Using TinyDTLS library */ +#define COAP_TLS_LIBRARY_OPENSSL 2 /**< Using OpenSSL library */ +#define COAP_TLS_LIBRARY_GNUTLS 3 /**< Using GnuTLS library */ + +/** + * The structure used for returning the underlying (D)TLS library + * information. + */ +typedef struct coap_tls_version_t { + uint64_t version; /**< (D)TLS runtime Library Version */ + int type; /**< Library type. One of COAP_TLS_LIBRARY_* */ + uint64_t built_version; /**< (D)TLS Built against Library Version */ +} coap_tls_version_t; + +/** + * Determine the type and version of the underlying (D)TLS library. + * + * @return The version and type of library libcoap was compiled against. + */ +coap_tls_version_t *coap_get_tls_library_version(void); + +/** + * Additional Security setup handler that can be set up by + * coap_context_set_pki(). + * Invoked when libcoap has done the validation checks at the TLS level, + * but the application needs to do some additional checks/changes/updates. + * + * @param tls_session The security session definition - e.g. SSL * for OpenSSL. + * NULL if server call-back. + * This will be dependent on the underlying TLS library - + * see coap_get_tls_library_version() + * @param setup_data A structure containing setup data originally passed into + * coap_context_set_pki() or coap_new_client_session_pki(). + * + * @return @c 1 if successful, else @c 0. + */ +typedef int (*coap_dtls_security_setup_t)(void* tls_session, + struct coap_dtls_pki_t *setup_data); + +/** + * CN Validation call-back that can be set up by coap_context_set_pki(). + * Invoked when libcoap has done the validation checks at the TLS level, + * but the application needs to check that the CN is allowed. + * CN is the SubjectAltName in the cert, if not present, then the leftmost + * Common Name (CN) component of the subject name. + * + * @param cn The determined CN from the certificate + * @param asn1_public_cert The ASN.1 DER encoded X.509 certificate + * @param asn1_length The ASN.1 length + * @param coap_session The CoAP session associated with the certificate update + * @param depth Depth in cert chain. If 0, then client cert, else a CA + * @param validated TLS layer can find no issues if 1 + * @param arg The same as was passed into coap_context_set_pki() + * in setup_data->cn_call_back_arg + * + * @return @c 1 if accepted, else @c 0 if to be rejected. + */ +typedef int (*coap_dtls_cn_callback_t)(const char *cn, + const uint8_t *asn1_public_cert, + size_t asn1_length, + struct coap_session_t *coap_session, + unsigned depth, + int validated, + void *arg); + +/** + * The enum used for determining the provided PKI ASN.1 (DER) Private Key + * formats. + */ +typedef enum coap_asn1_privatekey_type_t { + COAP_ASN1_PKEY_NONE, /**< NONE */ + COAP_ASN1_PKEY_RSA, /**< RSA type */ + COAP_ASN1_PKEY_RSA2, /**< RSA2 type */ + COAP_ASN1_PKEY_DSA, /**< DSA type */ + COAP_ASN1_PKEY_DSA1, /**< DSA1 type */ + COAP_ASN1_PKEY_DSA2, /**< DSA2 type */ + COAP_ASN1_PKEY_DSA3, /**< DSA3 type */ + COAP_ASN1_PKEY_DSA4, /**< DSA4 type */ + COAP_ASN1_PKEY_DH, /**< DH type */ + COAP_ASN1_PKEY_DHX, /**< DHX type */ + COAP_ASN1_PKEY_EC, /**< EC type */ + COAP_ASN1_PKEY_HMAC, /**< HMAC type */ + COAP_ASN1_PKEY_CMAC, /**< CMAC type */ + COAP_ASN1_PKEY_TLS1_PRF, /**< TLS1_PRF type */ + COAP_ASN1_PKEY_HKDF /**< HKDF type */ +} coap_asn1_privatekey_type_t; + +/** + * The enum used for determining the PKI key formats. + */ +typedef enum coap_pki_key_t { + COAP_PKI_KEY_PEM = 0, /**< The PKI key type is PEM */ + COAP_PKI_KEY_ASN1, /**< The PKI key type is ASN.1 (DER) */ +} coap_pki_key_t; + +/** + * The structure that holds the PKI PEM definitions. + */ +typedef struct coap_pki_key_pem_t { + const char *ca_file; /**< File location of Common CA in PEM format */ + const char *public_cert; /**< File location of Public Cert in PEM format */ + const char *private_key; /**< File location of Private Key in PEM format */ +} coap_pki_key_pem_t; + +/** + * The structure that holds the PKI ASN.1 (DER) definitions. + */ +typedef struct coap_pki_key_asn1_t { + const uint8_t *ca_cert; /**< ASN1 (DER) Common CA Cert */ + const uint8_t *public_cert; /**< ASN1 (DER) Public Cert */ + const uint8_t *private_key; /**< ASN1 (DER) Private Key */ + size_t ca_cert_len; /**< ASN1 CA Cert length */ + size_t public_cert_len; /**< ASN1 Public Cert length */ + size_t private_key_len; /**< ASN1 Private Key length */ + coap_asn1_privatekey_type_t private_key_type; /**< Private Key Type */ +} coap_pki_key_asn1_t; + +/** + * The structure that holds the PKI key information. + */ +typedef struct coap_dtls_key_t { + coap_pki_key_t key_type; /**< key format type */ + union { + coap_pki_key_pem_t pem; /**< for PEM keys */ + coap_pki_key_asn1_t asn1; /**< for ASN.1 (DER) keys */ + } key; +} coap_dtls_key_t; + +/** + * Server Name Indication (SNI) Validation call-back that can be set up by + * coap_context_set_pki(). + * Invoked if the SNI is not previously seen and prior to sending a certificate + * set back to the client so that the appropriate certificate set can be used + * based on the requesting SNI. + * + * @param sni The requested SNI + * @param arg The same as was passed into coap_context_set_pki() + * in setup_data->sni_call_back_arg + * + * @return New set of certificates to use, or @c NULL if SNI is to be rejected. + */ +typedef coap_dtls_key_t *(*coap_dtls_sni_callback_t)(const char *sni, + void* arg); + + +#define COAP_DTLS_PKI_SETUP_VERSION 1 /**< Latest PKI setup version */ + +/** + * The structure used for defining the PKI setup data to be used. + */ +typedef struct coap_dtls_pki_t { + uint8_t version; /** Set to 1 to support this version of the struct */ + + /* Options to enable different TLS functionality in libcoap */ + uint8_t verify_peer_cert; /**< 1 if peer cert is to be verified */ + uint8_t require_peer_cert; /**< 1 if peer cert is required */ + uint8_t allow_self_signed; /**< 1 if self signed certs are allowed */ + uint8_t allow_expired_certs; /**< 1 if expired certs are allowed */ + uint8_t cert_chain_validation; /**< 1 if to check cert_chain_verify_depth */ + uint8_t cert_chain_verify_depth; /**< recommended depth is 3 */ + uint8_t check_cert_revocation; /**< 1 if revocation checks wanted */ + uint8_t allow_no_crl; /**< 1 ignore if CRL not there */ + uint8_t allow_expired_crl; /**< 1 if expired crl is allowed */ + uint8_t reserved[6]; /**< Reserved - must be set to 0 for + future compatibility */ + /* Size of 6 chosen to align to next + * parameter, so if newly defined option + * it can use one of the reserverd slot so + * no need to change + * COAP_DTLS_PKI_SETUP_VERSION and just + * decrement the reserved[] count. + */ + + /** CN check call-back function. + * If not NULL, is called when the TLS connection has passed the configured + * TLS options above for the application to verify if the CN is valid. + */ + coap_dtls_cn_callback_t validate_cn_call_back; + void *cn_call_back_arg; /**< Passed in to the CN call-back function */ + + /** SNI check call-back function. + * If not @p NULL, called if the SNI is not previously seen and prior to + * sending a certificate set back to the client so that the appropriate + * certificate set can be used based on the requesting SNI. + */ + coap_dtls_sni_callback_t validate_sni_call_back; + void *sni_call_back_arg; /**< Passed in to the sni call-back function */ + + /** Additional Security call-back handler that is invoked when libcoap has + * done the standerd, defined validation checks at the TLS level, + * If not @p NULL, called from within the TLS Client Hello connection + * setup. + */ + coap_dtls_security_setup_t additional_tls_setup_call_back; + + char* client_sni; /**< If not NULL, SNI to use in client TLS setup. + Owned by the client app and must remain valid + during the call to coap_new_client_session_pki() */ + + coap_dtls_key_t pki_key; /**< PKI key definition */ +} coap_dtls_pki_t; + +/** @} */ + +/** + * @defgroup dtls_internal DTLS Support (Internal) + * Internal API functions for interfacing with DTLS libraries. + * @{ + */ + +/** + * Creates a new DTLS context for the given @p coap_context. This function + * returns a pointer to a new DTLS context object or @c NULL on error. + * + * Internal function. + * + * @param coap_context The CoAP context where the DTLS object shall be used. + * + * @return A DTLS context object or @c NULL on error. + */ +void * +coap_dtls_new_context(struct coap_context_t *coap_context); + +typedef enum coap_dtls_role_t { + COAP_DTLS_ROLE_CLIENT, /**< Internal function invoked for client */ + COAP_DTLS_ROLE_SERVER /**< Internal function invoked for server */ +} coap_dtls_role_t; + +/** + * Set the DTLS context's default PSK information. + * This does the PSK specifics following coap_dtls_new_context(). + * If @p COAP_DTLS_ROLE_SERVER, then identity hint will also get set. + * If @p COAP_DTLS_ROLE_SERVER, then the information will get put into the + * TLS library's context (from which sessions are derived). + * If @p COAP_DTLS_ROLE_CLIENT, then the information will get put into the + * TLS library's session. + * + * Internal function. + * + * @param coap_context The CoAP context. + * @param identity_hint The default PSK server identity hint sent to a client. + * Required parameter. If @p NULL, will be set to "". + * Empty string is a valid hint. + * This parameter is ignored if COAP_DTLS_ROLE_CLIENT + * @param role One of @p COAP_DTLS_ROLE_CLIENT or @p COAP_DTLS_ROLE_SERVER + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_psk(struct coap_context_t *coap_context, + const char *identity_hint, + coap_dtls_role_t role); + +/** + * Set the DTLS context's default server PKI information. + * This does the PKI specifics following coap_dtls_new_context(). + * If @p COAP_DTLS_ROLE_SERVER, then the information will get put into the + * TLS library's context (from which sessions are derived). + * If @p COAP_DTLS_ROLE_CLIENT, then the information will get put into the + * TLS library's session. + * + * Internal function. + * + * @param coap_context The CoAP context. + * @param setup_data Setup information defining how PKI is to be setup. + * Required parameter. If @p NULL, PKI will not be + * set up. + * @param role One of @p COAP_DTLS_ROLE_CLIENT or @p COAP_DTLS_ROLE_SERVER + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_pki(struct coap_context_t *coap_context, + coap_dtls_pki_t *setup_data, + coap_dtls_role_t role); + +/** + * Set the dtls context's default Root CA information for a client or server. + * + * Internal function. + * + * @param coap_context The current coap_context_t object. + * @param ca_file If not @p NULL, is the full path name of a PEM encoded + * file containing all the Root CAs to be used. + * @param ca_dir If not @p NULL, points to a directory containing PEM + * encoded files containing all the Root CAs to be used. + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_pki_root_cas(struct coap_context_t *coap_context, + const char *ca_file, + const char *ca_dir); + +/** + * Check whether one of the coap_dtls_context_set_{psk|pki}() functions have + * been called. + * + * Internal function. + * + * @param coap_context The current coap_context_t object. + * + * @return @c 1 if coap_dtls_context_set_{psk|pki}() called, else @c 0. + */ + +int coap_dtls_context_check_keys_enabled(struct coap_context_t *coap_context); + +/** + * Releases the storage allocated for @p dtls_context. + * + * Internal function. + * + * @param dtls_context The DTLS context as returned by coap_dtls_new_context(). + */ +void coap_dtls_free_context(void *dtls_context); + +/** + * Create a new client-side session. This should send a HELLO to the server. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. +*/ +void *coap_dtls_new_client_session(struct coap_session_t *coap_session); + +/** + * Create a new DTLS server-side session. + * Called after coap_dtls_hello() has returned @c 1, signalling that a validated + * HELLO was received from a client. + * This should send a HELLO to the server. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the DTLS session. + */ +void *coap_dtls_new_server_session(struct coap_session_t *coap_session); + +/** + * Terminates the DTLS session (may send an ALERT if necessary) then frees the + * underlying TLS library object containing security parameters for the session. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_free_session(struct coap_session_t *coap_session); + +/** + * Notify of a change in the CoAP session's MTU, for example after + * a PMTU update. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_session_update_mtu(struct coap_session_t *coap_session); + +/** + * Send data to a DTLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data pointer to data. + * @param data_len Number of bytes to send. + * + * @return @c 0 if this would be blocking, @c -1 if there is an error or the + * number of cleartext bytes sent. + */ +int coap_dtls_send(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Check if timeout is handled per CoAP session or per CoAP context. + * + * Internal function. + * + * @return @c 1 of timeout and retransmit is per context, @c 0 if it is + * per session. + */ +int coap_dtls_is_context_timeout(void); + +/** + * Do all pending retransmits and get next timeout + * + * Internal function. + * + * @param dtls_context The DTLS context. + * + * @return @c 0 if no event is pending or date of the next retransmit. + */ +coap_tick_t coap_dtls_get_context_timeout(void *dtls_context); + +/** + * Get next timeout for this session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param now The current time in ticks. + * + * @return @c 0 If no event is pending or ticks time of the next retransmit. + */ +coap_tick_t coap_dtls_get_timeout(struct coap_session_t *coap_session, + coap_tick_t now); + +/** + * Handle a DTLS timeout expiration. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_handle_timeout(struct coap_session_t *coap_session); + +/** + * Handling incoming data from a DTLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Encrypted datagram. + * @param data_len Encrypted datagram size. + * + * @return Result of coap_handle_dgram on the decrypted CoAP PDU + * or @c -1 for error. + */ +int coap_dtls_receive(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Handling client HELLO messages from a new candiate peer. + * Note that session->tls is empty. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Encrypted datagram. + * @param data_len Encrypted datagram size. + * + * @return @c 0 if a cookie verification message has been sent, @c 1 if the + * HELLO contains a valid cookie and a server session should be created, + * @c -1 if the message is invalid. + */ +int coap_dtls_hello(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Get DTLS overhead over cleartext PDUs. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Maximum number of bytes added by DTLS layer. + */ +unsigned int coap_dtls_get_overhead(struct coap_session_t *coap_session); + +/** + * Create a new TLS client-side session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param connected Updated with whether the connection is connected yet or not. + * @c 0 is not connected, @c 1 is connected. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. +*/ +void *coap_tls_new_client_session(struct coap_session_t *coap_session, int *connected); + +/** + * Create a TLS new server-side session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param connected Updated with whether the connection is connected yet or not. + * @c 0 is not connected, @c 1 is connected. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. + */ +void *coap_tls_new_server_session(struct coap_session_t *coap_session, int *connected); + +/** + * Terminates the TLS session (may send an ALERT if necessary) then frees the + * underlying TLS library object containing security parameters for the session. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_tls_free_session( struct coap_session_t *coap_session ); + +/** + * Send data to a TLS peer, with implicit flush. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Pointer to data. + * @param data_len Number of bytes to send. + * + * @return @c 0 if this should be retried, @c -1 if there is an error + * or the number of cleartext bytes sent. + */ +ssize_t coap_tls_write(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len + ); + +/** + * Read some data from a TLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Pointer to data. + * @param data_len Maximum number of bytes to read. + * + * @return @c 0 if this should be retried, @c -1 if there is an error + * or the number of cleartext bytes read. + */ +ssize_t coap_tls_read(struct coap_session_t *coap_session, + uint8_t *data, + size_t data_len + ); + +/** + * Initialize the underlying (D)TLS Library layer. + * + * Internal function. + * + */ +void coap_dtls_startup(void); + +/** @} */ + +/** + * @ingroup logging + * Sets the (D)TLS logging level to the specified @p level. + * Note: coap_log_level() will influence output if at a specified level. + * + * @param level The logging level to use - LOG_* + */ +void coap_dtls_set_log_level(int level); + +/** + * @ingroup logging + * Get the current (D)TLS logging. + * + * @return The current log level (one of LOG_*). + */ +int coap_dtls_get_log_level(void); + + +#endif /* COAP_DTLS_H */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_event.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_event.h new file mode 100644 index 00000000..81a3b051 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_event.h @@ -0,0 +1,102 @@ +/* + * coap_event.h -- libcoap Event API + * + * Copyright (C) 2016 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_EVENT_H_ +#define COAP_EVENT_H_ + +#include "libcoap.h" + +struct coap_context_t; +struct coap_session_t; + +/** + * @defgroup events Event API + * API functions for event delivery from lower-layer library functions. + * @{ + */ + +/** + * Scalar type to represent different events, e.g. DTLS events or + * retransmission timeouts. + */ + typedef unsigned int coap_event_t; + +/** + * (D)TLS events for COAP_PROTO_DTLS and COAP_PROTO_TLS + */ +#define COAP_EVENT_DTLS_CLOSED 0x0000 +#define COAP_EVENT_DTLS_CONNECTED 0x01DE +#define COAP_EVENT_DTLS_RENEGOTIATE 0x01DF +#define COAP_EVENT_DTLS_ERROR 0x0200 + +/** + * TCP events for COAP_PROTO_TCP and COAP_PROTO_TLS + */ +#define COAP_EVENT_TCP_CONNECTED 0x1001 +#define COAP_EVENT_TCP_CLOSED 0x1002 +#define COAP_EVENT_TCP_FAILED 0x1003 + +/** + * CSM exchange events for reliable protocols only + */ +#define COAP_EVENT_SESSION_CONNECTED 0x2001 +#define COAP_EVENT_SESSION_CLOSED 0x2002 +#define COAP_EVENT_SESSION_FAILED 0x2003 + +/** + * Type for event handler functions that can be registered with a CoAP + * context using the unction coap_set_event_handler(). When called by + * the library, the first argument will be the coap_context_t object + * where the handler function has been registered. The second argument + * is the event type that may be complemented by event-specific data + * passed as the third argument. + */ +typedef int (*coap_event_handler_t)(struct coap_context_t *, + coap_event_t event, + struct coap_session_t *session); + +/** + * Registers the function @p hnd as callback for events from the given + * CoAP context @p context. Any event handler that has previously been + * registered with @p context will be overwritten by this operation. + * + * @param context The CoAP context to register the event handler with. + * @param hnd The event handler to be registered. @c NULL if to be + * de-registered. + */ +void coap_register_event_handler(struct coap_context_t *context, + coap_event_handler_t hnd); + +/** + * Registers the function @p hnd as callback for events from the given + * CoAP context @p context. Any event handler that has previously been + * registered with @p context will be overwritten by this operation. + * + * @deprecated Use coap_register_event_handler() instead. + * + * @param context The CoAP context to register the event handler with. + * @param hnd The event handler to be registered. + */ +COAP_DEPRECATED +void coap_set_event_handler(struct coap_context_t *context, + coap_event_handler_t hnd); + +/** + * Clears the event handler registered with @p context. + * + * @deprecated Use coap_register_event_handler() instead with NULL for hnd. + * + * @param context The CoAP context whose event handler is to be removed. + */ +COAP_DEPRECATED +void coap_clear_event_handler(struct coap_context_t *context); + +/** @} */ + +#endif /* COAP_EVENT_H */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_hashkey.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_hashkey.h new file mode 100644 index 00000000..252f3482 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_hashkey.h @@ -0,0 +1,59 @@ +/* + * coap_hashkey.h -- definition of hash key type and helper functions + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_hashkey.h + * @brief definition of hash key type and helper functions + */ + +#ifndef COAP_HASHKEY_H_ +#define COAP_HASHKEY_H_ + +#include "libcoap.h" +#include "uthash.h" +#include "str.h" + +typedef unsigned char coap_key_t[4]; + +#ifndef coap_hash +/** + * Calculates a fast hash over the given string @p s of length @p len and stores + * the result into @p h. Depending on the exact implementation, this function + * cannot be used as one-way function to check message integrity or simlar. + * + * @param s The string used for hash calculation. + * @param len The length of @p s. + * @param h The result buffer to store the calculated hash key. + */ +void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h); + +#define coap_hash(String,Length,Result) \ + coap_hash_impl((String),(Length),(Result)) + +/* This is used to control the pre-set hash-keys for resources. */ +#define COAP_DEFAULT_HASH +#else +#undef COAP_DEFAULT_HASH +#endif /* coap_hash */ + +/** + * Calls coap_hash() with given @c coap_string_t object as parameter. + * + * @param Str Must contain a pointer to a coap string object. + * @param H A coap_key_t object to store the result. + * + * @hideinitializer + */ +#define coap_str_hash(Str,H) { \ + assert(Str); \ + memset((H), 0, sizeof(coap_key_t)); \ + coap_hash((Str)->s, (Str)->length, (H)); \ + } + +#endif /* COAP_HASHKEY_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_io.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_io.h new file mode 100644 index 00000000..1854501b --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_io.h @@ -0,0 +1,210 @@ +/* + * coap_io.h -- Default network I/O functions for libcoap + * + * Copyright (C) 2012-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_IO_H_ +#define COAP_IO_H_ + +#include +#include + +#include "address.h" + +#ifndef COAP_RXBUFFER_SIZE +#define COAP_RXBUFFER_SIZE 1472 +#endif /* COAP_RXBUFFER_SIZE */ + +#ifdef _WIN32 +typedef SOCKET coap_fd_t; +#define coap_closesocket closesocket +#define COAP_SOCKET_ERROR SOCKET_ERROR +#define COAP_INVALID_SOCKET INVALID_SOCKET +#else +typedef int coap_fd_t; +#define coap_closesocket close +#define COAP_SOCKET_ERROR (-1) +#define COAP_INVALID_SOCKET (-1) +#endif + +struct coap_packet_t; +struct coap_session_t; +struct coap_pdu_t; + +typedef uint16_t coap_socket_flags_t; + +typedef struct coap_socket_t { +#if defined(WITH_LWIP) + struct udp_pcb *pcb; +#elif defined(WITH_CONTIKI) + void *conn; +#else + coap_fd_t fd; +#endif /* WITH_LWIP */ + coap_socket_flags_t flags; +} coap_socket_t; + +/** + * coap_socket_flags_t values + */ +#define COAP_SOCKET_EMPTY 0x0000 /**< the socket is not used */ +#define COAP_SOCKET_NOT_EMPTY 0x0001 /**< the socket is not empty */ +#define COAP_SOCKET_BOUND 0x0002 /**< the socket is bound */ +#define COAP_SOCKET_CONNECTED 0x0004 /**< the socket is connected */ +#define COAP_SOCKET_WANT_READ 0x0010 /**< non blocking socket is waiting for reading */ +#define COAP_SOCKET_WANT_WRITE 0x0020 /**< non blocking socket is waiting for writing */ +#define COAP_SOCKET_WANT_ACCEPT 0x0040 /**< non blocking server socket is waiting for accept */ +#define COAP_SOCKET_WANT_CONNECT 0x0080 /**< non blocking client socket is waiting for connect */ +#define COAP_SOCKET_CAN_READ 0x0100 /**< non blocking socket can now read without blocking */ +#define COAP_SOCKET_CAN_WRITE 0x0200 /**< non blocking socket can now write without blocking */ +#define COAP_SOCKET_CAN_ACCEPT 0x0400 /**< non blocking server socket can now accept without blocking */ +#define COAP_SOCKET_CAN_CONNECT 0x0800 /**< non blocking client socket can now connect without blocking */ +#define COAP_SOCKET_MULTICAST 0x1000 /**< socket is used for multicast communication */ + +struct coap_endpoint_t *coap_malloc_endpoint( void ); +void coap_mfree_endpoint( struct coap_endpoint_t *ep ); + +int +coap_socket_connect_udp(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +int +coap_socket_bind_udp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr ); + +int +coap_socket_connect_tcp1(coap_socket_t *sock, + const coap_address_t *local_if, + const coap_address_t *server, + int default_port, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +int +coap_socket_connect_tcp2(coap_socket_t *sock, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +int +coap_socket_bind_tcp(coap_socket_t *sock, + const coap_address_t *listen_addr, + coap_address_t *bound_addr); + +int +coap_socket_accept_tcp(coap_socket_t *server, + coap_socket_t *new_client, + coap_address_t *local_addr, + coap_address_t *remote_addr); + +void coap_socket_close(coap_socket_t *sock); + +ssize_t +coap_socket_send( coap_socket_t *sock, struct coap_session_t *session, + const uint8_t *data, size_t data_len ); + +ssize_t +coap_socket_write(coap_socket_t *sock, const uint8_t *data, size_t data_len); + +ssize_t +coap_socket_read(coap_socket_t *sock, uint8_t *data, size_t data_len); + +#ifdef WITH_LWIP +ssize_t +coap_socket_send_pdu( coap_socket_t *sock, struct coap_session_t *session, + struct coap_pdu_t *pdu ); +#endif + +const char *coap_socket_strerror( void ); + +/** + * Function interface for data transmission. This function returns the number of + * bytes that have been transmitted, or a value less than zero on error. + * + * @param sock Socket to send data with + * @param session Addressing information for unconnected sockets, or NULL + * @param data The data to send. + * @param datalen The actual length of @p data. + * + * @return The number of bytes written on success, or a value + * less than zero on error. + */ +ssize_t coap_network_send( coap_socket_t *sock, const struct coap_session_t *session, const uint8_t *data, size_t datalen ); + +/** + * Function interface for reading data. This function returns the number of + * bytes that have been read, or a value less than zero on error. In case of an + * error, @p *packet is set to NULL. + * + * @param sock Socket to read data from + * @param packet Received packet metadata and payload. src and dst should be preset. + * + * @return The number of bytes received on success, or a value less than + * zero on error. + */ +ssize_t coap_network_read( coap_socket_t *sock, struct coap_packet_t *packet ); + +#ifndef coap_mcast_interface +# define coap_mcast_interface(Local) 0 +#endif + +/** + * Given a packet, set msg and msg_len to an address and length of the packet's + * data in memory. + * */ +void coap_packet_get_memmapped(struct coap_packet_t *packet, + unsigned char **address, + size_t *length); + +#ifdef WITH_LWIP +/** + * Get the pbuf of a packet. The caller takes over responsibility for freeing + * the pbuf. + */ +struct pbuf *coap_packet_extract_pbuf(struct coap_packet_t *packet); +#endif + +#if defined(WITH_LWIP) +/* + * This is only included in coap_io.h instead of .c in order to be available for + * sizeof in lwippools.h. + * Simple carry-over of the incoming pbuf that is later turned into a node. + * + * Source address data is currently side-banded via ip_current_dest_addr & co + * as the packets have limited lifetime anyway. + */ +struct coap_packet_t { + struct pbuf *pbuf; + const struct coap_endpoint_t *local_interface; + coap_address_t src; /**< the packet's source address */ + coap_address_t dst; /**< the packet's destination address */ + int ifindex; /**< the interface index */ +// uint16_t srcport; +}; +#else +struct coap_packet_t { + coap_address_t src; /**< the packet's source address */ + coap_address_t dst; /**< the packet's destination address */ + int ifindex; /**< the interface index */ + size_t length; /**< length of payload */ + unsigned char payload[COAP_RXBUFFER_SIZE]; /**< payload */ +}; +#endif +typedef struct coap_packet_t coap_packet_t; + +typedef enum { + COAP_NACK_TOO_MANY_RETRIES, + COAP_NACK_NOT_DELIVERABLE, + COAP_NACK_RST, + COAP_NACK_TLS_FAILED +} coap_nack_reason_t; + +#endif /* COAP_IO_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_mutex.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_mutex.h new file mode 100644 index 00000000..99d7d335 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_mutex.h @@ -0,0 +1,50 @@ +/* + * coap_mutex.h -- mutex utilities + * + * Copyright (C) 2019 Jon Shallow + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_mutex.h + * @brief COAP mutex mechanism wrapper + */ + +#ifndef COAP_MUTEX_H_ +#define COAP_MUTEX_H_ + +#if defined(RIOT_VERSION) + +#include + +typedef mutex_t coap_mutex_t; +#define COAP_MUTEX_INITIALIZER MUTEX_INIT +#define coap_mutex_lock(a) mutex_lock(a) +#define coap_mutex_trylock(a) mutex_trylock(a) +#define coap_mutex_unlock(a) mutex_unlock(a) + +#elif defined(WITH_CONTIKI) + +/* CONTIKI does not support mutex */ + +typedef int coap_mutex_t; +#define COAP_MUTEX_INITIALIZER 0 +#define coap_mutex_lock(a) *(a) = 1 +#define coap_mutex_trylock(a) *(a) = 1 +#define coap_mutex_unlock(a) *(a) = 0 + +#else /* ! RIOT_VERSION && ! WITH_CONTIKI */ + +#include + +typedef pthread_mutex_t coap_mutex_t; +#define COAP_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +#define coap_mutex_lock(a) pthread_mutex_lock(a) +#define coap_mutex_trylock(a) pthread_mutex_trylock(a) +#define coap_mutex_unlock(a) pthread_mutex_unlock(a) + +#endif /* ! RIOT_VERSION && ! WITH_CONTIKI */ + +#endif /* COAP_MUTEX_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_session.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_session.h new file mode 100644 index 00000000..1dc0103e --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_session.h @@ -0,0 +1,492 @@ +/* coap_session.h -- Session management for libcoap +* +* Copyright (C) 2017 Jean-Claue Michelou +* +* This file is part of the CoAP library libcoap. Please see +* README for terms of use. +*/ + +#ifndef COAP_SESSION_H_ +#define COAP_SESSION_H_ + + +#include "coap_io.h" +#include "coap_time.h" +#include "pdu.h" + +struct coap_endpoint_t; +struct coap_context_t; +struct coap_queue_t; + +/** +* Abstraction of a fixed point number that can be used where necessary instead +* of a float. 1,000 fractional bits equals one integer +*/ +typedef struct coap_fixed_point_t { + uint16_t integer_part; /**< Integer part of fixed point variable */ + uint16_t fractional_part; /**< Fractional part of fixed point variable + 1/1000 (3 points) precision */ +} coap_fixed_point_t; + +#define COAP_DEFAULT_SESSION_TIMEOUT 300 +#define COAP_PARTIAL_SESSION_TIMEOUT_TICKS (30 * COAP_TICKS_PER_SECOND) +#define COAP_DEFAULT_MAX_HANDSHAKE_SESSIONS 100 + +#define COAP_PROTO_NOT_RELIABLE(p) ((p)==COAP_PROTO_UDP || (p)==COAP_PROTO_DTLS) +#define COAP_PROTO_RELIABLE(p) ((p)==COAP_PROTO_TCP || (p)==COAP_PROTO_TLS) + +typedef uint8_t coap_session_type_t; +/** + * coap_session_type_t values + */ +#define COAP_SESSION_TYPE_CLIENT 1 /**< client-side */ +#define COAP_SESSION_TYPE_SERVER 2 /**< server-side */ +#define COAP_SESSION_TYPE_HELLO 3 /**< server-side ephemeral session for responding to a client hello */ + +typedef uint8_t coap_session_state_t; +/** + * coap_session_state_t values + */ +#define COAP_SESSION_STATE_NONE 0 +#define COAP_SESSION_STATE_CONNECTING 1 +#define COAP_SESSION_STATE_HANDSHAKE 2 +#define COAP_SESSION_STATE_CSM 3 +#define COAP_SESSION_STATE_ESTABLISHED 4 + +typedef struct coap_session_t { + struct coap_session_t *next; + coap_proto_t proto; /**< protocol used */ + coap_session_type_t type; /**< client or server side socket */ + coap_session_state_t state; /**< current state of relationaship with peer */ + unsigned ref; /**< reference count from queues */ + unsigned tls_overhead; /**< overhead of TLS layer */ + unsigned mtu; /**< path or CSM mtu */ + coap_address_t local_if; /**< optional local interface address */ + coap_address_t remote_addr; /**< remote address and port */ + coap_address_t local_addr; /**< local address and port */ + int ifindex; /**< interface index */ + coap_socket_t sock; /**< socket object for the session, if any */ + struct coap_endpoint_t *endpoint; /**< session's endpoint */ + struct coap_context_t *context; /**< session's context */ + void *tls; /**< security parameters */ + uint16_t tx_mid; /**< the last message id that was used in this session */ + uint8_t con_active; /**< Active CON request sent */ + struct coap_queue_t *delayqueue; /**< list of delayed messages waiting to be sent */ + size_t partial_write; /**< if > 0 indicates number of bytes already written from the pdu at the head of sendqueue */ + uint8_t read_header[8]; /**< storage space for header of incoming message header */ + size_t partial_read; /**< if > 0 indicates number of bytes already read for an incoming message */ + coap_pdu_t *partial_pdu; /**< incomplete incoming pdu */ + coap_tick_t last_rx_tx; + coap_tick_t last_tx_rst; + coap_tick_t last_ping; + coap_tick_t last_pong; + coap_tick_t csm_tx; + uint8_t *psk_identity; + size_t psk_identity_len; + uint8_t *psk_key; + size_t psk_key_len; + void *app; /**< application-specific data */ + unsigned int max_retransmit; /**< maximum re-transmit count (default 4) */ + coap_fixed_point_t ack_timeout; /**< timeout waiting for ack (default 2 secs) */ + coap_fixed_point_t ack_random_factor; /**< ack random factor backoff (default 1.5) */ + unsigned int dtls_timeout_count; /**< dtls setup retry counter */ + int dtls_event; /**< Tracking any (D)TLS events on this sesison */ +} coap_session_t; + +/** +* Increment reference counter on a session. +* +* @param session The CoAP session. +* @return same as session +*/ +coap_session_t *coap_session_reference(coap_session_t *session); + +/** +* Decrement reference counter on a session. +* Note that the session may be deleted as a result and should not be used +* after this call. +* +* @param session The CoAP session. +*/ +void coap_session_release(coap_session_t *session); + +/** +* Stores @p data with the given session. This function overwrites any value +* that has previously been stored with @p session. +*/ +void coap_session_set_app_data(coap_session_t *session, void *data); + +/** +* Returns any application-specific data that has been stored with @p +* session using the function coap_session_set_app_data(). This function will +* return @c NULL if no data has been stored. +*/ +void *coap_session_get_app_data(const coap_session_t *session); + +/** +* Notify session that it has failed. +* +* @param session The CoAP session. +* @param reason The reason why the session was disconnected. +*/ +void coap_session_disconnected(coap_session_t *session, coap_nack_reason_t reason); + +/** +* Notify session transport has just connected and CSM exchange can now start. +* +* @param session The CoAP session. +*/ +void coap_session_send_csm(coap_session_t *session); + +/** +* Notify session that it has just connected or reconnected. +* +* @param session The CoAP session. +*/ +void coap_session_connected(coap_session_t *session); + +/** +* Set the session MTU. This is the maximum message size that can be sent, +* excluding IP and UDP overhead. +* +* @param session The CoAP session. +* @param mtu maximum message size +*/ +void coap_session_set_mtu(coap_session_t *session, unsigned mtu); + +/** + * Get maximum acceptable PDU size + * + * @param session The CoAP session. + * @return maximum PDU size, not including header (but including token). + */ +size_t coap_session_max_pdu_size(const coap_session_t *session); + +/** +* Creates a new client session to the designated server. +* @param ctx The CoAP context. +* @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. +* @param server The server's address. If the port number is zero, the default port for the protocol will be used. +* @param proto Protocol. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +coap_session_t *coap_new_client_session( + struct coap_context_t *ctx, + const coap_address_t *local_if, + const coap_address_t *server, + coap_proto_t proto +); + +/** +* Creates a new client session to the designated server with PSK credentials +* @param ctx The CoAP context. +* @param local_if Address of local interface. It is recommended to use NULL to let the operating system choose a suitable local interface. If an address is specified, the port number should be zero, which means that a free port is automatically selected. +* @param server The server's address. If the port number is zero, the default port for the protocol will be used. +* @param proto Protocol. +* @param identity PSK client identity +* @param key PSK shared key +* @param key_len PSK shared key length +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +coap_session_t *coap_new_client_session_psk( + struct coap_context_t *ctx, + const coap_address_t *local_if, + const coap_address_t *server, + coap_proto_t proto, + const char *identity, + const uint8_t *key, + unsigned key_len +); + +struct coap_dtls_pki_t; + +/** +* Creates a new client session to the designated server with PKI credentials +* @param ctx The CoAP context. +* @param local_if Address of local interface. It is recommended to use NULL to +* let the operating system choose a suitable local interface. +* If an address is specified, the port number should be zero, +* which means that a free port is automatically selected. +* @param server The server's address. If the port number is zero, the default +* port for the protocol will be used. +* @param proto CoAP Protocol. +* @param setup_data PKI parameters. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release() +* to free. +*/ +coap_session_t *coap_new_client_session_pki( + struct coap_context_t *ctx, + const coap_address_t *local_if, + const coap_address_t *server, + coap_proto_t proto, + struct coap_dtls_pki_t *setup_data +); + +/** +* Creates a new server session for the specified endpoint. +* @param ctx The CoAP context. +* @param ep An endpoint where an incoming connection request is pending. +* +* @return A new CoAP session or NULL if failed. Call coap_session_release to free. +*/ +coap_session_t *coap_new_server_session( + struct coap_context_t *ctx, + struct coap_endpoint_t *ep +); + +/** +* Function interface for datagram data transmission. This function returns +* the number of bytes that have been transmitted, or a value less than zero +* on error. +* +* @param session Session to send data on. +* @param data The data to send. +* @param datalen The actual length of @p data. +* +* @return The number of bytes written on success, or a value +* less than zero on error. +*/ +ssize_t coap_session_send(coap_session_t *session, + const uint8_t *data, size_t datalen); + +/** +* Function interface for stream data transmission. This function returns +* the number of bytes that have been transmitted, or a value less than zero +* on error. The number of bytes written may be less than datalen because of +* congestion control. +* +* @param session Session to send data on. +* @param data The data to send. +* @param datalen The actual length of @p data. +* +* @return The number of bytes written on success, or a value +* less than zero on error. +*/ +ssize_t coap_session_write(coap_session_t *session, + const uint8_t *data, size_t datalen); + +/** +* Send a pdu according to the session's protocol. This function returns +* the number of bytes that have been transmitted, or a value less than zero +* on error. +* +* @param session Session to send pdu on. +* @param pdu The pdu to send. +* +* @return The number of bytes written on success, or a value +* less than zero on error. +*/ +ssize_t coap_session_send_pdu(coap_session_t *session, coap_pdu_t *pdu); + + +/** + * @ingroup logging + * Get session description. + * + * @param session The CoAP session. + * @return description string. + */ +const char *coap_session_str(const coap_session_t *session); + +ssize_t +coap_session_delay_pdu(coap_session_t *session, coap_pdu_t *pdu, + struct coap_queue_t *node); +/** +* Abstraction of virtual endpoint that can be attached to coap_context_t. The +* tuple (handle, addr) must uniquely identify this endpoint. +*/ +typedef struct coap_endpoint_t { + struct coap_endpoint_t *next; + struct coap_context_t *context; /**< endpoint's context */ + coap_proto_t proto; /**< protocol used on this interface */ + uint16_t default_mtu; /**< default mtu for this interface */ + coap_socket_t sock; /**< socket object for the interface, if any */ + coap_address_t bind_addr; /**< local interface address */ + coap_session_t *sessions; /**< list of active sessions */ +} coap_endpoint_t; + +/** +* Create a new endpoint for communicating with peers. +* +* @param context The coap context that will own the new endpoint +* @param listen_addr Address the endpoint will listen for incoming requests on or originate outgoing requests from. Use NULL to specify that no incoming request will be accepted and use a random endpoint. +* @param proto Protocol used on this endpoint +*/ + +coap_endpoint_t *coap_new_endpoint(struct coap_context_t *context, const coap_address_t *listen_addr, coap_proto_t proto); + +/** +* Set the endpoint's default MTU. This is the maximum message size that can be +* sent, excluding IP and UDP overhead. +* +* @param endpoint The CoAP endpoint. +* @param mtu maximum message size +*/ +void coap_endpoint_set_default_mtu(coap_endpoint_t *endpoint, unsigned mtu); + +void coap_free_endpoint(coap_endpoint_t *ep); + + +/** + * @ingroup logging +* Get endpoint description. +* +* @param endpoint The CoAP endpoint. +* @return description string. +*/ +const char *coap_endpoint_str(const coap_endpoint_t *endpoint); + +/** +* Lookup the server session for the packet received on an endpoint, or create +* a new one. +* +* @param endpoint Active endpoint the packet was received on. +* @param packet Received packet. +* @param now The current time in ticks. +* @return The CoAP session or @c NULL if error. +*/ +coap_session_t *coap_endpoint_get_session(coap_endpoint_t *endpoint, + const struct coap_packet_t *packet, coap_tick_t now); + +/** + * Create a new DTLS session for the @p session. + * Note: the @p session is released if no DTLS server session can be created. + * + * @ingroup dtls_internal + * + * @param session Session to add DTLS session to + * @param now The current time in ticks. + * + * @return CoAP session or @c NULL if error. + */ +coap_session_t *coap_session_new_dtls_session(coap_session_t *session, + coap_tick_t now); + +coap_session_t *coap_session_get_by_peer(struct coap_context_t *ctx, + const struct coap_address_t *remote_addr, int ifindex); + +void coap_session_free(coap_session_t *session); +void coap_session_mfree(coap_session_t *session); + + /** + * @defgroup cc Rate Control + * The transmission parameters for CoAP rate control ("Congestion + * Control" in stream-oriented protocols) are defined in + * https://tools.ietf.org/html/rfc7252#section-4.8 + * @{ + */ + + /** + * Number of seconds when to expect an ACK or a response to an + * outstanding CON message. + * RFC 7252, Section 4.8 Default value of ACK_TIMEOUT is 2 + */ +#define COAP_DEFAULT_ACK_TIMEOUT ((coap_fixed_point_t){2,0}) + + /** + * A factor that is used to randomize the wait time before a message + * is retransmitted to prevent synchronization effects. + * RFC 7252, Section 4.8 Default value of ACK_RANDOM_FACTOR is 1.5 + */ +#define COAP_DEFAULT_ACK_RANDOM_FACTOR ((coap_fixed_point_t){1,500}) + + /** + * Number of message retransmissions before message sending is stopped + * RFC 7252, Section 4.8 Default value of MAX_RETRANSMIT is 4 + */ +#define COAP_DEFAULT_MAX_RETRANSMIT 4 + + /** + * The number of simultaneous outstanding interactions that a client + * maintains to a given server. + * RFC 7252, Section 4.8 Default value of NSTART is 1 + */ +#define COAP_DEFAULT_NSTART 1 + + /** @} */ + +/** +* Set the CoAP maximum retransmit count before failure +* +* Number of message retransmissions before message sending is stopped +* +* @param session The CoAP session. +* @param value The value to set to. The default is 4 and should not normally +* get changed. +*/ +void coap_session_set_max_retransmit(coap_session_t *session, + unsigned int value); + +/** +* Set the CoAP initial ack response timeout before the next re-transmit +* +* Number of seconds when to expect an ACK or a response to an +* outstanding CON message. +* +* @param session The CoAP session. +* @param value The value to set to. The default is 2 and should not normally +* get changed. +*/ +void coap_session_set_ack_timeout(coap_session_t *session, + coap_fixed_point_t value); + +/** +* Set the CoAP ack randomize factor +* +* A factor that is used to randomize the wait time before a message +* is retransmitted to prevent synchronization effects. +* +* @param session The CoAP session. +* @param value The value to set to. The default is 1.5 and should not normally +* get changed. +*/ +void coap_session_set_ack_random_factor(coap_session_t *session, + coap_fixed_point_t value); + +/** +* Get the CoAP maximum retransmit before failure +* +* Number of message retransmissions before message sending is stopped +* +* @param session The CoAP session. +* +* @return Current maximum retransmit value +*/ +unsigned int coap_session_get_max_transmit(coap_session_t *session); + +/** +* Get the CoAP initial ack response timeout before the next re-transmit +* +* Number of seconds when to expect an ACK or a response to an +* outstanding CON message. +* +* @param session The CoAP session. +* +* @return Current ack response timeout value +*/ +coap_fixed_point_t coap_session_get_ack_timeout(coap_session_t *session); + +/** +* Get the CoAP ack randomize factor +* +* A factor that is used to randomize the wait time before a message +* is retransmitted to prevent synchronization effects. +* +* @param session The CoAP session. +* +* @return Current ack randomize value +*/ +coap_fixed_point_t coap_session_get_ack_random_factor(coap_session_t *session); + +/** + * Send a ping message for the session. + * @param session The CoAP session. + * + * @return COAP_INVALID_TID if there is an error + */ +coap_tid_t coap_session_send_ping(coap_session_t *session); + +#endif /* COAP_SESSION_H */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_time.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_time.h new file mode 100644 index 00000000..e4a8e7c7 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/coap_time.h @@ -0,0 +1,162 @@ +/* + * coap_time.h -- Clock Handling + * + * Copyright (C) 2010-2019 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file coap_time.h + * @brief Clock Handling + */ + +#ifndef COAP_TIME_H_ +#define COAP_TIME_H_ + +/** + * @defgroup clock Clock Handling + * Default implementation of internal clock. + * @{ + */ + +#if defined(WITH_LWIP) + +#include +#include + +/* lwIP provides ms in sys_now */ +#define COAP_TICKS_PER_SECOND 1000 + +typedef uint32_t coap_tick_t; +typedef uint32_t coap_time_t; +typedef int32_t coap_tick_diff_t; + +COAP_STATIC_INLINE void coap_ticks_impl(coap_tick_t *t) { + *t = sys_now(); +} + +COAP_STATIC_INLINE void coap_clock_init_impl(void) { +} + +#define coap_clock_init coap_clock_init_impl +#define coap_ticks coap_ticks_impl + +COAP_STATIC_INLINE coap_time_t coap_ticks_to_rt(coap_tick_t t) { + return t / COAP_TICKS_PER_SECOND; +} + +#elif defined(WITH_CONTIKI) + +#include "clock.h" + +typedef clock_time_t coap_tick_t; +typedef clock_time_t coap_time_t; + +/** + * This data type is used to represent the difference between two clock_tick_t + * values. This data type must have the same size in memory as coap_tick_t to + * allow wrapping. + */ +typedef int coap_tick_diff_t; + +#define COAP_TICKS_PER_SECOND CLOCK_SECOND + +COAP_STATIC_INLINE void coap_clock_init(void) { + clock_init(); +} + +COAP_STATIC_INLINE void coap_ticks(coap_tick_t *t) { + *t = clock_time(); +} + +COAP_STATIC_INLINE coap_time_t coap_ticks_to_rt(coap_tick_t t) { + return t / COAP_TICKS_PER_SECOND; +} + +#else +#include + +/** + * This data type represents internal timer ticks with COAP_TICKS_PER_SECOND + * resolution. + */ +typedef uint64_t coap_tick_t; + +/** + * CoAP time in seconds since epoch. + */ +typedef time_t coap_time_t; + +/** + * This data type is used to represent the difference between two clock_tick_t + * values. This data type must have the same size in memory as coap_tick_t to + * allow wrapping. + */ +typedef int64_t coap_tick_diff_t; + +/** Use ms resolution on POSIX systems */ +#define COAP_TICKS_PER_SECOND ((coap_tick_t)(1000U)) + +/** + * Initializes the internal clock. + */ +void coap_clock_init(void); + +/** + * Sets @p t to the internal time with COAP_TICKS_PER_SECOND resolution. + */ +void coap_ticks(coap_tick_t *t); + +/** + * Helper function that converts coap ticks to wallclock time. On POSIX, this + * function returns the number of seconds since the epoch. On other systems, it + * may be the calculated number of seconds since last reboot or so. + * + * @param t Internal system ticks. + * + * @return The number of seconds that has passed since a specific reference + * point (seconds since epoch on POSIX). + */ +coap_time_t coap_ticks_to_rt(coap_tick_t t); + +/** +* Helper function that converts coap ticks to POSIX wallclock time in us. +* +* @param t Internal system ticks. +* +* @return The number of seconds that has passed since a specific reference +* point (seconds since epoch on POSIX). +*/ +uint64_t coap_ticks_to_rt_us(coap_tick_t t); + +/** +* Helper function that converts POSIX wallclock time in us to coap ticks. +* +* @param t POSIX time is us +* +* @return coap ticks +*/ +coap_tick_t coap_ticks_from_rt_us(uint64_t t); +#endif + +/** + * Returns @c 1 if and only if @p a is less than @p b where less is defined on a + * signed data type. + */ +COAP_STATIC_INLINE int coap_time_lt(coap_tick_t a, coap_tick_t b) { + return ((coap_tick_diff_t)(a - b)) < 0; +} + +/** + * Returns @c 1 if and only if @p a is less than or equal @p b where less is + * defined on a signed data type. + */ +COAP_STATIC_INLINE int coap_time_le(coap_tick_t a, coap_tick_t b) { + return a == b || coap_time_lt(a,b); +} + +/** @} */ + +#endif /* COAP_TIME_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/encode.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/encode.h new file mode 100644 index 00000000..b6d15244 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/encode.h @@ -0,0 +1,96 @@ +/* + * encode.h -- encoding and decoding of CoAP data types + * + * Copyright (C) 2010-2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_ENCODE_H_ +#define COAP_ENCODE_H_ + +#if (BSD >= 199103) || defined(WITH_CONTIKI) || defined(_WIN32) +# include +#else +# include +#endif + +#include + +#define Nn 8 /* duplicate definition of N if built on sky motes */ +#define ENCODE_HEADER_SIZE 4 +#define HIBIT (1 << (Nn - 1)) +#define EMASK ((1 << ENCODE_HEADER_SIZE) - 1) +#define MMASK ((1 << Nn) - 1 - EMASK) +#define MAX_VALUE ( (1 << Nn) - (1 << ENCODE_HEADER_SIZE) ) * (1 << ((1 << ENCODE_HEADER_SIZE) - 1)) + +#define COAP_PSEUDOFP_DECODE_8_4(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK)) + +#ifndef HAVE_FLS +/* include this only if fls() is not available */ +extern int coap_fls(unsigned int i); +#else +#define coap_fls(i) fls(i) +#endif + +#ifndef HAVE_FLSLL + /* include this only if flsll() is not available */ +extern int coap_flsll(long long i); +#else +#define coap_flsll(i) flsll(i) +#endif + +/* ls and s must be integer variables */ +#define COAP_PSEUDOFP_ENCODE_8_4_DOWN(v,ls) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (v >> ls) & MMASK) + ls) +#define COAP_PSEUDOFP_ENCODE_8_4_UP(v,ls,s) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (s = (((v + ((1<> ls) & MMASK)), s == 0 ? HIBIT + ls + 1 : s + ls)) + +/** + * Decodes multiple-length byte sequences. @p buf points to an input byte + * sequence of length @p length. Returns the decoded value. + * + * @param buf The input byte sequence to decode from + * @param length The length of the input byte sequence + * + * @return The decoded value + */ +unsigned int coap_decode_var_bytes(const uint8_t *buf, unsigned int length); + +/** + * Encodes multiple-length byte sequences. @p buf points to an output buffer of + * sufficient length to store the encoded bytes. @p value is the value to + * encode. + * Returns the number of bytes used to encode @p value or 0 on error. + * + * @param buf The output buffer to decode into + * @param length The output buffer size to encode into (must be sufficient) + * @param value The value to encode into the buffer + * + * @return The number of bytes used to encode @p value or @c 0 on error. + */ +unsigned int coap_encode_var_safe(uint8_t *buf, + size_t length, + unsigned int value); + +/** + * @deprecated Use coap_encode_var_safe() instead. + * Provided for backward compatibility. As @p value has a + * maximum value of 0xffffffff, and buf is usually defined as an array, it + * is unsafe to continue to use this variant if buf[] is less than buf[4]. + * + * For example + * char buf[1],oops; + * .. + * coap_encode_var_bytes(buf, 0xfff); + * would cause oops to get overwritten. This error can only be found by code + * inspection. + * coap_encode_var_safe(buf, sizeof(buf), 0xfff); + * would catch this error at run-time and should be used instead. + */ +COAP_STATIC_INLINE COAP_DEPRECATED int +coap_encode_var_bytes(uint8_t *buf, unsigned int value +) { + return (int)coap_encode_var_safe(buf, sizeof(value), value); +} + +#endif /* COAP_ENCODE_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/libcoap.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/libcoap.h new file mode 100644 index 00000000..77ba5db2 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/libcoap.h @@ -0,0 +1,54 @@ +/* + * libcoap.h -- platform specific header file for CoAP stack + * + * Copyright (C) 2015 Carsten Schoenert + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_LIBCOAP_H_ +#define COAP_LIBCOAP_H_ + +/* The non posix embedded platforms like Contiki, TinyOS, RIOT, ... doesn't have + * a POSIX compatible header structure so we have to slightly do some platform + * related things. Currently there is only Contiki available so we check for a + * CONTIKI environment and do *not* include the POSIX related network stuff. If + * there are other platforms in future there need to be analogous environments. + * + * The CONTIKI variable is within the Contiki build environment! */ + +#if defined(_WIN32) +#pragma comment(lib,"Ws2_32.lib") +#include +typedef SSIZE_T ssize_t; +typedef USHORT in_port_t; +#elif !defined (CONTIKI) +#include +#include +#endif /* CONTIKI */ + +#ifndef COAP_STATIC_INLINE +# if defined(__cplusplus) +# define COAP_STATIC_INLINE inline +# else +# if defined(_MSC_VER) +# define COAP_STATIC_INLINE static __inline +# else +# define COAP_STATIC_INLINE static inline +# endif +# endif +#endif +#ifndef COAP_DEPRECATED +# if defined(_MSC_VER) +# define COAP_DEPRECATED __declspec(deprecated) +# else +# define COAP_DEPRECATED __attribute__ ((deprecated)) +# endif +#endif + +void coap_startup(void); + +void coap_cleanup(void); + +#endif /* COAP_LIBCOAP_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/lwippools.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/lwippools.h new file mode 100644 index 00000000..cb90d809 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/lwippools.h @@ -0,0 +1,81 @@ +/* + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/* Memory pool definitions for the libcoap when used with lwIP (which has its + * own mechanism for quickly allocating chunks of data with known sizes). Has + * to be findable by lwIP (ie. an #include must either directly + * include this or include something more generic which includes this), and + * MEMP_USE_CUSTOM_POOLS has to be set in lwipopts.h. */ + +#include "coap_config.h" +#include +#include +#include + +#ifndef MEMP_NUM_COAPCONTEXT +#define MEMP_NUM_COAPCONTEXT 1 +#endif + +#ifndef MEMP_NUM_COAPENDPOINT +#define MEMP_NUM_COAPENDPOINT 1 +#endif + +/* 1 is sufficient as this is very short-lived */ +#ifndef MEMP_NUM_COAPPACKET +#define MEMP_NUM_COAPPACKET 1 +#endif + +#ifndef MEMP_NUM_COAPNODE +#define MEMP_NUM_COAPNODE 4 +#endif + +#ifndef MEMP_NUM_COAPPDU +#define MEMP_NUM_COAPPDU MEMP_NUM_COAPNODE +#endif + +#ifndef MEMP_NUM_COAPSESSION +#define MEMP_NUM_COAPSESSION 2 +#endif + +#ifndef MEMP_NUM_COAP_SUBSCRIPTION +#define MEMP_NUM_COAP_SUBSCRIPTION 4 +#endif + +#ifndef MEMP_NUM_COAPRESOURCE +#define MEMP_NUM_COAPRESOURCE 10 +#endif + +#ifndef MEMP_NUM_COAPRESOURCEATTR +#define MEMP_NUM_COAPRESOURCEATTR 20 +#endif + +#ifndef MEMP_NUM_COAPOPTLIST +#define MEMP_NUM_COAPOPTLIST 1 +#endif + +#ifndef MEMP_LEN_COAPOPTLIST +#define MEMP_LEN_COAPOPTLIST 12 +#endif + +#ifndef MEMP_NUM_COAPSTRING +#define MEMP_NUM_COAPSTRING 10 +#endif + +#ifndef MEMP_LEN_COAPSTRING +#define MEMP_LEN_COAPSTRING 32 +#endif + +LWIP_MEMPOOL(COAP_CONTEXT, MEMP_NUM_COAPCONTEXT, sizeof(coap_context_t), "COAP_CONTEXT") +LWIP_MEMPOOL(COAP_ENDPOINT, MEMP_NUM_COAPENDPOINT, sizeof(coap_endpoint_t), "COAP_ENDPOINT") +LWIP_MEMPOOL(COAP_PACKET, MEMP_NUM_COAPPACKET, sizeof(coap_packet_t), "COAP_PACKET") +LWIP_MEMPOOL(COAP_NODE, MEMP_NUM_COAPNODE, sizeof(coap_queue_t), "COAP_NODE") +LWIP_MEMPOOL(COAP_PDU, MEMP_NUM_COAPPDU, sizeof(coap_pdu_t), "COAP_PDU") +LWIP_MEMPOOL(COAP_SESSION, MEMP_NUM_COAPSESSION, sizeof(coap_session_t), "COAP_SESSION") +LWIP_MEMPOOL(COAP_subscription, MEMP_NUM_COAP_SUBSCRIPTION, sizeof(coap_subscription_t), "COAP_subscription") +LWIP_MEMPOOL(COAP_RESOURCE, MEMP_NUM_COAPRESOURCE, sizeof(coap_resource_t), "COAP_RESOURCE") +LWIP_MEMPOOL(COAP_RESOURCEATTR, MEMP_NUM_COAPRESOURCEATTR, sizeof(coap_attr_t), "COAP_RESOURCEATTR") +LWIP_MEMPOOL(COAP_OPTLIST, MEMP_NUM_COAPOPTLIST, sizeof(coap_optlist_t)+MEMP_LEN_COAPOPTLIST, "COAP_OPTLIST") +LWIP_MEMPOOL(COAP_STRING, MEMP_NUM_COAPSTRING, sizeof(coap_string_t)+MEMP_LEN_COAPSTRING, "COAP_STRING") + diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/mem.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/mem.h new file mode 100644 index 00000000..ea3c619f --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/mem.h @@ -0,0 +1,116 @@ +/* + * mem.h -- CoAP memory handling + * + * Copyright (C) 2010-2011,2014-2015 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_MEM_H_ +#define COAP_MEM_H_ + +#include + +#ifndef WITH_LWIP +/** + * Initializes libcoap's memory management. + * This function must be called once before coap_malloc() can be used on + * constrained devices. + */ +void coap_memory_init(void); +#endif /* WITH_LWIP */ + +/** + * Type specifiers for coap_malloc_type(). Memory objects can be typed to + * facilitate arrays of type objects to be used instead of dynamic memory + * management on constrained devices. + */ +typedef enum { + COAP_STRING, + COAP_ATTRIBUTE_NAME, + COAP_ATTRIBUTE_VALUE, + COAP_PACKET, + COAP_NODE, + COAP_CONTEXT, + COAP_ENDPOINT, + COAP_PDU, + COAP_PDU_BUF, + COAP_RESOURCE, + COAP_RESOURCEATTR, +#ifdef HAVE_LIBTINYDTLS + COAP_DTLS_SESSION, +#endif + COAP_SESSION, + COAP_OPTLIST, +} coap_memory_tag_t; + +#ifndef WITH_LWIP + +/** + * Allocates a chunk of @p size bytes and returns a pointer to the newly + * allocated memory. The @p type is used to select the appropriate storage + * container on constrained devices. The storage allocated by coap_malloc_type() + * must be released with coap_free_type(). + * + * @param type The type of object to be stored. + * @param size The number of bytes requested. + * @return A pointer to the allocated storage or @c NULL on error. + */ +void *coap_malloc_type(coap_memory_tag_t type, size_t size); + +/** + * Releases the memory that was allocated by coap_malloc_type(). The type tag @p + * type must be the same that was used for allocating the object pointed to by + * @p . + * + * @param type The type of the object to release. + * @param p A pointer to memory that was allocated by coap_malloc_type(). + */ +void coap_free_type(coap_memory_tag_t type, void *p); + +/** + * Wrapper function to coap_malloc_type() for backwards compatibility. + */ +COAP_STATIC_INLINE void *coap_malloc(size_t size) { + return coap_malloc_type(COAP_STRING, size); +} + +/** + * Wrapper function to coap_free_type() for backwards compatibility. + */ +COAP_STATIC_INLINE void coap_free(void *object) { + coap_free_type(COAP_STRING, object); +} + +#endif /* not WITH_LWIP */ + +#ifdef WITH_LWIP + +#include + +/* no initialization needed with lwip (or, more precisely: lwip must be + * completely initialized anyway by the time coap gets active) */ +COAP_STATIC_INLINE void coap_memory_init(void) {} + +/* It would be nice to check that size equals the size given at the memp + * declaration, but i currently don't see a standard way to check that without + * sourcing the custom memp pools and becoming dependent of its syntax + */ +#define coap_malloc_type(type, size) memp_malloc(MEMP_ ## type) +#define coap_free_type(type, p) memp_free(MEMP_ ## type, p) + +/* Those are just here to make uri.c happy where string allocation has not been + * made conditional. + */ +COAP_STATIC_INLINE void *coap_malloc(size_t size) { + LWIP_ASSERT("coap_malloc must not be used in lwIP", 0); +} + +COAP_STATIC_INLINE void coap_free(void *pointer) { + LWIP_ASSERT("coap_free must not be used in lwIP", 0); +} + +#endif /* WITH_LWIP */ + +#endif /* COAP_MEM_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/net.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/net.h new file mode 100644 index 00000000..7fccf332 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/net.h @@ -0,0 +1,746 @@ +/* + * net.h -- CoAP network interface + * + * Copyright (C) 2010-2015 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_NET_H_ +#define COAP_NET_H_ + +#include +#include +#include +#ifndef _WIN32 +#include +#endif +#include + +#ifdef WITH_LWIP +#include +#endif + +#include "coap_io.h" +#include "coap_dtls.h" +#include "coap_event.h" +#include "coap_time.h" +#include "option.h" +#include "pdu.h" +#include "prng.h" +#include "coap_session.h" + +struct coap_queue_t; + +/** + * Queue entry + */ +typedef struct coap_queue_t { + struct coap_queue_t *next; + coap_tick_t t; /**< when to send PDU for the next time */ + unsigned char retransmit_cnt; /**< retransmission counter, will be removed + * when zero */ + unsigned int timeout; /**< the randomized timeout value */ + coap_session_t *session; /**< the CoAP session */ + coap_tid_t id; /**< CoAP transaction id */ + coap_pdu_t *pdu; /**< the CoAP PDU to send */ +} coap_queue_t; + +/** + * Adds @p node to given @p queue, ordered by variable t in @p node. + * + * @param queue Queue to add to. + * @param node Node entry to add to Queue. + * + * @return @c 1 added to queue, @c 0 failure. + */ +int coap_insert_node(coap_queue_t **queue, coap_queue_t *node); + +/** + * Destroys specified @p node. + * + * @param node Node entry to remove. + * + * @return @c 1 node deleted from queue, @c 0 failure. + */ +int coap_delete_node(coap_queue_t *node); + +/** + * Removes all items from given @p queue and frees the allocated storage. + * + * @param queue The queue to delete. + */ +void coap_delete_all(coap_queue_t *queue); + +/** + * Creates a new node suitable for adding to the CoAP sendqueue. + * + * @return New node entry, or @c NULL if failure. + */ +coap_queue_t *coap_new_node(void); + +struct coap_resource_t; +struct coap_context_t; +#ifndef WITHOUT_ASYNC +struct coap_async_state_t; +#endif + +/** + * Response handler that is used as call-back in coap_context_t. + * + * @param context CoAP session. + * @param session CoAP session. + * @param sent The PDU that was transmitted. + * @param received The PDU that was received. + * @param id CoAP transaction ID. + */ +typedef void (*coap_response_handler_t)(struct coap_context_t *context, + coap_session_t *session, + coap_pdu_t *sent, + coap_pdu_t *received, + const coap_tid_t id); + +/** + * Negative Acknowedge handler that is used as call-back in coap_context_t. + * + * @param context CoAP session. + * @param session CoAP session. + * @param sent The PDU that was transmitted. + * @param reason The reason for the NACK. + * @param id CoAP transaction ID. + */ +typedef void (*coap_nack_handler_t)(struct coap_context_t *context, + coap_session_t *session, + coap_pdu_t *sent, + coap_nack_reason_t reason, + const coap_tid_t id); + +/** + * Recieved Ping handler that is used as call-back in coap_context_t. + * + * @param context CoAP session. + * @param session CoAP session. + * @param received The PDU that was received. + * @param id CoAP transaction ID. + */ +typedef void (*coap_ping_handler_t)(struct coap_context_t *context, + coap_session_t *session, + coap_pdu_t *received, + const coap_tid_t id); + +/** + * Recieved Pong handler that is used as call-back in coap_context_t. + * + * @param context CoAP session. + * @param session CoAP session. + * @param received The PDU that was received. + * @param id CoAP transaction ID. + */ +typedef void (*coap_pong_handler_t)(struct coap_context_t *context, + coap_session_t *session, + coap_pdu_t *received, + const coap_tid_t id); + +/** + * The CoAP stack's global state is stored in a coap_context_t object. + */ +typedef struct coap_context_t { + coap_opt_filter_t known_options; + struct coap_resource_t *resources; /**< hash table or list of known + resources */ + struct coap_resource_t *unknown_resource; /**< can be used for handling + unknown resources */ + +#ifndef WITHOUT_ASYNC + /** + * list of asynchronous transactions */ + struct coap_async_state_t *async_state; +#endif /* WITHOUT_ASYNC */ + + /** + * The time stamp in the first element of the sendqeue is relative + * to sendqueue_basetime. */ + coap_tick_t sendqueue_basetime; + coap_queue_t *sendqueue; + coap_endpoint_t *endpoint; /**< the endpoints used for listening */ + coap_session_t *sessions; /**< client sessions */ + +#ifdef WITH_CONTIKI + struct uip_udp_conn *conn; /**< uIP connection object */ + struct etimer retransmit_timer; /**< fires when the next packet must be sent */ + struct etimer notify_timer; /**< used to check resources periodically */ +#endif /* WITH_CONTIKI */ + +#ifdef WITH_LWIP + uint8_t timer_configured; /**< Set to 1 when a retransmission is + * scheduled using lwIP timers for this + * context, otherwise 0. */ +#endif /* WITH_LWIP */ + + coap_response_handler_t response_handler; + coap_nack_handler_t nack_handler; + coap_ping_handler_t ping_handler; + coap_pong_handler_t pong_handler; + + /** + * Callback function that is used to signal events to the + * application. This field is set by coap_set_event_handler(). + */ + coap_event_handler_t handle_event; + + ssize_t (*network_send)(coap_socket_t *sock, const coap_session_t *session, const uint8_t *data, size_t datalen); + + ssize_t (*network_read)(coap_socket_t *sock, struct coap_packet_t *packet); + + size_t(*get_client_psk)(const coap_session_t *session, const uint8_t *hint, size_t hint_len, uint8_t *identity, size_t *identity_len, size_t max_identity_len, uint8_t *psk, size_t max_psk_len); + size_t(*get_server_psk)(const coap_session_t *session, const uint8_t *identity, size_t identity_len, uint8_t *psk, size_t max_psk_len); + size_t(*get_server_hint)(const coap_session_t *session, uint8_t *hint, size_t max_hint_len); + + void *dtls_context; + uint8_t *psk_hint; + size_t psk_hint_len; + uint8_t *psk_key; + size_t psk_key_len; + + unsigned int session_timeout; /**< Number of seconds of inactivity after which an unused session will be closed. 0 means use default. */ + unsigned int max_idle_sessions; /**< Maximum number of simultaneous unused sessions per endpoint. 0 means no maximum. */ + unsigned int max_handshake_sessions; /**< Maximum number of simultaneous negotating sessions per endpoint. 0 means use default. */ + unsigned int ping_timeout; /**< Minimum inactivity time before sending a ping message. 0 means disabled. */ + unsigned int csm_timeout; /**< Timeout for waiting for a CSM from the remote side. 0 means disabled. */ + + void *app; /**< application-specific data */ +} coap_context_t; + +/** + * Registers a new message handler that is called whenever a response was + * received that matches an ongoing transaction. + * + * @param context The context to register the handler for. + * @param handler The response handler to register. + */ +COAP_STATIC_INLINE void +coap_register_response_handler(coap_context_t *context, + coap_response_handler_t handler) { + context->response_handler = handler; +} + +/** + * Registers a new message handler that is called whenever a confirmable + * message (request or response) is dropped after all retries have been + * exhausted, or a rst message was received, or a network or TLS level + * event was received that indicates delivering the message is not possible. + * + * @param context The context to register the handler for. + * @param handler The nack handler to register. + */ +COAP_STATIC_INLINE void +coap_register_nack_handler(coap_context_t *context, + coap_nack_handler_t handler) { + context->nack_handler = handler; +} + +/** + * Registers a new message handler that is called whenever a CoAP Ping + * message is received. + * + * @param context The context to register the handler for. + * @param handler The ping handler to register. + */ +COAP_STATIC_INLINE void +coap_register_ping_handler(coap_context_t *context, + coap_ping_handler_t handler) { + context->ping_handler = handler; +} + +/** + * Registers a new message handler that is called whenever a CoAP Pong + * message is received. + * + * @param context The context to register the handler for. + * @param handler The pong handler to register. + */ +COAP_STATIC_INLINE void +coap_register_pong_handler(coap_context_t *context, + coap_pong_handler_t handler) { + context->pong_handler = handler; +} + +/** + * Registers the option type @p type with the given context object @p ctx. + * + * @param ctx The context to use. + * @param type The option type to register. + */ +COAP_STATIC_INLINE void +coap_register_option(coap_context_t *ctx, uint16_t type) { + coap_option_setb(ctx->known_options, type); +} + +/** + * Set sendqueue_basetime in the given context object @p ctx to @p now. This + * function returns the number of elements in the queue head that have timed + * out. + */ +unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now); + +/** + * Returns the next pdu to send without removing from sendqeue. + */ +coap_queue_t *coap_peek_next( coap_context_t *context ); + +/** + * Returns the next pdu to send and removes it from the sendqeue. + */ +coap_queue_t *coap_pop_next( coap_context_t *context ); + +/** + * Creates a new coap_context_t object that will hold the CoAP stack status. + */ +coap_context_t *coap_new_context(const coap_address_t *listen_addr); + +/** + * Set the context's default PSK hint and/or key for a server. + * + * @param context The current coap_context_t object. + * @param hint The default PSK server hint sent to a client. If @p NULL, PSK + * authentication is disabled. Empty string is a valid hint. + * @param key The default PSK key. If @p NULL, PSK authentication will fail. + * @param key_len The default PSK key's length. If @p 0, PSK authentication will + * fail. + * + * @return @c 1 if successful, else @c 0. + */ +int coap_context_set_psk( coap_context_t *context, const char *hint, + const uint8_t *key, size_t key_len ); + +/** + * Set the context's default PKI information for a server. + * + * @param context The current coap_context_t object. + * @param setup_data If @p NULL, PKI authentication will fail. Certificate + * information required. + * + * @return @c 1 if successful, else @c 0. + */ +int +coap_context_set_pki(coap_context_t *context, + coap_dtls_pki_t *setup_data); + +/** + * Set the context's default Root CA information for a client or server. + * + * @param context The current coap_context_t object. + * @param ca_file If not @p NULL, is the full path name of a PEM encoded + * file containing all the Root CAs to be used. + * @param ca_dir If not @p NULL, points to a directory containing PEM + * encoded files containing all the Root CAs to be used. + * + * @return @c 1 if successful, else @c 0. + */ +int +coap_context_set_pki_root_cas(coap_context_t *context, + const char *ca_file, + const char *ca_dir); + +/** + * Set the context keepalive timer for sessions. + * A keepalive message will be sent after if a session has been inactive, + * i.e. no packet sent or received, for the given number of seconds. + * For reliable protocols, a PING message will be sent. If a PONG has not + * been received before the next PING is due to be sent, the session will + * considered as disconnected. + * + * @param context The coap_context_t object. + * @param seconds Number of seconds for the inactivity timer, or zero + * to disable CoAP-level keepalive messages. + * + * @return 1 if successful, else 0 + */ +void coap_context_set_keepalive(coap_context_t *context, unsigned int seconds); + +/** + * Returns a new message id and updates @p session->tx_mid accordingly. The + * message id is returned in network byte order to make it easier to read in + * tracing tools. + * + * @param session The current coap_session_t object. + * + * @return Incremented message id in network byte order. + */ +COAP_STATIC_INLINE uint16_t +coap_new_message_id(coap_session_t *session) { + return ++session->tx_mid; +} + +/** + * CoAP stack context must be released with coap_free_context(). This function + * clears all entries from the receive queue and send queue and deletes the + * resources that have been registered with @p context, and frees the attached + * endpoints. + * + * @param context The current coap_context_t object to free off. + */ +void coap_free_context(coap_context_t *context); + +/** + * Stores @p data with the given CoAP context. This function + * overwrites any value that has previously been stored with @p + * context. + * + * @param context The CoAP context. + * @param data The data to store with wih the context. Note that this data + * must be valid during the lifetime of @p context. + */ +void coap_set_app_data(coap_context_t *context, void *data); + +/** + * Returns any application-specific data that has been stored with @p + * context using the function coap_set_app_data(). This function will + * return @c NULL if no data has been stored. + * + * @param context The CoAP context. + * + * @return The data previously stored or @c NULL if not data stored. + */ +void *coap_get_app_data(const coap_context_t *context); + +/** + * Creates a new ACK PDU with specified error @p code. The options specified by + * the filter expression @p opts will be copied from the original request + * contained in @p request. Unless @c SHORT_ERROR_RESPONSE was defined at build + * time, the textual reason phrase for @p code will be added as payload, with + * Content-Type @c 0. + * This function returns a pointer to the new response message, or @c NULL on + * error. The storage allocated for the new message must be relased with + * coap_free(). + * + * @param request Specification of the received (confirmable) request. + * @param code The error code to set. + * @param opts An option filter that specifies which options to copy from + * the original request in @p node. + * + * @return A pointer to the new message or @c NULL on error. + */ +coap_pdu_t *coap_new_error_response(coap_pdu_t *request, + unsigned char code, + coap_opt_filter_t opts); + +/** + * Sends an error response with code @p code for request @p request to @p dst. + * @p opts will be passed to coap_new_error_response() to copy marked options + * from the request. This function returns the transaction id if the message was + * sent, or @c COAP_INVALID_TID otherwise. + * + * @param session The CoAP session. + * @param request The original request to respond to. + * @param code The response code. + * @param opts A filter that specifies the options to copy from the + * @p request. + * + * @return The transaction id if the message was sent, or @c + * COAP_INVALID_TID otherwise. + */ +coap_tid_t coap_send_error(coap_session_t *session, + coap_pdu_t *request, + unsigned char code, + coap_opt_filter_t opts); + +/** + * Helper funktion to create and send a message with @p type (usually ACK or + * RST). This function returns @c COAP_INVALID_TID when the message was not + * sent, a valid transaction id otherwise. + * + * @param session The CoAP session. + * @param request The request that should be responded to. + * @param type Which type to set. + * @return transaction id on success or @c COAP_INVALID_TID + * otherwise. + */ +coap_tid_t +coap_send_message_type(coap_session_t *session, coap_pdu_t *request, unsigned char type); + +/** + * Sends an ACK message with code @c 0 for the specified @p request to @p dst. + * This function returns the corresponding transaction id if the message was + * sent or @c COAP_INVALID_TID on error. + * + * @param session The CoAP session. + * @param request The request to be acknowledged. + * + * @return The transaction id if ACK was sent or @c + * COAP_INVALID_TID on error. + */ +coap_tid_t coap_send_ack(coap_session_t *session, coap_pdu_t *request); + +/** + * Sends an RST message with code @c 0 for the specified @p request to @p dst. + * This function returns the corresponding transaction id if the message was + * sent or @c COAP_INVALID_TID on error. + * + * @param session The CoAP session. + * @param request The request to be reset. + * + * @return The transaction id if RST was sent or @c + * COAP_INVALID_TID on error. + */ +COAP_STATIC_INLINE coap_tid_t +coap_send_rst(coap_session_t *session, coap_pdu_t *request) { + return coap_send_message_type(session, request, COAP_MESSAGE_RST); +} + +/** +* Sends a CoAP message to given peer. The memory that is +* allocated by pdu will be released by coap_send(). +* The caller must not use the pdu after calling coap_send(). +* +* @param session The CoAP session. +* @param pdu The CoAP PDU to send. +* +* @return The message id of the sent message or @c +* COAP_INVALID_TID on error. +*/ +coap_tid_t coap_send( coap_session_t *session, coap_pdu_t *pdu ); + +/** + * Handles retransmissions of confirmable messages + * + * @param context The CoAP context. + * @param node The node to retransmit. + * + * @return The message id of the sent message or @c + * COAP_INVALID_TID on error. + */ +coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node); + +/** +* For applications with their own message loop, send all pending retransmits and +* return the list of sockets with events to wait for and the next timeout +* The application should call coap_read, then coap_write again when any condition below is true: +* - data is available on any of the sockets with the COAP_SOCKET_WANT_READ +* - an incoming connection is pending in the listen queue and the COAP_SOCKET_WANT_ACCEPT flag is set +* - at least some data can be written without blocking on any of the sockets with the COAP_SOCKET_WANT_WRITE flag set +* - a connection event occured (success or failure) and the COAP_SOCKET_WANT_CONNECT flag is set +* - the timeout has expired +* Before calling coap_read or coap_write again, the application should position COAP_SOCKET_CAN_READ and COAP_SOCKET_CAN_WRITE flags as applicable. +* +* @param ctx The CoAP context +* @param sockets array of socket descriptors, filled on output +* @param max_sockets size of socket array. +* @param num_sockets pointer to the number of valid entries in the socket arrays on output +* @param now Current time. +* +* @return timeout as maxmimum number of milliseconds that the application should wait for network events or 0 if the application should wait forever. +*/ + +unsigned int +coap_write(coap_context_t *ctx, + coap_socket_t *sockets[], + unsigned int max_sockets, + unsigned int *num_sockets, + coap_tick_t now +); + +/** + * For applications with their own message loop, reads all data from the network. + * + * @param ctx The CoAP context + * @param now Current time + */ +void coap_read(coap_context_t *ctx, coap_tick_t now); + +/** + * The main message processing loop. + * + * @param ctx The CoAP context + * @param timeout_ms Minimum number of milliseconds to wait for new messages before returning. If zero the call will block until at least one packet is sent or received. + * + * @return number of milliseconds spent or @c -1 if there was an error + */ + +int coap_run_once( coap_context_t *ctx, unsigned int timeout_ms ); + +/** + * Parses and interprets a CoAP datagram with context @p ctx. This function + * returns @c 0 if the datagram was handled, or a value less than zero on + * error. + * + * @param ctx The current CoAP context. + * @param session The current CoAP session. + * @param data The received packet'd data. + * @param data_len The received packet'd data length. + * + * @return @c 0 if message was handled successfully, or less than zero on + * error. + */ +int coap_handle_dgram(coap_context_t *ctx, coap_session_t *session, uint8_t *data, size_t data_len); + +/** + * Invokes the event handler of @p context for the given @p event and + * @p data. + * + * @param context The CoAP context whose event handler is to be called. + * @param event The event to deliver. + * @param session The session related to @p event. + * @return The result from the associated event handler or 0 if none was + * registered. + */ +int coap_handle_event(coap_context_t *context, + coap_event_t event, + coap_session_t *session); +/** + * This function removes the element with given @p id from the list given list. + * If @p id was found, @p node is updated to point to the removed element. Note + * that the storage allocated by @p node is @b not released. The caller must do + * this manually using coap_delete_node(). This function returns @c 1 if the + * element with id @p id was found, @c 0 otherwise. For a return value of @c 0, + * the contents of @p node is undefined. + * + * @param queue The queue to search for @p id. + * @param session The session to look for. + * @param id The transaction id to look for. + * @param node If found, @p node is updated to point to the removed node. You + * must release the storage pointed to by @p node manually. + * + * @return @c 1 if @p id was found, @c 0 otherwise. + */ +int coap_remove_from_queue(coap_queue_t **queue, + coap_session_t *session, + coap_tid_t id, + coap_queue_t **node); + +coap_tid_t +coap_wait_ack( coap_context_t *context, coap_session_t *session, + coap_queue_t *node); + +/** + * Retrieves transaction from the queue. + * + * @param queue The transaction queue to be searched. + * @param session The session to find. + * @param id The transaction id to find. + * + * @return A pointer to the transaction object or @c NULL if not found. + */ +coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_session_t *session, coap_tid_t id); + +/** + * Cancels all outstanding messages for session @p session that have the specified + * token. + * + * @param context The context in use. + * @param session Session of the messages to remove. + * @param token Message token. + * @param token_length Actual length of @p token. + */ +void coap_cancel_all_messages(coap_context_t *context, + coap_session_t *session, + const uint8_t *token, + size_t token_length); + +/** +* Cancels all outstanding messages for session @p session. +* +* @param context The context in use. +* @param session Session of the messages to remove. +* @param reason The reasion for the session cancellation +*/ +void +coap_cancel_session_messages(coap_context_t *context, + coap_session_t *session, + coap_nack_reason_t reason); + +/** + * Dispatches the PDUs from the receive queue in given context. + */ +void coap_dispatch(coap_context_t *context, coap_session_t *session, + coap_pdu_t *pdu); + +/** + * Returns 1 if there are no messages to send or to dispatch in the context's + * queues. */ +int coap_can_exit(coap_context_t *context); + +/** + * Returns the current value of an internal tick counter. The counter counts \c + * COAP_TICKS_PER_SECOND ticks every second. + */ +void coap_ticks(coap_tick_t *); + +/** + * Verifies that @p pdu contains no unknown critical options. Options must be + * registered at @p ctx, using the function coap_register_option(). A basic set + * of options is registered automatically by coap_new_context(). This function + * returns @c 1 if @p pdu is ok, @c 0 otherwise. The given filter object @p + * unknown will be updated with the unknown options. As only @c COAP_MAX_OPT + * options can be signalled this way, remaining options must be examined + * manually. + * + * @code + coap_opt_filter_t f = COAP_OPT_NONE; + coap_opt_iterator_t opt_iter; + + if (coap_option_check_critical(ctx, pdu, f) == 0) { + coap_option_iterator_init(pdu, &opt_iter, f); + + while (coap_option_next(&opt_iter)) { + if (opt_iter.type & 0x01) { + ... handle unknown critical option in opt_iter ... + } + } + } + @endcode + * + * @param ctx The context where all known options are registered. + * @param pdu The PDU to check. + * @param unknown The output filter that will be updated to indicate the + * unknown critical options found in @p pdu. + * + * @return @c 1 if everything was ok, @c 0 otherwise. + */ +int coap_option_check_critical(coap_context_t *ctx, + coap_pdu_t *pdu, + coap_opt_filter_t unknown); + +/** + * Creates a new response for given @p request with the contents of @c + * .well-known/core. The result is NULL on error or a newly allocated PDU that + * must be either sent with coap_sent() or released by coap_delete_pdu(). + * + * @param context The current coap context to use. + * @param session The CoAP session. + * @param request The request for @c .well-known/core . + * + * @return A new 2.05 response for @c .well-known/core or NULL on error. + */ +coap_pdu_t *coap_wellknown_response(coap_context_t *context, + coap_session_t *session, + coap_pdu_t *request); + +/** + * Calculates the initial timeout based on the session CoAP transmission + * parameters 'ack_timeout', 'ack_random_factor', and COAP_TICKS_PER_SECOND. + * The calculation requires 'ack_timeout' and 'ack_random_factor' to be in + * Qx.FRAC_BITS fixed point notation, whereas the passed parameter @p r + * is interpreted as the fractional part of a Q0.MAX_BITS random value. + * + * @param session session timeout is associated with + * @param r random value as fractional part of a Q0.MAX_BITS fixed point + * value + * @return COAP_TICKS_PER_SECOND * 'ack_timeout' * + * (1 + ('ack_random_factor' - 1) * r) + */ +unsigned int coap_calc_timeout(coap_session_t *session, unsigned char r); + +/** + * Function interface for joining a multicast group for listening + * + * @param ctx The current context + * @param groupname The name of the group that is to be joined for listening + * + * @return 0 on success, -1 on error + */ +int +coap_join_mcast_group(coap_context_t *ctx, const char *groupname); + +#endif /* COAP_NET_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/option.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/option.h new file mode 100644 index 00000000..3af9e71e --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/option.h @@ -0,0 +1,461 @@ +/* + * option.h -- helpers for handling options in CoAP PDUs + * + * Copyright (C) 2010-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file option.h + * @brief Helpers for handling options in CoAP PDUs + */ + +#ifndef COAP_OPTION_H_ +#define COAP_OPTION_H_ + +#include "bits.h" +#include "pdu.h" + +/** + * Use byte-oriented access methods here because sliding a complex struct + * coap_opt_t over the data buffer may cause bus error on certain platforms. + */ +typedef uint8_t coap_opt_t; +#define PCHAR(p) ((coap_opt_t *)(p)) + +/** + * Representation of CoAP options. + */ +typedef struct { + uint16_t delta; + size_t length; + const uint8_t *value; +} coap_option_t; + +/** + * Parses the option pointed to by @p opt into @p result. This function returns + * the number of bytes that have been parsed, or @c 0 on error. An error is + * signaled when illegal delta or length values are encountered or when option + * parsing would result in reading past the option (i.e. beyond opt + length). + * + * @param opt The beginning of the option to parse. + * @param length The maximum length of @p opt. + * @param result A pointer to the coap_option_t structure that is filled with + * actual values iff coap_opt_parse() > 0. + * @return The number of bytes parsed or @c 0 on error. + */ +size_t coap_opt_parse(const coap_opt_t *opt, + size_t length, + coap_option_t *result); + +/** + * Returns the size of the given option, taking into account a possible option + * jump. + * + * @param opt An option jump or the beginning of the option. + * @return The number of bytes between @p opt and the end of the option + * starting at @p opt. In case of an error, this function returns + * @c 0 as options need at least one byte storage space. + */ +size_t coap_opt_size(const coap_opt_t *opt); + +/** + * @defgroup opt_filter Option Filters + * API functions for access option filters + * @{ + */ + +/** + * The number of option types below 256 that can be stored in an + * option filter. COAP_OPT_FILTER_SHORT + COAP_OPT_FILTER_LONG must be + * at most 16. Each coap_option_filter_t object reserves + * ((COAP_OPT_FILTER_SHORT + 1) / 2) * 2 bytes for short options. + */ +#define COAP_OPT_FILTER_SHORT 6 + +/** + * The number of option types above 255 that can be stored in an + * option filter. COAP_OPT_FILTER_SHORT + COAP_OPT_FILTER_LONG must be + * at most 16. Each coap_option_filter_t object reserves + * COAP_OPT_FILTER_LONG * 2 bytes for short options. + */ +#define COAP_OPT_FILTER_LONG 2 + +/* Ensure that COAP_OPT_FILTER_SHORT and COAP_OPT_FILTER_LONG are set + * correctly. */ +#if (COAP_OPT_FILTER_SHORT + COAP_OPT_FILTER_LONG > 16) +#error COAP_OPT_FILTER_SHORT + COAP_OPT_FILTER_LONG must be less or equal 16 +#endif /* (COAP_OPT_FILTER_SHORT + COAP_OPT_FILTER_LONG > 16) */ + +/** The number of elements in coap_opt_filter_t. */ +#define COAP_OPT_FILTER_SIZE \ + (((COAP_OPT_FILTER_SHORT + 1) >> 1) + COAP_OPT_FILTER_LONG) +1 + +/** + * Fixed-size vector we use for option filtering. It is large enough + * to hold COAP_OPT_FILTER_SHORT entries with an option number between + * 0 and 255, and COAP_OPT_FILTER_LONG entries with an option number + * between 256 and 65535. Its internal structure is + * + * @code +struct { + uint16_t mask; + uint16_t long_opts[COAP_OPT_FILTER_LONG]; + uint8_t short_opts[COAP_OPT_FILTER_SHORT]; +} + * @endcode + * + * The first element contains a bit vector that indicates which fields + * in the remaining array are used. The first COAP_OPT_FILTER_LONG + * bits correspond to the long option types that are stored in the + * elements from index 1 to COAP_OPT_FILTER_LONG. The next + * COAP_OPT_FILTER_SHORT bits correspond to the short option types + * that are stored in the elements from index COAP_OPT_FILTER_LONG + 1 + * to COAP_OPT_FILTER_LONG + COAP_OPT_FILTER_SHORT. The latter + * elements are treated as bytes. + */ +typedef uint16_t coap_opt_filter_t[COAP_OPT_FILTER_SIZE]; + +/** Pre-defined filter that includes all options. */ +#define COAP_OPT_ALL NULL + +/** + * Clears filter @p f. + * + * @param f The filter to clear. + */ +COAP_STATIC_INLINE void +coap_option_filter_clear(coap_opt_filter_t f) { + memset(f, 0, sizeof(coap_opt_filter_t)); +} + +/** + * Sets the corresponding entry for @p type in @p filter. This + * function returns @c 1 if bit was set or @c 0 on error (i.e. when + * the given type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type for which the bit should be set. + * + * @return @c 1 if bit was set, @c 0 otherwise. + */ +int coap_option_filter_set(coap_opt_filter_t filter, uint16_t type); + +/** + * Clears the corresponding entry for @p type in @p filter. This + * function returns @c 1 if bit was set or @c 0 on error (i.e. when + * the given type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type that should be cleared from the filter. + * + * @return @c 1 if bit was set, @c 0 otherwise. + */ +int coap_option_filter_unset(coap_opt_filter_t filter, uint16_t type); + +/** + * Checks if @p type is contained in @p filter. This function returns + * @c 1 if found, @c 0 if not, or @c -1 on error (i.e. when the given + * type does not fit in the filter). + * + * @param filter The filter object to search. + * @param type The type to search for. + * + * @return @c 1 if @p type was found, @c 0 otherwise, or @c -1 on error. + */ +int coap_option_filter_get(coap_opt_filter_t filter, uint16_t type); + +/** + * Sets the corresponding bit for @p type in @p filter. This function returns @c + * 1 if bit was set or @c -1 on error (i.e. when the given type does not fit in + * the filter). + * + * @deprecated Use coap_option_filter_set() instead. + * + * @param filter The filter object to change. + * @param type The type for which the bit should be set. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +COAP_STATIC_INLINE int +coap_option_setb(coap_opt_filter_t filter, uint16_t type) { + return coap_option_filter_set(filter, type) ? 1 : -1; +} + +/** + * Clears the corresponding bit for @p type in @p filter. This function returns + * @c 1 if bit was cleared or @c -1 on error (i.e. when the given type does not + * fit in the filter). + * + * @deprecated Use coap_option_filter_unset() instead. + * + * @param filter The filter object to change. + * @param type The type for which the bit should be cleared. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +COAP_STATIC_INLINE int +coap_option_clrb(coap_opt_filter_t filter, uint16_t type) { + return coap_option_filter_unset(filter, type) ? 1 : -1; +} + +/** + * Gets the corresponding bit for @p type in @p filter. This function returns @c + * 1 if the bit is set @c 0 if not, or @c -1 on error (i.e. when the given type + * does not fit in the filter). + * + * @deprecated Use coap_option_filter_get() instead. + * + * @param filter The filter object to read bit from. + * @param type The type for which the bit should be read. + * + * @return @c 1 if bit was set, @c 0 if not, @c -1 on error. + */ +COAP_STATIC_INLINE int +coap_option_getb(coap_opt_filter_t filter, uint16_t type) { + return coap_option_filter_get(filter, type); +} + +/** + * Iterator to run through PDU options. This object must be + * initialized with coap_option_iterator_init(). Call + * coap_option_next() to walk through the list of options until + * coap_option_next() returns @c NULL. + * + * @code + * coap_opt_t *option; + * coap_opt_iterator_t opt_iter; + * coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL); + * + * while ((option = coap_option_next(&opt_iter))) { + * ... do something with option ... + * } + * @endcode + */ +typedef struct { + size_t length; /**< remaining length of PDU */ + uint16_t type; /**< decoded option type */ + unsigned int bad:1; /**< iterator object is ok if not set */ + unsigned int filtered:1; /**< denotes whether or not filter is used */ + coap_opt_t *next_option; /**< pointer to the unparsed next option */ + coap_opt_filter_t filter; /**< option filter */ +} coap_opt_iterator_t; + +/** + * Initializes the given option iterator @p oi to point to the beginning of the + * @p pdu's option list. This function returns @p oi on success, @c NULL + * otherwise (i.e. when no options exist). Note that a length check on the + * option list must be performed before coap_option_iterator_init() is called. + * + * @param pdu The PDU the options of which should be walked through. + * @param oi An iterator object that will be initilized. + * @param filter An optional option type filter. + * With @p type != @c COAP_OPT_ALL, coap_option_next() + * will return only options matching this bitmask. + * Fence-post options @c 14, @c 28, @c 42, ... are always + * skipped. + * + * @return The iterator object @p oi on success, @c NULL otherwise. + */ +coap_opt_iterator_t *coap_option_iterator_init(const coap_pdu_t *pdu, + coap_opt_iterator_t *oi, + const coap_opt_filter_t filter); + +/** + * Updates the iterator @p oi to point to the next option. This function returns + * a pointer to that option or @c NULL if no more options exist. The contents of + * @p oi will be updated. In particular, @c oi->n specifies the current option's + * ordinal number (counted from @c 1), @c oi->type is the option's type code, + * and @c oi->option points to the beginning of the current option itself. When + * advanced past the last option, @c oi->option will be @c NULL. + * + * Note that options are skipped whose corresponding bits in the filter + * specified with coap_option_iterator_init() are @c 0. Options with type codes + * that do not fit in this filter hence will always be returned. + * + * @param oi The option iterator to update. + * + * @return The next option or @c NULL if no more options exist. + */ +coap_opt_t *coap_option_next(coap_opt_iterator_t *oi); + +/** + * Retrieves the first option of type @p type from @p pdu. @p oi must point to a + * coap_opt_iterator_t object that will be initialized by this function to + * filter only options with code @p type. This function returns the first option + * with this type, or @c NULL if not found. + * + * @param pdu The PDU to parse for options. + * @param type The option type code to search for. + * @param oi An iterator object to use. + * + * @return A pointer to the first option of type @p type, or @c NULL if + * not found. + */ +coap_opt_t *coap_check_option(coap_pdu_t *pdu, + uint16_t type, + coap_opt_iterator_t *oi); + +/** + * Encodes the given delta and length values into @p opt. This function returns + * the number of bytes that were required to encode @p delta and @p length or @c + * 0 on error. Note that the result indicates by how many bytes @p opt must be + * advanced to encode the option value. + * + * @param opt The option buffer space where @p delta and @p length are + * written. + * @param maxlen The maximum length of @p opt. + * @param delta The actual delta value to encode. + * @param length The actual length value to encode. + * + * @return The number of bytes used or @c 0 on error. + */ +size_t coap_opt_setheader(coap_opt_t *opt, + size_t maxlen, + uint16_t delta, + size_t length); + +/** + * Compute storage bytes needed for an option with given @p delta and + * @p length + * + * @param delta The option delta. + * @param length The option length. + * + * @return The number of bytes required to encode this option. + */ +size_t coap_opt_encode_size(uint16_t delta, size_t length); + +/** + * Encodes option with given @p delta into @p opt. This function returns the + * number of bytes written to @p opt or @c 0 on error. This happens especially + * when @p opt does not provide sufficient space to store the option value, + * delta, and option jumps when required. + * + * @param opt The option buffer space where @p val is written. + * @param n Maximum length of @p opt. + * @param delta The option delta. + * @param val The option value to copy into @p opt. + * @param length The actual length of @p val. + * + * @return The number of bytes that have been written to @p opt or @c 0 on + * error. The return value will always be less than @p n. + */ +size_t coap_opt_encode(coap_opt_t *opt, + size_t n, + uint16_t delta, + const uint8_t *val, + size_t length); + +/** + * Decodes the delta value of the next option. This function returns the number + * of bytes read or @c 0 on error. The caller of this function must ensure that + * it does not read over the boundaries of @p opt (e.g. by calling + * coap_opt_check_delta(). + * + * @param opt The option to examine. + * + * @return The number of bytes read or @c 0 on error. + */ +uint16_t coap_opt_delta(const coap_opt_t *opt); + +/** + * Returns the length of the given option. @p opt must point to an option jump + * or the beginning of the option. This function returns @c 0 when @p opt is not + * an option or the actual length of @p opt (which can be @c 0 as well). + * + * @note {The rationale for using @c 0 in case of an error is that in most + * contexts, the result of this function is used to skip the next + * coap_opt_length() bytes.} + * + * @param opt The option whose length should be returned. + * + * @return The option's length or @c 0 when undefined. + */ +uint16_t coap_opt_length(const coap_opt_t *opt); + +/** + * Returns a pointer to the value of the given option. @p opt must point to an + * option jump or the beginning of the option. This function returns @c NULL if + * @p opt is not a valid option. + * + * @param opt The option whose value should be returned. + * + * @return A pointer to the option value or @c NULL on error. + */ +const uint8_t *coap_opt_value(const coap_opt_t *opt); + +/** @} */ + +/** + * Representation of chained list of CoAP options to install. + * + * @code + * coap_optlist_t *optlist_chain = NULL; + * coap_pdu_t *pdu = coap_new_pdu(session); + * + * ... other set up code ... + * coap_insert_optlist(&optlist_chain, coap_new_optlist(COAP_OPTION_OBSERVE, + * COAP_OBSERVE_ESTABLISH, NULL)); + * + * coap_add_optlist_pdu(pdu, &optlist_chain); + * ... other code ... + * coap_delete_optlist(optlist_chain); + * @endcode + */ +typedef struct coap_optlist_t { + struct coap_optlist_t *next; /**< next entry in the optlist chain */ + uint16_t number; /**< the option number (no delta coding) */ + size_t length; /**< the option value length */ + uint8_t *data; /**< the option data */ +} coap_optlist_t; + +/** + * Create a new optlist entry. + * + * @param number The option number (COAP_OPTION_*) + * @param length The option length + * @param data The option value data + * + * @return A pointer to the new optlist entry, or @c NULL if error + */ +coap_optlist_t *coap_new_optlist(uint16_t number, + size_t length, + const uint8_t *data); + +/** + * The current optlist of @p optlist_chain is first sorted (as per RFC7272 + * ordering requirements) and then added to the @p pdu. + * + * @param pdu The pdu to add the options to from the chain list + * @param optlist_chain The chained list of optlist to add to the pdu + * + * @return @c 1 if succesful or @c 0 if failure; + */ +int coap_add_optlist_pdu(coap_pdu_t *pdu, coap_optlist_t** optlist_chain); + +/** + * Adds @p optlist to the given @p optlist_chain. The optlist_chain variable + * be set to NULL before the initial call to coap_insert_optlist(). + * The optlist_chain will need to be deleted using coap_delete_optlist() + * when no longer required. + * + * @param optlist_chain The chain to add optlist to + * @param optlist The optlist to add to the queue + * + * @return @c 1 if successful, @c 0 otherwise. + */ +int coap_insert_optlist(coap_optlist_t **optlist_chain, + coap_optlist_t *optlist); + +/** + * Removes all entries from the @p optlist_chain, freeing off their + * memory usage. + * + * @param optlist_chain The optlist chain to remove all the entries from + */ +void coap_delete_optlist(coap_optlist_t *optlist_chain); + +#endif /* COAP_OPTION_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/pdu.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/pdu.h new file mode 100644 index 00000000..206e2643 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/pdu.h @@ -0,0 +1,543 @@ +/* + * pdu.h -- CoAP message structure + * + * Copyright (C) 2010-2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file pdu.h + * @brief Pre-defined constants that reflect defaults for CoAP + */ + +#ifndef COAP_PDU_H_ +#define COAP_PDU_H_ + +#include "uri.h" + +struct coap_session_t; + +#ifdef WITH_LWIP +#include +#endif + +#include + +#define COAP_DEFAULT_PORT 5683 /* CoAP default UDP/TCP port */ +#define COAPS_DEFAULT_PORT 5684 /* CoAP default UDP/TCP port for secure transmission */ +#define COAP_DEFAULT_MAX_AGE 60 /* default maximum object lifetime in seconds */ +#ifndef COAP_DEFAULT_MTU +#define COAP_DEFAULT_MTU 1152 +#endif /* COAP_DEFAULT_MTU */ + +/* TCP Message format constants, do not modify */ +#define COAP_MESSAGE_SIZE_OFFSET_TCP8 13 +#define COAP_MESSAGE_SIZE_OFFSET_TCP16 269 /* 13 + 256 */ +#define COAP_MESSAGE_SIZE_OFFSET_TCP32 65805 /* 269 + 65536 */ + +/* Derived message size limits */ +#define COAP_MAX_MESSAGE_SIZE_TCP0 (COAP_MESSAGE_SIZE_OFFSET_TCP8-1) /* 12 */ +#define COAP_MAX_MESSAGE_SIZE_TCP8 (COAP_MESSAGE_SIZE_OFFSET_TCP16-1) /* 268 */ +#define COAP_MAX_MESSAGE_SIZE_TCP16 (COAP_MESSAGE_SIZE_OFFSET_TCP32-1) /* 65804 */ +#define COAP_MAX_MESSAGE_SIZE_TCP32 (COAP_MESSAGE_SIZE_OFFSET_TCP32+0xFFFFFFFF) + +#ifndef COAP_DEFAULT_MAX_PDU_RX_SIZE +#if defined(WITH_CONTIKI) || defined(WITH_LWIP) +#define COAP_DEFAULT_MAX_PDU_RX_SIZE (COAP_MAX_MESSAGE_SIZE_TCP16+4) +#else +/* 8 MiB max-message-size plus some space for options */ +#define COAP_DEFAULT_MAX_PDU_RX_SIZE (8*1024*1024+256) +#endif +#endif /* COAP_DEFAULT_MAX_PDU_RX_SIZE */ + +#ifndef COAP_DEBUG_BUF_SIZE +#if defined(WITH_CONTIKI) || defined(WITH_LWIP) +#define COAP_DEBUG_BUF_SIZE 128 +#else /* defined(WITH_CONTIKI) || defined(WITH_LWIP) */ +/* 1024 derived from RFC7252 4.6. Message Size max payload */ +#define COAP_DEBUG_BUF_SIZE (8 + 1024 * 2) +#endif /* defined(WITH_CONTIKI) || defined(WITH_LWIP) */ +#endif /* COAP_DEBUG_BUF_SIZE */ + +#define COAP_DEFAULT_VERSION 1 /* version of CoAP supported */ +#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */ + +/** well-known resources URI */ +#define COAP_DEFAULT_URI_WELLKNOWN ".well-known/core" + +/* CoAP message types */ + +#define COAP_MESSAGE_CON 0 /* confirmable message (requires ACK/RST) */ +#define COAP_MESSAGE_NON 1 /* non-confirmable message (one-shot message) */ +#define COAP_MESSAGE_ACK 2 /* used to acknowledge confirmable messages */ +#define COAP_MESSAGE_RST 3 /* indicates error in received messages */ + +/* CoAP request methods */ + +#define COAP_REQUEST_GET 1 +#define COAP_REQUEST_POST 2 +#define COAP_REQUEST_PUT 3 +#define COAP_REQUEST_DELETE 4 +#define COAP_REQUEST_FETCH 5 /* RFC 8132 */ +#define COAP_REQUEST_PATCH 6 /* RFC 8132 */ +#define COAP_REQUEST_IPATCH 7 /* RFC 8132 */ + +/* + * CoAP option types (be sure to update coap_option_check_critical() when + * adding options + */ + +#define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */ +#define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */ +#define COAP_OPTION_ETAG 4 /* E, opaque, 1-8 B, (none) */ +#define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */ +#define COAP_OPTION_URI_PORT 7 /* C, uint, 0-2 B, destination port */ +#define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */ +#define COAP_OPTION_URI_PATH 11 /* C, String, 0-255 B, (none) */ +#define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */ +#define COAP_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT +#define COAP_OPTION_MAXAGE 14 /* E, uint, 0--4 B, 60 Seconds */ +#define COAP_OPTION_URI_QUERY 15 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_ACCEPT 17 /* C, uint, 0-2 B, (none) */ +#define COAP_OPTION_LOCATION_QUERY 20 /* E, String, 0-255 B, (none) */ +#define COAP_OPTION_SIZE2 28 /* E, uint, 0-4 B, (none) */ +#define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1034 B, (none) */ +#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */ + +/* option types from RFC 7641 */ + +#define COAP_OPTION_OBSERVE 6 /* E, empty/uint, 0 B/0-3 B, (none) */ +#define COAP_OPTION_SUBSCRIPTION COAP_OPTION_OBSERVE + +/* selected option types from RFC 7959 */ + +#define COAP_OPTION_BLOCK2 23 /* C, uint, 0--3 B, (none) */ +#define COAP_OPTION_BLOCK1 27 /* C, uint, 0--3 B, (none) */ + +/* selected option types from RFC 7967 */ + +#define COAP_OPTION_NORESPONSE 258 /* N, uint, 0--1 B, 0 */ + +#define COAP_MAX_OPT 65535 /**< the highest option number we know */ + +/* CoAP result codes (HTTP-Code / 100 * 40 + HTTP-Code % 100) */ + +/* As of draft-ietf-core-coap-04, response codes are encoded to base + * 32, i.e. the three upper bits determine the response class while + * the remaining five fine-grained information specific to that class. + */ +#define COAP_RESPONSE_CODE(N) (((N)/100 << 5) | (N)%100) + +/* Determines the class of response code C */ +#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF) + +#ifndef SHORT_ERROR_RESPONSE +/** + * Returns a human-readable response phrase for the specified CoAP response @p + * code. This function returns @c NULL if not found. + * + * @param code The response code for which the literal phrase should be + * retrieved. + * + * @return A zero-terminated string describing the error, or @c NULL if not + * found. + */ +const char *coap_response_phrase(unsigned char code); + +#define COAP_ERROR_PHRASE_LENGTH 32 /**< maximum length of error phrase */ + +#else +#define coap_response_phrase(x) ((char *)NULL) + +#define COAP_ERROR_PHRASE_LENGTH 0 /**< maximum length of error phrase */ +#endif /* SHORT_ERROR_RESPONSE */ + +/* The following definitions exist for backwards compatibility */ +#if 0 /* this does not exist any more */ +#define COAP_RESPONSE_100 40 /* 100 Continue */ +#endif +#define COAP_RESPONSE_200 COAP_RESPONSE_CODE(200) /* 2.00 OK */ +#define COAP_RESPONSE_201 COAP_RESPONSE_CODE(201) /* 2.01 Created */ +#define COAP_RESPONSE_304 COAP_RESPONSE_CODE(203) /* 2.03 Valid */ +#define COAP_RESPONSE_400 COAP_RESPONSE_CODE(400) /* 4.00 Bad Request */ +#define COAP_RESPONSE_404 COAP_RESPONSE_CODE(404) /* 4.04 Not Found */ +#define COAP_RESPONSE_405 COAP_RESPONSE_CODE(405) /* 4.05 Method Not Allowed */ +#define COAP_RESPONSE_415 COAP_RESPONSE_CODE(415) /* 4.15 Unsupported Media Type */ +#define COAP_RESPONSE_500 COAP_RESPONSE_CODE(500) /* 5.00 Internal Server Error */ +#define COAP_RESPONSE_501 COAP_RESPONSE_CODE(501) /* 5.01 Not Implemented */ +#define COAP_RESPONSE_503 COAP_RESPONSE_CODE(503) /* 5.03 Service Unavailable */ +#define COAP_RESPONSE_504 COAP_RESPONSE_CODE(504) /* 5.04 Gateway Timeout */ +#if 0 /* these response codes do not have a valid code any more */ +# define COAP_RESPONSE_X_240 240 /* Token Option required by server */ +# define COAP_RESPONSE_X_241 241 /* Uri-Authority Option required by server */ +#endif +#define COAP_RESPONSE_X_242 COAP_RESPONSE_CODE(402) /* Critical Option not supported */ + +#define COAP_SIGNALING_CODE(N) (((N)/100 << 5) | (N)%100) +#define COAP_SIGNALING_CSM COAP_SIGNALING_CODE(701) +#define COAP_SIGNALING_PING COAP_SIGNALING_CODE(702) +#define COAP_SIGNALING_PONG COAP_SIGNALING_CODE(703) +#define COAP_SIGNALING_RELEASE COAP_SIGNALING_CODE(704) +#define COAP_SIGNALING_ABORT COAP_SIGNALING_CODE(705) + +/* Applies to COAP_SIGNALING_CSM */ +#define COAP_SIGNALING_OPTION_MAX_MESSAGE_SIZE 2 +#define COAP_SIGNALING_OPTION_BLOCK_WISE_TRANSFER 4 +/* Applies to COAP_SIGNALING_PING / COAP_SIGNALING_PONG */ +#define COAP_SIGNALING_OPTION_CUSTODY 2 +/* Applies to COAP_SIGNALING_RELEASE */ +#define COAP_SIGNALING_OPTION_ALTERNATIVE_ADDRESS 2 +#define COAP_SIGNALING_OPTION_HOLD_OFF 4 +/* Applies to COAP_SIGNALING_ABORT */ +#define COAP_SIGNALING_OPTION_BAD_CSM_OPTION 2 + +/* CoAP media type encoding */ + +#define COAP_MEDIATYPE_TEXT_PLAIN 0 /* text/plain (UTF-8) */ +#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT 40 /* application/link-format */ +#define COAP_MEDIATYPE_APPLICATION_XML 41 /* application/xml */ +#define COAP_MEDIATYPE_APPLICATION_OCTET_STREAM 42 /* application/octet-stream */ +#define COAP_MEDIATYPE_APPLICATION_RDF_XML 43 /* application/rdf+xml */ +#define COAP_MEDIATYPE_APPLICATION_EXI 47 /* application/exi */ +#define COAP_MEDIATYPE_APPLICATION_JSON 50 /* application/json */ +#define COAP_MEDIATYPE_APPLICATION_CBOR 60 /* application/cbor */ + +/* Content formats from RFC 8152 */ +#define COAP_MEDIATYPE_APPLICATION_COSE_SIGN 98 /* application/cose; cose-type="cose-sign" */ +#define COAP_MEDIATYPE_APPLICATION_COSE_SIGN1 18 /* application/cose; cose-type="cose-sign1" */ +#define COAP_MEDIATYPE_APPLICATION_COSE_ENCRYPT 96 /* application/cose; cose-type="cose-encrypt" */ +#define COAP_MEDIATYPE_APPLICATION_COSE_ENCRYPT0 16 /* application/cose; cose-type="cose-encrypt0" */ +#define COAP_MEDIATYPE_APPLICATION_COSE_MAC 97 /* application/cose; cose-type="cose-mac" */ +#define COAP_MEDIATYPE_APPLICATION_COSE_MAC0 17 /* application/cose; cose-type="cose-mac0" */ + +#define COAP_MEDIATYPE_APPLICATION_COSE_KEY 101 /* application/cose-key */ +#define COAP_MEDIATYPE_APPLICATION_COSE_KEY_SET 102 /* application/cose-key-set */ + +/* Content formats from RFC 8428 */ +#define COAP_MEDIATYPE_APPLICATION_SENML_JSON 110 /* application/senml+json */ +#define COAP_MEDIATYPE_APPLICATION_SENSML_JSON 111 /* application/sensml+json */ +#define COAP_MEDIATYPE_APPLICATION_SENML_CBOR 112 /* application/senml+cbor */ +#define COAP_MEDIATYPE_APPLICATION_SENSML_CBOR 113 /* application/sensml+cbor */ +#define COAP_MEDIATYPE_APPLICATION_SENML_EXI 114 /* application/senml-exi */ +#define COAP_MEDIATYPE_APPLICATION_SENSML_EXI 115 /* application/sensml-exi */ +#define COAP_MEDIATYPE_APPLICATION_SENML_XML 310 /* application/senml+xml */ +#define COAP_MEDIATYPE_APPLICATION_SENSML_XML 311 /* application/sensml+xml */ + +/* Note that identifiers for registered media types are in the range 0-65535. We + * use an unallocated type here and hope for the best. */ +#define COAP_MEDIATYPE_ANY 0xff /* any media type */ + +/** + * coap_tid_t is used to store CoAP transaction id, i.e. a hash value + * built from the remote transport address and the message id of a + * CoAP PDU. Valid transaction ids are greater or equal zero. + */ +typedef int coap_tid_t; + +/** Indicates an invalid transaction id. */ +#define COAP_INVALID_TID -1 + +/** + * Indicates that a response is suppressed. This will occur for error + * responses if the request was received via IP multicast. + */ +#define COAP_DROPPED_RESPONSE -2 + +#define COAP_PDU_DELAYED -3 + +#define COAP_OPT_LONG 0x0F /* OC == 0b1111 indicates that the option list + * in a CoAP message is limited by 0b11110000 + * marker */ + +#define COAP_OPT_END 0xF0 /* end marker */ + +#define COAP_PAYLOAD_START 0xFF /* payload marker */ + +/** + * @deprecated Use coap_optlist_t instead. + * + * Structures for more convenient handling of options. (To be used with ordered + * coap_list_t.) The option's data will be added to the end of the coap_option + * structure (see macro COAP_OPTION_DATA). + */ +COAP_DEPRECATED typedef struct { + uint16_t key; /* the option key (no delta coding) */ + unsigned int length; +} coap_option; + +#define COAP_OPTION_KEY(option) (option).key +#define COAP_OPTION_LENGTH(option) (option).length +#define COAP_OPTION_DATA(option) ((unsigned char *)&(option) + sizeof(coap_option)) + +/** + * structure for CoAP PDUs + * token, if any, follows the fixed size header, then options until + * payload marker (0xff), then the payload if stored inline. + * Memory layout is: + * <---header--->|<---token---><---options--->0xff<---payload---> + * header is addressed with a negative offset to token, its maximum size is + * max_hdr_size. + * options starts at token + token_length + * payload starts at data, its length is used_size - (data - token) + */ + +typedef struct coap_pdu_t { + uint8_t type; /**< message type */ + uint8_t code; /**< request method (value 1--10) or response code (value 40-255) */ + uint8_t max_hdr_size; /**< space reserved for protocol-specific header */ + uint8_t hdr_size; /**< actaul size used for protocol-specific header */ + uint8_t token_length; /**< length of Token */ + uint16_t tid; /**< transaction id, if any, in regular host byte order */ + uint16_t max_delta; /**< highest option number */ + size_t alloc_size; /**< allocated storage for token, options and payload */ + size_t used_size; /**< used bytes of storage for token, options and payload */ + size_t max_size; /**< maximum size for token, options and payload, or zero for variable size pdu */ + uint8_t *token; /**< first byte of token, if any, or options */ + uint8_t *data; /**< first byte of payload, if any */ +#ifdef WITH_LWIP + struct pbuf *pbuf; /**< lwIP PBUF. The package data will always reside + * inside the pbuf's payload, but this pointer + * has to be kept because no exact offset can be + * given. This field must not be accessed from + * outside, because the pbuf's reference count + * is checked to be 1 when the pbuf is assigned + * to the pdu, and the pbuf stays exclusive to + * this pdu. */ +#endif +} coap_pdu_t; + +#define COAP_PDU_IS_EMPTY(pdu) ((pdu)->code == 0) +#define COAP_PDU_IS_REQUEST(pdu) (!COAP_PDU_IS_EMPTY(pdu) && (pdu)->code < 32) +#define COAP_PDU_IS_RESPONSE(pdu) ((pdu)->code >= 64 && (pdu)->code < 224) +#define COAP_PDU_IS_SIGNALING(pdu) ((pdu)->code >= 224) + +#define COAP_PDU_MAX_UDP_HEADER_SIZE 4 +#define COAP_PDU_MAX_TCP_HEADER_SIZE 6 + +#ifdef WITH_LWIP +/** + * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to this + * function. + * + * The pbuf is checked for being contiguous, and for having only one reference. + * The reference is stored in the PDU and will be freed when the PDU is freed. + * + * (For now, these are fatal errors; in future, a new pbuf might be allocated, + * the data copied and the passed pbuf freed). + * + * This behaves like coap_pdu_init(0, 0, 0, pbuf->tot_len), and afterwards + * copying the contents of the pbuf to the pdu. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf); +#endif + +typedef uint8_t coap_proto_t; +/** +* coap_proto_t values +*/ +#define COAP_PROTO_NONE 0 +#define COAP_PROTO_UDP 1 +#define COAP_PROTO_DTLS 2 +#define COAP_PROTO_TCP 3 +#define COAP_PROTO_TLS 4 + +/** + * Creates a new CoAP PDU with at least enough storage space for the given + * @p size maximum message size. The function returns a pointer to the + * node coap_pdu_t object on success, or @c NULL on error. The storage allocated + * for the result must be released with coap_delete_pdu() if coap_send() is not + * called. + * + * @param type The type of the PDU (one of COAP_MESSAGE_CON, COAP_MESSAGE_NON, + * COAP_MESSAGE_ACK, COAP_MESSAGE_RST). + * @param code The message code. + * @param tid The transcation id to set or 0 if unknown / not applicable. + * @param size The maximum allowed number of byte for the message. + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * +coap_pdu_init(uint8_t type, uint8_t code, uint16_t tid, size_t size); + +/** + * Dynamically grows the size of @p pdu to @p new_size. The new size + * must not exceed the PDU's configure maximum size. On success, this + * function returns 1, otherwise 0. + * + * @param pdu The PDU to resize. + * @param new_size The new size in bytes. + * @return 1 if the operation succeeded, 0 otherwise. + */ +int coap_pdu_resize(coap_pdu_t *pdu, size_t new_size); + +/** + * Clears any contents from @p pdu and resets @c used_size, + * and @c data pointers. @c max_size is set to @p size, any + * other field is set to @c 0. Note that @p pdu must be a valid + * pointer to a coap_pdu_t object created e.g. by coap_pdu_init(). + */ +void coap_pdu_clear(coap_pdu_t *pdu, size_t size); + +/** + * Creates a new CoAP PDU. + */ +coap_pdu_t *coap_new_pdu(const struct coap_session_t *session); + +/** + * Dispose of an CoAP PDU and frees associated storage. + * Not that in general you should not call this function directly. + * When a PDU is sent with coap_send(), coap_delete_pdu() will be + * called automatically for you. + */ + +void coap_delete_pdu(coap_pdu_t *); + +/** +* Interprets @p data to determine the number of bytes in the header. +* This function returns @c 0 on error or a number greater than zero on success. +* +* @param proto Session's protocol +* @param data The first byte of raw data to parse as CoAP PDU. +* +* @return A value greater than zero on success or @c 0 on error. +*/ +size_t coap_pdu_parse_header_size(coap_proto_t proto, + const uint8_t *data); + +/** + * Parses @p data to extract the message size. + * @p length must be at least coap_pdu_parse_header_size(proto, data). + * This function returns @c 0 on error or a number greater than zero on success. + * + * @param proto Session's protocol + * @param data The raw data to parse as CoAP PDU. + * @param length The actual size of @p data. + * + * @return A value greater than zero on success or @c 0 on error. + */ +size_t coap_pdu_parse_size(coap_proto_t proto, + const uint8_t *data, + size_t length); + +/** + * Decode the protocol specific header for the specified PDU. + * @param pdu A newly received PDU. + * @param proto The target wire protocol. + * @return 1 for success or 0 on error. + */ + +int coap_pdu_parse_header(coap_pdu_t *pdu, coap_proto_t proto); + +/** + * Verify consistency in the given CoAP PDU structure and locate the data. + * This function returns @c 0 on error or a number greater than zero on + * success. + * This function only parses the token and options, up to the payload start + * marker. + * + * @param pdu The PDU structure to. + * + * @return 1 on success or @c 0 on error. + */ +int coap_pdu_parse_opt(coap_pdu_t *pdu); + +/** +* Parses @p data into the CoAP PDU structure given in @p result. +* The target pdu must be large enough to +* This function returns @c 0 on error or a number greater than zero on success. +* +* @param proto Session's protocol +* @param data The raw data to parse as CoAP PDU. +* @param length The actual size of @p data. +* @param pdu The PDU structure to fill. Note that the structure must +* provide space to hold at least the token and options +* part of the message. +* +* @return 1 on success or @c 0 on error. +*/ +int coap_pdu_parse(coap_proto_t proto, + const uint8_t *data, + size_t length, + coap_pdu_t *pdu); +/** + * Adds token of length @p len to @p pdu. + * Adding the token destroys any following contents of the pdu. Hence options + * and data must be added after coap_add_token() has been called. In @p pdu, + * length is set to @p len + @c 4, and max_delta is set to @c 0. This function + * returns @c 0 on error or a value greater than zero on success. + * + * @param pdu The PDU where the token is to be added. + * @param len The length of the new token. + * @param data The token to add. + * + * @return A value greater than zero on success, or @c 0 on error. + */ +int coap_add_token(coap_pdu_t *pdu, + size_t len, + const uint8_t *data); + +/** + * Adds option of given type to pdu that is passed as first + * parameter. + * coap_add_option() destroys the PDU's data, so coap_add_data() must be called + * after all options have been added. As coap_add_token() destroys the options + * following the token, the token must be added before coap_add_option() is + * called. This function returns the number of bytes written or @c 0 on error. + */ +size_t coap_add_option(coap_pdu_t *pdu, + uint16_t type, + size_t len, + const uint8_t *data); + +/** + * Adds option of given type to pdu that is passed as first parameter, but does + * not write a value. It works like coap_add_option with respect to calling + * sequence (i.e. after token and before data). This function returns a memory + * address to which the option data has to be written before the PDU can be + * sent, or @c NULL on error. + */ +uint8_t *coap_add_option_later(coap_pdu_t *pdu, + uint16_t type, + size_t len); + +/** + * Adds given data to the pdu that is passed as first parameter. Note that the + * PDU's data is destroyed by coap_add_option(). coap_add_data() must be called + * only once per PDU, otherwise the result is undefined. + */ +int coap_add_data(coap_pdu_t *pdu, + size_t len, + const uint8_t *data); + +/** + * Adds given data to the pdu that is passed as first parameter but does not + * copyt it. Note that the PDU's data is destroyed by coap_add_option(). + * coap_add_data() must be have been called once for this PDU, otherwise the + * result is undefined. + * The actual data must be copied at the returned location. + */ +uint8_t *coap_add_data_after(coap_pdu_t *pdu, size_t len); + +/** + * Retrieves the length and data pointer of specified PDU. Returns 0 on error or + * 1 if *len and *data have correct values. Note that these values are destroyed + * with the pdu. + */ +int coap_get_data(const coap_pdu_t *pdu, + size_t *len, + uint8_t **data); + +/** + * Compose the protocol specific header for the specified PDU. + * @param pdu A newly composed PDU. + * @param proto The target wire protocol. + * @return Number of header bytes prepended before pdu->token or 0 on error. + */ + +size_t coap_pdu_encode_header(coap_pdu_t *pdu, coap_proto_t proto); + +#endif /* COAP_PDU_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/prng.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/prng.h new file mode 100644 index 00000000..c9510bf5 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/prng.h @@ -0,0 +1,127 @@ +/* + * prng.h -- Pseudo Random Numbers + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file prng.h + * @brief Pseudo Random Numbers + */ + +#ifndef COAP_PRNG_H_ +#define COAP_PRNG_H_ + +/** + * @defgroup prng Pseudo Random Numbers + * API functions for gerating pseudo random numbers + * @{ + */ + +#if defined(WITH_CONTIKI) +#include + +/** + * Fills \p buf with \p len random bytes. This is the default implementation for + * prng(). You might want to change prng() to use a better PRNG on your specific + * platform. + */ +COAP_STATIC_INLINE int +contiki_prng_impl(unsigned char *buf, size_t len) { + uint16_t v = random_rand(); + while (len > sizeof(v)) { + memcpy(buf, &v, sizeof(v)); + len -= sizeof(v); + buf += sizeof(v); + v = random_rand(); + } + + memcpy(buf, &v, len); + return 1; +} + +#define prng(Buf,Length) contiki_prng_impl((Buf), (Length)) +#define prng_init(Value) random_init((uint16_t)(Value)) +#elif defined(WITH_LWIP) && defined(LWIP_RAND) +COAP_STATIC_INLINE int +lwip_prng_impl(unsigned char *buf, size_t len) { + u32_t v = LWIP_RAND(); + while (len > sizeof(v)) { + memcpy(buf, &v, sizeof(v)); + len -= sizeof(v); + buf += sizeof(v); + v = LWIP_RAND(); + } + + memcpy(buf, &v, len); + return 1; +} + +#define prng(Buf,Length) lwip_prng_impl((Buf), (Length)) +#define prng_init(Value) +#elif defined(_WIN32) +#define prng_init(Value) +errno_t __cdecl rand_s( _Out_ unsigned int* _RandomValue ); + /** + * Fills \p buf with \p len random bytes. This is the default implementation for + * prng(). You might want to change prng() to use a better PRNG on your specific + * platform. + */ +COAP_STATIC_INLINE int +coap_prng_impl( unsigned char *buf, size_t len ) { + while ( len != 0 ) { + uint32_t r = 0; + size_t i; + if ( rand_s( &r ) != 0 ) + return 0; + for ( i = 0; i < len && i < 4; i++ ) { + *buf++ = (uint8_t)r; + r >>= 8; + } + len -= i; + } + return 1; +} + +#else +#include + + /** + * Fills \p buf with \p len random bytes. This is the default implementation for + * prng(). You might want to change prng() to use a better PRNG on your specific + * platform. + */ +COAP_STATIC_INLINE int +coap_prng_impl( unsigned char *buf, size_t len ) { + while ( len-- ) + *buf++ = rand() & 0xFF; + return 1; +} +#endif + + +#ifndef prng +/** + * Fills \p Buf with \p Length bytes of random data. + * + * @hideinitializer + */ +#define prng(Buf,Length) coap_prng_impl((Buf), (Length)) +#endif + +#ifndef prng_init +/** + * Called to set the PRNG seed. You may want to re-define this to allow for a + * better PRNG. + * + * @hideinitializer + */ +#define prng_init(Value) srand((unsigned long)(Value)) +#endif + +/** @} */ + +#endif /* COAP_PRNG_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/resource.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/resource.h new file mode 100644 index 00000000..58018720 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/resource.h @@ -0,0 +1,524 @@ +/* + * resource.h -- generic resource handling + * + * Copyright (C) 2010,2011,2014,2015 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +/** + * @file resource.h + * @brief Generic resource handling + */ + +#ifndef COAP_RESOURCE_H_ +#define COAP_RESOURCE_H_ + +# include + +#ifndef COAP_RESOURCE_CHECK_TIME +/** The interval in seconds to check if resources have changed. */ +#define COAP_RESOURCE_CHECK_TIME 2 +#endif /* COAP_RESOURCE_CHECK_TIME */ + +#include "uthash.h" +#include "async.h" +#include "str.h" +#include "pdu.h" +#include "net.h" +#include "subscribe.h" + +/** + * Definition of message handler function (@sa coap_resource_t). + */ +typedef void (*coap_method_handler_t) + (coap_context_t *, + struct coap_resource_t *, + coap_session_t *, + coap_pdu_t *, + coap_binary_t * /* token */, + coap_string_t * /* query string */, + coap_pdu_t * /* response */); + +#define COAP_ATTR_FLAGS_RELEASE_NAME 0x1 +#define COAP_ATTR_FLAGS_RELEASE_VALUE 0x2 + +typedef struct coap_attr_t { + struct coap_attr_t *next; + coap_str_const_t *name; + coap_str_const_t *value; + int flags; +} coap_attr_t; + +/** The URI passed to coap_resource_init() is free'd by coap_delete_resource(). */ +#define COAP_RESOURCE_FLAGS_RELEASE_URI 0x1 + +/** + * Notifications will be sent non-confirmable by default. RFC 7641 Section 4.5 + * https://tools.ietf.org/html/rfc7641#section-4.5 + */ +#define COAP_RESOURCE_FLAGS_NOTIFY_NON 0x0 + +/** + * Notifications will be sent confirmable by default. RFC 7641 Section 4.5 + * https://tools.ietf.org/html/rfc7641#section-4.5 + */ +#define COAP_RESOURCE_FLAGS_NOTIFY_CON 0x2 + +typedef struct coap_resource_t { + unsigned int dirty:1; /**< set to 1 if resource has changed */ + unsigned int partiallydirty:1; /**< set to 1 if some subscribers have not yet + * been notified of the last change */ + unsigned int observable:1; /**< can be observed */ + unsigned int cacheable:1; /**< can be cached */ + unsigned int is_unknown:1; /**< resource created for unknown handler */ + + /** + * Used to store handlers for the seven coap methods @c GET, @c POST, @c PUT, + * @c DELETE, @c FETCH, @c PATCH and @c IPATCH. + * coap_dispatch() will pass incoming requests to the handler + * that corresponds to its request method or generate a 4.05 response if no + * handler is available. + */ + coap_method_handler_t handler[7]; + + UT_hash_handle hh; + + coap_attr_t *link_attr; /**< attributes to be included with the link format */ + coap_subscription_t *subscribers; /**< list of observers for this resource */ + + /** + * Request URI Path for this resource. This field will point into static + * or allocated memory which must remain there for the duration of the + * resource. + */ + coap_str_const_t *uri_path; /**< the key used for hash lookup for this resource */ + int flags; + + /** + * The next value for the Observe option. This field must be increased each + * time the resource changes. Only the lower 24 bits are sent. + */ + unsigned int observe; + + /** + * This pointer is under user control. It can be used to store context for + * the coap handler. + */ + void *user_data; + +} coap_resource_t; + +/** + * Creates a new resource object and initializes the link field to the string + * @p uri_path. This function returns the new coap_resource_t object. + * + * If the string is going to be freed off by coap_delete_resource() when + * COAP_RESOURCE_FLAGS_RELEASE_URI is set in @p flags, then either the 's' + * variable of coap_str_const_t has to point to constant text, or point to data + * within the allocated coap_str_const_t parameter. + * + * @param uri_path The string URI path of the new resource. + * @param flags Flags for memory management (in particular release of + * memory). Possible values:@n + * + * COAP_RESOURCE_FLAGS_RELEASE_URI + * If this flag is set, the URI passed to + * coap_resource_init() is free'd by + * coap_delete_resource()@n + * + * COAP_RESOURCE_FLAGS_NOTIFY_CON + * If this flag is set, coap-observe notifications + * will be sent confirmable by default.@n + * + * COAP_RESOURCE_FLAGS_NOTIFY_NON (default) + * If this flag is set, coap-observe notifications + * will be sent non-confirmable by default.@n + * + * If flags is set to 0 then the + * COAP_RESOURCE_FLAGS_NOTIFY_NON is considered. + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_resource_t *coap_resource_init(coap_str_const_t *uri_path, + int flags); + + +/** + * Creates a new resource object for the unknown resource handler with support + * for PUT. + * + * In the same way that additional handlers can be added to the resource + * created by coap_resource_init() by using coap_register_handler(), POST, + * GET, DELETE etc. handlers can be added to this resource. It is the + * responsibility of the application to manage the unknown resources by either + * creating new resources with coap_resource_init() (which should have a + * DELETE handler specified for the resource removal) or by maintaining an + * active resource list. + * + * Note: There can only be one unknown resource handler per context - attaching + * a new one overrides the previous definition. + * + * Note: It is not possible to observe the unknown resource with a GET request + * - a separate resource needs to be reated by the PUT (or POST) handler, + * and make that resource observable. + * + * This function returns the new coap_resource_t object. + * + * @param put_handler The PUT handler to register with @p resource for + * unknown Uri-Path. + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_resource_t *coap_resource_unknown_init(coap_method_handler_t put_handler); + +/** + * Sets the notification message type of resource @p resource to given + * @p mode + + * @param resource The resource to update. + * @param mode Must be one of @c COAP_RESOURCE_FLAGS_NOTIFY_NON + * or @c COAP_RESOURCE_FLAGS_NOTIFY_CON. + */ +COAP_STATIC_INLINE void +coap_resource_set_mode(coap_resource_t *resource, int mode) { + resource->flags = (resource->flags & + ~(COAP_RESOURCE_FLAGS_NOTIFY_CON|COAP_RESOURCE_FLAGS_NOTIFY_NON)) | + (mode & (COAP_RESOURCE_FLAGS_NOTIFY_CON|COAP_RESOURCE_FLAGS_NOTIFY_NON)); +} + +/** + * Sets the user_data. The user_data is exclusively used by the library-user + * and can be used as context in the handler functions. + * + * @param r Resource to attach the data to + * @param data Data to attach to the user_data field. This pointer is only used for + * storage, the data remains under user control + */ +COAP_STATIC_INLINE void +coap_resource_set_userdata(coap_resource_t *r, void *data) { + r->user_data = data; +} + +/** + * Gets the user_data. The user_data is exclusively used by the library-user + * and can be used as context in the handler functions. + * + * @param r Resource to retrieve the user_darta from + * + * @return The user_data pointer + */ +COAP_STATIC_INLINE void * +coap_resource_get_userdata(coap_resource_t *r) { + return r->user_data; +} + +/** + * Registers the given @p resource for @p context. The resource must have been + * created by coap_resource_init() or coap_resource_unknown_init(), the + * storage allocated for the resource will be released by coap_delete_resource(). + * + * @param context The context to use. + * @param resource The resource to store. + */ +void coap_add_resource(coap_context_t *context, coap_resource_t *resource); + +/** + * Deletes a resource identified by @p resource. The storage allocated for that + * resource is freed, and removed from the context. + * + * @param context The context where the resources are stored. + * @param resource The resource to delete. + * + * @return @c 1 if the resource was found (and destroyed), + * @c 0 otherwise. + */ +int coap_delete_resource(coap_context_t *context, coap_resource_t *resource); + +/** + * Deletes all resources from given @p context and frees their storage. + * + * @param context The CoAP context with the resources to be deleted. + */ +void coap_delete_all_resources(coap_context_t *context); + +/** + * Registers a new attribute with the given @p resource. As the + * attribute's coap_str_const_ fields will point to @p name and @p value the + * caller must ensure that these pointers are valid during the + * attribute's lifetime. + + * If the @p name and/or @p value string is going to be freed off at attribute + * removal time by the setting of COAP_ATTR_FLAGS_RELEASE_NAME or + * COAP_ATTR_FLAGS_RELEASE_VALUE in @p flags, then either the 's' + * variable of coap_str_const_t has to point to constant text, or point to data + * within the allocated coap_str_const_t parameter. + * + * @param resource The resource to register the attribute with. + * @param name The attribute's name as a string. + * @param value The attribute's value as a string or @c NULL if none. + * @param flags Flags for memory management (in particular release of + * memory). Possible values:@n + * + * COAP_ATTR_FLAGS_RELEASE_NAME + * If this flag is set, the name passed to + * coap_add_attr_release() is free'd + * when the attribute is deleted@n + * + * COAP_ATTR_FLAGS_RELEASE_VALUE + * If this flag is set, the value passed to + * coap_add_attr_release() is free'd + * when the attribute is deleted@n + * + * @return A pointer to the new attribute or @c NULL on error. + */ +coap_attr_t *coap_add_attr(coap_resource_t *resource, + coap_str_const_t *name, + coap_str_const_t *value, + int flags); + +/** + * Returns @p resource's coap_attr_t object with given @p name if found, @c NULL + * otherwise. + * + * @param resource The resource to search for attribute @p name. + * @param name Name of the requested attribute as a string. + * @return The first attribute with specified @p name or @c NULL if none + * was found. + */ +coap_attr_t *coap_find_attr(coap_resource_t *resource, + coap_str_const_t *name); + +/** + * Deletes an attribute. + * Note: This is for internal use only, as it is not deleted from its chain. + * + * @param attr Pointer to a previously created attribute. + * + */ +void coap_delete_attr(coap_attr_t *attr); + +/** + * Status word to encode the result of conditional print or copy operations such + * as coap_print_link(). The lower 28 bits of coap_print_status_t are used to + * encode the number of characters that has actually been printed, bits 28 to 31 + * encode the status. When COAP_PRINT_STATUS_ERROR is set, an error occurred + * during output. In this case, the other bits are undefined. + * COAP_PRINT_STATUS_TRUNC indicates that the output is truncated, i.e. the + * printing would have exceeded the current buffer. + */ +typedef unsigned int coap_print_status_t; + +#define COAP_PRINT_STATUS_MASK 0xF0000000u +#define COAP_PRINT_OUTPUT_LENGTH(v) ((v) & ~COAP_PRINT_STATUS_MASK) +#define COAP_PRINT_STATUS_ERROR 0x80000000u +#define COAP_PRINT_STATUS_TRUNC 0x40000000u + +/** + * Writes a description of this resource in link-format to given text buffer. @p + * len must be initialized to the maximum length of @p buf and will be set to + * the number of characters actually written if successful. This function + * returns @c 1 on success or @c 0 on error. + * + * @param resource The resource to describe. + * @param buf The output buffer to write the description to. + * @param len Must be initialized to the length of @p buf and + * will be set to the length of the printed link description. + * @param offset The offset within the resource description where to + * start writing into @p buf. This is useful for dealing + * with the Block2 option. @p offset is updated during + * output as it is consumed. + * + * @return If COAP_PRINT_STATUS_ERROR is set, an error occured. Otherwise, + * the lower 28 bits will indicate the number of characters that + * have actually been output into @p buffer. The flag + * COAP_PRINT_STATUS_TRUNC indicates that the output has been + * truncated. + */ +coap_print_status_t coap_print_link(const coap_resource_t *resource, + unsigned char *buf, + size_t *len, + size_t *offset); + +/** + * Registers the specified @p handler as message handler for the request type @p + * method + * + * @param resource The resource for which the handler shall be registered. + * @param method The CoAP request method to handle. + * @param handler The handler to register with @p resource. + */ +void coap_register_handler(coap_resource_t *resource, + unsigned char method, + coap_method_handler_t handler); + +/** + * Returns the resource identified by the unique string @p uri_path. If no + * resource was found, this function returns @c NULL. + * + * @param context The context to look for this resource. + * @param uri_path The unique string uri of the resource. + * + * @return A pointer to the resource or @c NULL if not found. + */ +coap_resource_t *coap_get_resource_from_uri_path(coap_context_t *context, + coap_str_const_t *uri_path); + +/** + * @addtogroup observe + */ + +/** + * Adds the specified peer as observer for @p resource. The subscription is + * identified by the given @p token. This function returns the registered + * subscription information if the @p observer has been added, or @c NULL on + * error. + * + * @param resource The observed resource. + * @param session The observer's session + * @param token The token that identifies this subscription. + * @param query The query string, if any. subscription will + take ownership of the string. + * @param has_block2 If Option Block2 defined. + * @param block2 Contents of Block2 if Block 2 defined. + * @return A pointer to the added/updated subscription + * information or @c NULL on error. + */ +coap_subscription_t *coap_add_observer(coap_resource_t *resource, + coap_session_t *session, + const coap_binary_t *token, + coap_string_t *query, + int has_block2, + coap_block_t block2); + +/** + * Returns a subscription object for given @p peer. + * + * @param resource The observed resource. + * @param session The observer's session + * @param token The token that identifies this subscription or @c NULL for + * any token. + * @return A valid subscription if exists or @c NULL otherwise. + */ +coap_subscription_t *coap_find_observer(coap_resource_t *resource, + coap_session_t *session, + const coap_binary_t *token); + +/** + * Marks an observer as alive. + * + * @param context The CoAP context to use. + * @param session The observer's session + * @param token The corresponding token that has been used for the + * subscription. + */ +void coap_touch_observer(coap_context_t *context, + coap_session_t *session, + const coap_binary_t *token); + +/** + * Removes any subscription for @p observer from @p resource and releases the + * allocated storage. The result is @c 1 if an observation relationship with @p + * observer and @p token existed, @c 0 otherwise. + * + * @param resource The observed resource. + * @param session The observer's session. + * @param token The token that identifies this subscription or @c NULL for + * any token. + * @return @c 1 if the observer has been deleted, @c 0 otherwise. + */ +int coap_delete_observer(coap_resource_t *resource, + coap_session_t *session, + const coap_binary_t *token); + +/** + * Removes any subscription for @p session and releases the allocated storage. + * + * @param context The CoAP context to use. + * @param session The observer's session. + */ +void coap_delete_observers(coap_context_t *context, coap_session_t *session); + +/** + * Checks for all known resources, if they are dirty and notifies subscribed + * observers. + */ +void coap_check_notify(coap_context_t *context); + +#define RESOURCES_ADD(r, obj) \ + HASH_ADD(hh, (r), uri_path->s[0], (obj)->uri_path->length, (obj)) + +#define RESOURCES_DELETE(r, obj) \ + HASH_DELETE(hh, (r), (obj)) + +#define RESOURCES_ITER(r,tmp) \ + coap_resource_t *tmp, *rtmp; \ + HASH_ITER(hh, (r), tmp, rtmp) + +#define RESOURCES_FIND(r, k, res) { \ + HASH_FIND(hh, (r), (k)->s, (k)->length, (res)); \ + } + +/** @} */ + +coap_print_status_t coap_print_wellknown(coap_context_t *, + unsigned char *, + size_t *, size_t, + coap_opt_t *); + +void +coap_handle_failed_notify(coap_context_t *, + coap_session_t *, + const coap_binary_t *); + +/** + * Set whether a @p resource is observable. If the resource is observable + * and the client has set the COAP_OPTION_OBSERVE in a request packet, then + * whenever the state of the resource changes (a call to + * coap_resource_trigger_observe()), an Observer response will get sent. + * + * @param resource The CoAP resource to use. + * @param mode @c 1 if Observable is to be set, @c 0 otherwise. + * + */ +COAP_STATIC_INLINE void +coap_resource_set_get_observable(coap_resource_t *resource, int mode) { + resource->observable = mode ? 1 : 0; +} + +/** + * Initiate the sending of an Observe packet for all observers of @p resource, + * optionally matching @p query if not NULL + * + * @param resource The CoAP resource to use. + * @param query The Query to match against or NULL + * + * @return @c 1 if the Observe has been triggered, @c 0 otherwise. + */ +int +coap_resource_notify_observers(coap_resource_t *resource, + const coap_string_t *query); + +/** + * Get the UriPath from a @p resource. + * + * @param resource The CoAP resource to check. + * + * @return The UriPath if it exists or @c NULL otherwise. + */ +COAP_STATIC_INLINE coap_str_const_t* +coap_resource_get_uri_path(coap_resource_t *resource) { + if (resource) + return resource->uri_path; + return NULL; +} + +/** + * @deprecated use coap_resource_notify_observers() instead. + */ +COAP_DEPRECATED int +coap_resource_set_dirty(coap_resource_t *r, + const coap_string_t *query); + +#endif /* COAP_RESOURCE_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/str.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/str.h new file mode 100644 index 00000000..6c1488c9 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/str.h @@ -0,0 +1,121 @@ +/* + * str.h -- strings to be used in the CoAP library + * + * Copyright (C) 2010-2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_STR_H_ +#define COAP_STR_H_ + +#include + + +/** + * @defgroup string String handling support + * API functions for handling strings + * @{ + */ + +/** + * Coap string data definition + */ +typedef struct coap_string_t { + size_t length; /**< length of string */ + uint8_t *s; /**< string data */ +} coap_string_t; + +/** + * Coap string data definition with const data + */ +typedef struct coap_str_const_t { + size_t length; /**< length of string */ + const uint8_t *s; /**< string data */ +} coap_str_const_t; + +#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); } + +/** + * Coap binary data definition + */ +typedef struct coap_binary_t { + size_t length; /**< length of binary data */ + uint8_t *s; /**< binary data */ +} coap_binary_t; + +/** + * Returns a new string object with at least size+1 bytes storage allocated. + * The string must be released using coap_delete_string(). + * + * @param size The size to allocate for the binary string data. + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_string_t *coap_new_string(size_t size); + +/** + * Deletes the given string and releases any memory allocated. + * + * @param string The string to free off. + */ +void coap_delete_string(coap_string_t *string); + +/** + * Returns a new const string object with at least size+1 bytes storage + * allocated, and the provided data copied into the string object. + * The string must be released using coap_delete_str_const(). + * + * @param data The data to put in the new string object. + * @param size The size to allocate for the binary string data. + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_str_const_t *coap_new_str_const(const uint8_t *data, size_t size); + +/** + * Deletes the given const string and releases any memory allocated. + * + * @param string The string to free off. + */ +void coap_delete_str_const(coap_str_const_t *string); + +/** + * Take the specified byte array (text) and create a coap_str_const_t * + * + * WARNING: The byte array must be in the local scope and not a + * parameter in the function call as sizeof() will return the size of the + * pointer, not the size of the byte array, leading to unxepected results. + * + * @param string The const byte array to convert to a coap_str_const_t * + */ +#ifdef __cplusplus +namespace libcoap { + struct CoAPStrConst : coap_str_const_t { + operator coap_str_const_t *() { return this; } + }; +} +#define coap_make_str_const(CStr) \ + libcoap::CoAPStrConst{sizeof(CStr)-1, reinterpret_cast(CStr)} +#else /* __cplusplus */ +#define coap_make_str_const(string) \ + (&(coap_str_const_t){sizeof(string)-1,(const uint8_t *)(string)}) +#endif /* __cplusplus */ + +/** + * Compares the two strings for equality + * + * @param string1 The first string. + * @param string2 The second string. + * + * @return @c 1 if the strings are equal + * @c 0 otherwise. + */ +#define coap_string_equal(string1,string2) \ + ((string1)->length == (string2)->length && ((string1)->length == 0 || \ + memcmp((string1)->s, (string2)->s, (string1)->length) == 0)) + +/** @} */ + +#endif /* COAP_STR_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/subscribe.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/subscribe.h new file mode 100644 index 00000000..ed635a61 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/subscribe.h @@ -0,0 +1,77 @@ +/* + * subscribe.h -- subscription handling for CoAP + * see RFC7641 + * + * Copyright (C) 2010-2012,2014-2015 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + + +#ifndef COAP_SUBSCRIBE_H_ +#define COAP_SUBSCRIBE_H_ + +#include "address.h" +#include "coap_io.h" +#include "block.h" + +/** + * @defgroup observe Resource observation + * API functions for interfacing with the observe handling (RFC7641) + * @{ + */ + +/** + * The value COAP_OBSERVE_ESTABLISH in a GET request indicates a new observe + * relationship for (sender address, token) is requested. + */ +#define COAP_OBSERVE_ESTABLISH 0 + +/** + * The value COAP_OBSERVE_CANCEL in a GET request indicates that the observe + * relationship for (sender address, token) must be cancelled. + */ +#define COAP_OBSERVE_CANCEL 1 + +#ifndef COAP_OBS_MAX_NON +/** + * Number of notifications that may be sent non-confirmable before a confirmable + * message is sent to detect if observers are alive. The maximum allowed value + * here is @c 15. + */ +#define COAP_OBS_MAX_NON 5 +#endif /* COAP_OBS_MAX_NON */ + +#ifndef COAP_OBS_MAX_FAIL +/** + * Number of confirmable notifications that may fail (i.e. time out without + * being ACKed) before an observer is removed. The maximum value for + * COAP_OBS_MAX_FAIL is @c 3. + */ +#define COAP_OBS_MAX_FAIL 3 +#endif /* COAP_OBS_MAX_FAIL */ + +/** Subscriber information */ +typedef struct coap_subscription_t { + struct coap_subscription_t *next; /**< next element in linked list */ + coap_session_t *session; /**< subscriber session */ + + unsigned int non_cnt:4; /**< up to 15 non-confirmable notifies allowed */ + unsigned int fail_cnt:2; /**< up to 3 confirmable notifies can fail */ + unsigned int dirty:1; /**< set if the notification temporarily could not be + * sent (in that case, the resource's partially + * dirty flag is set too) */ + unsigned int has_block2:1; /**< GET request had Block2 definition */ + uint16_t tid; /**< transaction id, if any, in regular host byte order */ + coap_block_t block2; /**< GET request Block2 definition */ + size_t token_length; /**< actual length of token */ + unsigned char token[8]; /**< token used for subscription */ + coap_string_t *query; /**< query string used for subscription, if any */ +} coap_subscription_t; + +void coap_subscription_init(coap_subscription_t *); + +/** @} */ + +#endif /* COAP_SUBSCRIBE_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uri.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uri.h new file mode 100644 index 00000000..4d167011 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uri.h @@ -0,0 +1,147 @@ +/* + * uri.h -- helper functions for URI treatment + * + * Copyright (C) 2010-2011,2016 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_URI_H_ +#define COAP_URI_H_ + +#include + +#include "str.h" +struct coap_pdu_t; + +/** + * The scheme specifiers. Secure schemes have an odd numeric value, + * others are even. + */ +enum coap_uri_scheme_t { + COAP_URI_SCHEME_COAP=0, + COAP_URI_SCHEME_COAPS=1, + COAP_URI_SCHEME_COAP_TCP=2, + COAP_URI_SCHEME_COAPS_TCP=3 +}; + +/** This mask can be used to check if a parsed URI scheme is secure. */ +#define COAP_URI_SCHEME_SECURE_MASK 0x01 + +/** + * Representation of parsed URI. Components may be filled from a string with + * coap_split_uri() and can be used as input for option-creation functions. + */ +typedef struct { + coap_str_const_t host; /**< host part of the URI */ + uint16_t port; /**< The port in host byte order */ + coap_str_const_t path; /**< Beginning of the first path segment. + Use coap_split_path() to create Uri-Path options */ + coap_str_const_t query; /**< The query part if present */ + + /** The parsed scheme specifier. */ + enum coap_uri_scheme_t scheme; +} coap_uri_t; + +static inline int +coap_uri_scheme_is_secure(const coap_uri_t *uri) { + return uri && ((uri->scheme & COAP_URI_SCHEME_SECURE_MASK) != 0); +} + +/** + * Creates a new coap_uri_t object from the specified URI. Returns the new + * object or NULL on error. The memory allocated by the new coap_uri_t + * must be released using coap_free(). + * + * @param uri The URI path to copy. + * @param length The length of uri. + * + * @return New URI object or NULL on error. + */ +coap_uri_t *coap_new_uri(const uint8_t *uri, unsigned int length); + +/** + * Clones the specified coap_uri_t object. Thie function allocates sufficient + * memory to hold the coap_uri_t structure and its contents. The object must + * be released with coap_free(). */ +coap_uri_t *coap_clone_uri(const coap_uri_t *uri); + +/** + * @defgroup uri_parse URI Parsing Functions + * + * CoAP PDUs contain normalized URIs with their path and query split into + * multiple segments. The functions in this module help splitting strings. + * @{ + */ + +/** + * Parses a given string into URI components. The identified syntactic + * components are stored in the result parameter @p uri. Optional URI + * components that are not specified will be set to { 0, 0 }, except for the + * port which is set to @c COAP_DEFAULT_PORT. This function returns @p 0 if + * parsing succeeded, a value less than zero otherwise. + * + * @param str_var The string to split up. + * @param len The actual length of @p str_var + * @param uri The coap_uri_t object to store the result. + * @return @c 0 on success, or < 0 on error. + * + */ +int coap_split_uri(const uint8_t *str_var, size_t len, coap_uri_t *uri); + +/** + * Splits the given URI path into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective segment after percent-decoding. + * + * @param s The path string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + */ +int coap_split_path(const uint8_t *s, + size_t length, + unsigned char *buf, + size_t *buflen); + +/** + * Splits the given URI query into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective query term. + * + * @param s The query string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + * + * @bug This function does not reserve additional space for delta > 12. + */ +int coap_split_query(const uint8_t *s, + size_t length, + unsigned char *buf, + size_t *buflen); + +/** + * Extract query string from request PDU according to escape rules in 6.5.8. + * @param request Request PDU. + * @return Reconstructed and escaped query string part. + */ +coap_string_t *coap_get_query(const struct coap_pdu_t *request); + +/** + * Extract uri_path string from request PDU + * @param request Request PDU. + * @return Reconstructed and escaped uri path string part. + */ +coap_string_t *coap_get_uri_path(const struct coap_pdu_t *request); + +/** @} */ + +#endif /* COAP_URI_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uthash.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uthash.h new file mode 100644 index 00000000..156eb821 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/uthash.h @@ -0,0 +1,1108 @@ +/* +Copyright (c) 2003-2017, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#define UTHASH_VERSION 2.0.2 + +#include /* memcmp, memset, strlen */ +#include /* ptrdiff_t */ +#include /* exit */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if !defined(DECLTYPE) && !defined(NO_DECLTYPE) +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE(x) +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while (0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while (0) +#endif + +/* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ +#if defined(_WIN32) +#if defined(_MSC_VER) && _MSC_VER >= 1600 +#include +#elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) +#include +#else +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#endif +#elif defined(__GNUC__) && !defined(__VXWORKS__) +#include +#else +typedef unsigned int uint32_t; +typedef unsigned char uint8_t; +#endif + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ +#endif +#ifndef uthash_malloc +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#endif +#ifndef uthash_free +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ +#endif +#ifndef uthash_bzero +#define uthash_bzero(a,n) memset(a,'\0',n) +#endif +#ifndef uthash_memcmp +#define uthash_memcmp(a,b,n) memcmp(a,b,n) +#endif +#ifndef uthash_strlen +#define uthash_strlen(s) strlen(s) +#endif + +#ifndef uthash_noexpand_fyi +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#endif +#ifndef uthash_expand_fyi +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ +#endif + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhp */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) +/* calculate the hash handle from element address elp */ +#define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) + +#define HASH_VALUE(keyptr,keylen,hashv) \ +do { \ + HASH_FCN(keyptr, keylen, hashv); \ +} while (0) + +#define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ +do { \ + (out) = NULL; \ + if (head) { \ + unsigned _hf_bkt; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ + } \ + } \ +} while (0) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + unsigned _hf_hashv; \ + HASH_VALUE(keyptr, keylen, _hf_hashv); \ + HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) +#define HASH_BLOOM_MAKE(tbl) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!(tbl)->bloom_bv) { \ + uthash_fatal("out of memory"); \ + } \ + uthash_bzero((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ +} while (0) + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0) + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1UL << (tbl)->bloom_nbits) - 1U))) + +#else +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#define HASH_BLOOM_BYTELEN 0U +#endif + +#define HASH_MAKE_TABLE(hh,head) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc(sizeof(UT_hash_table)); \ + if (!(head)->hh.tbl) { \ + uthash_fatal("out of memory"); \ + } \ + uthash_bzero((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + if (!(head)->hh.tbl->buckets) { \ + uthash_fatal("out of memory"); \ + } \ + uthash_bzero((head)->hh.tbl->buckets, \ + HASH_INITIAL_NUM_BUCKETS * sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ +} while (0) + +#define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ +do { \ + (replaced) = NULL; \ + HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ + if (replaced) { \ + HASH_DELETE(hh, head, replaced); \ + } \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ +} while (0) + +#define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ +} while (0) + +#define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ +do { \ + unsigned _hr_hashv; \ + HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ + HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ +} while (0) + +#define HASH_APPEND_LIST(hh, head, add) \ +do { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail->next = (add); \ + (head)->hh.tbl->tail = &((add)->hh); \ +} while (0) + +#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ +do { \ + do { \ + if (cmpfcn(DECLTYPE(head)(_hs_iter), add) > 0) { \ + break; \ + } \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ +} while (0) + +#ifdef NO_DECLTYPE +#undef HASH_AKBI_INNER_LOOP +#define HASH_AKBI_INNER_LOOP(hh,head,add,cmpfcn) \ +do { \ + char *_hs_saved_head = (char*)(head); \ + do { \ + DECLTYPE_ASSIGN(head, _hs_iter); \ + if (cmpfcn(head, add) > 0) { \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + break; \ + } \ + DECLTYPE_ASSIGN(head, _hs_saved_head); \ + } while ((_hs_iter = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->next)); \ +} while (0) +#endif + +#define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (char*) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + (head) = (add); \ + HASH_MAKE_TABLE(hh, head); \ + } else { \ + void *_hs_iter = (head); \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_AKBI_INNER_LOOP(hh, head, add, cmpfcn); \ + if (_hs_iter) { \ + (add)->hh.next = _hs_iter; \ + if (((add)->hh.prev = HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev)) { \ + HH_FROM_ELMT((head)->hh.tbl, (add)->hh.prev)->next = (add); \ + } else { \ + (head) = (add); \ + } \ + HH_FROM_ELMT((head)->hh.tbl, _hs_iter)->prev = (add); \ + } else { \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + } \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE_INORDER"); \ +} while (0) + +#define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ +do { \ + unsigned _hs_hashv; \ + HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ + HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) + +#define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ + HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) + +#define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.hashv = (hashval); \ + (add)->hh.key = (const void *) (keyptr); \ + (add)->hh.keylen = (unsigned) (keylen_in); \ + if (!(head)) { \ + (add)->hh.next = NULL; \ + (add)->hh.prev = NULL; \ + (head) = (add); \ + HASH_MAKE_TABLE(hh, head); \ + } else { \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_APPEND_LIST(hh, head, add); \ + } \ + (head)->hh.tbl->num_items++; \ + HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ + HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ + HASH_FSCK(hh, head, "HASH_ADD_KEYPTR_BYHASHVALUE"); \ +} while (0) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_hashv; \ + HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ +} while (0) + +#define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ + HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) + +#define HASH_TO_BKT(hashv,num_bkts,bkt) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1U)); \ +} while (0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ + HASH_DELETE_HH(hh, head, &(delptr)->hh) + +#define HASH_DELETE_HH(hh,head,delptrhh) \ +do { \ + struct UT_hash_handle *_hd_hh_del = (delptrhh); \ + if ((_hd_hh_del->prev == NULL) && (_hd_hh_del->next == NULL)) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } else { \ + unsigned _hd_bkt; \ + if (_hd_hh_del == (head)->hh.tbl->tail) { \ + (head)->hh.tbl->tail = HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev); \ + } \ + if (_hd_hh_del->prev != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->prev)->next = _hd_hh_del->next; \ + } else { \ + DECLTYPE_ASSIGN(head, _hd_hh_del->next); \ + } \ + if (_hd_hh_del->next != NULL) { \ + HH_FROM_ELMT((head)->hh.tbl, _hd_hh_del->next)->prev = _hd_hh_del->prev; \ + } \ + HASH_TO_BKT(_hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT((head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh, head, "HASH_DELETE"); \ +} while (0) + + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) +#define HASH_REPLACE_STR(head,strfield,add,replaced) \ + HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_REPLACE_INT(head,intfield,add,replaced) \ + HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ + HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head,where) \ +do { \ + struct UT_hash_handle *_thh; \ + if (head) { \ + unsigned _bkt_i; \ + unsigned _count = 0; \ + char *_prev; \ + for (_bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; ++_bkt_i) { \ + unsigned _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("%s: invalid hh_prev %p, actual %p\n", \ + (where), (void*)_thh->hh_prev, (void*)_prev); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("%s: invalid bucket count %u, actual %u\n", \ + (where), (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid hh item count %u, actual %u\n", \ + (where), (head)->hh.tbl->num_items, _count); \ + } \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev != (char*)_thh->prev) { \ + HASH_OOPS("%s: invalid prev %p, actual %p\n", \ + (where), (void*)_thh->prev, (void*)_prev); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = (_thh->next ? HH_FROM_ELMT((head)->hh.tbl, _thh->next) : NULL); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("%s: invalid app item count %u, actual %u\n", \ + (where), (head)->hh.tbl->num_items, _count); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head,where) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ +#ifdef HASH_FUNCTION +#define HASH_FCN HASH_FUNCTION +#else +#define HASH_FCN HASH_JEN +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ +#define HASH_BER(key,keylen,hashv) \ +do { \ + unsigned _hb_keylen = (unsigned)keylen; \ + const unsigned char *_hb_key = (const unsigned char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen-- != 0U) { \ + (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ + } \ +} while (0) + + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,hashv) \ +do { \ + unsigned _sx_i; \ + const unsigned char *_hs_key = (const unsigned char*)(key); \ + hashv = 0; \ + for (_sx_i=0; _sx_i < keylen; _sx_i++) { \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + } \ +} while (0) +/* FNV-1a variation */ +#define HASH_FNV(key,keylen,hashv) \ +do { \ + unsigned _fn_i; \ + const unsigned char *_hf_key = (const unsigned char*)(key); \ + (hashv) = 2166136261U; \ + for (_fn_i=0; _fn_i < keylen; _fn_i++) { \ + hashv = hashv ^ _hf_key[_fn_i]; \ + hashv = hashv * 16777619U; \ + } \ +} while (0) + +#define HASH_OAT(key,keylen,hashv) \ +do { \ + unsigned _ho_i; \ + const unsigned char *_ho_key=(const unsigned char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ +} while (0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,hashv) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + unsigned const char *_hj_key=(unsigned const char*)(key); \ + hashv = 0xfeedbeefu; \ + _hj_i = _hj_j = 0x9e3779b9u; \ + _hj_k = (unsigned)(keylen); \ + while (_hj_k >= 12U) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12U; \ + } \ + hashv += (unsigned)(keylen); \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ + case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ + case 1: _hj_i += _hj_key[0]; \ + default: ; /* does not happen */ \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ +} while (0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,hashv) \ +do { \ + unsigned const char *_sfh_key=(unsigned const char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ + \ + unsigned _sfh_rem = _sfh_len & 3U; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabeu; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0U; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2U*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ +} while (0) + +#ifdef HASH_USING_NO_STRICT_ALIASING +/* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. + * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. + * MurmurHash uses the faster approach only on CPU's where we know it's safe. + * + * Note the preprocessor built-in defines can be emitted using: + * + * gcc -m64 -dM -E - < /dev/null (on gcc) + * cc -## a.c (where a.c is a simple test file) (Sun Studio) + */ +#if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) +#define MUR_GETBLOCK(p,i) p[i] +#else /* non intel */ +#define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) +#define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) +#define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) +#define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) +#define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) +#if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) +#define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) +#else /* assume little endian non-intel */ +#define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) +#define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) +#define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) +#endif +#define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ + (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ + (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ + MUR_ONE_THREE(p)))) +#endif +#define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) +#define MUR_FMIX(_h) \ +do { \ + _h ^= _h >> 16; \ + _h *= 0x85ebca6bu; \ + _h ^= _h >> 13; \ + _h *= 0xc2b2ae35u; \ + _h ^= _h >> 16; \ +} while (0) + +#define HASH_MUR(key,keylen,hashv) \ +do { \ + const uint8_t *_mur_data = (const uint8_t*)(key); \ + const int _mur_nblocks = (int)(keylen) / 4; \ + uint32_t _mur_h1 = 0xf88D5353u; \ + uint32_t _mur_c1 = 0xcc9e2d51u; \ + uint32_t _mur_c2 = 0x1b873593u; \ + uint32_t _mur_k1 = 0; \ + const uint8_t *_mur_tail; \ + const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \ + int _mur_i; \ + for (_mur_i = -_mur_nblocks; _mur_i != 0; _mur_i++) { \ + _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + \ + _mur_h1 ^= _mur_k1; \ + _mur_h1 = MUR_ROTL32(_mur_h1,13); \ + _mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \ + } \ + _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ + _mur_k1=0; \ + switch ((keylen) & 3U) { \ + case 0: break; \ + case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ + case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ + case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ + _mur_k1 *= _mur_c1; \ + _mur_k1 = MUR_ROTL32(_mur_k1,15); \ + _mur_k1 *= _mur_c2; \ + _mur_h1 ^= _mur_k1; \ + } \ + _mur_h1 ^= (uint32_t)(keylen); \ + MUR_FMIX(_mur_h1); \ + hashv = _mur_h1; \ +} while (0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ +do { \ + if ((head).hh_head != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ + } else { \ + (out) = NULL; \ + } \ + while ((out) != NULL) { \ + if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ + if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ + break; \ + } \ + } \ + if ((out)->hh.hh_next != NULL) { \ + DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ + } else { \ + (out) = NULL; \ + } \ + } \ +} while (0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,addhh) \ +do { \ + UT_hash_bucket *_ha_head = &(head); \ + _ha_head->count++; \ + (addhh)->hh_next = _ha_head->hh_head; \ + (addhh)->hh_prev = NULL; \ + if (_ha_head->hh_head != NULL) { \ + _ha_head->hh_head->hh_prev = (addhh); \ + } \ + _ha_head->hh_head = (addhh); \ + if ((_ha_head->count >= ((_ha_head->expand_mult + 1U) * HASH_BKT_CAPACITY_THRESH)) \ + && !(addhh)->tbl->noexpand) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while (0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(head,delhh) \ +do { \ + UT_hash_bucket *_hd_head = &(head); \ + _hd_head->count--; \ + if (_hd_head->hh_head == (delhh)) { \ + _hd_head->hh_head = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_prev) { \ + (delhh)->hh_prev->hh_next = (delhh)->hh_next; \ + } \ + if ((delhh)->hh_next) { \ + (delhh)->hh_next->hh_prev = (delhh)->hh_prev; \ + } \ +} while (0) + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(tbl) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { \ + uthash_fatal("out of memory"); \ + } \ + uthash_bzero(_he_new_buckets, \ + 2UL * (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ + (tbl)->ideal_chain_maxlen = \ + ((tbl)->num_items >> ((tbl)->log2_num_buckets+1U)) + \ + ((((tbl)->num_items & (((tbl)->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ + (tbl)->nonideal_items = 0; \ + for (_he_bkt_i = 0; _he_bkt_i < (tbl)->num_buckets; _he_bkt_i++) { \ + _he_thh = (tbl)->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh != NULL) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT(_he_thh->hashv, (tbl)->num_buckets * 2U, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[_he_bkt]); \ + if (++(_he_newbkt->count) > (tbl)->ideal_chain_maxlen) { \ + (tbl)->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / (tbl)->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head != NULL) { \ + _he_newbkt->hh_head->hh_prev = _he_thh; \ + } \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free((tbl)->buckets, (tbl)->num_buckets * sizeof(struct UT_hash_bucket)); \ + (tbl)->num_buckets *= 2U; \ + (tbl)->log2_num_buckets++; \ + (tbl)->buckets = _he_new_buckets; \ + (tbl)->ineff_expands = ((tbl)->nonideal_items > ((tbl)->num_items >> 1)) ? \ + ((tbl)->ineff_expands+1U) : 0U; \ + if ((tbl)->ineff_expands > 1U) { \ + (tbl)->noexpand = 1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ +} while (0) + + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head != NULL) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping != 0U) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p != NULL) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for (_hs_i = 0; _hs_i < _hs_insize; ++_hs_i) { \ + _hs_psize++; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + if (_hs_q == NULL) { \ + break; \ + } \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize != 0U) || ((_hs_qsize != 0U) && (_hs_q != NULL))) { \ + if (_hs_psize == 0U) { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } else if ((_hs_qsize == 0U) || (_hs_q == NULL)) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else if ((cmpfcn( \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl, _hs_q)) \ + )) <= 0) { \ + _hs_e = _hs_p; \ + if (_hs_p != NULL) { \ + _hs_p = ((_hs_p->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_p->next) : NULL); \ + } \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = ((_hs_q->next != NULL) ? \ + HH_FROM_ELMT((head)->hh.tbl, _hs_q->next) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail != NULL ) { \ + _hs_tail->next = ((_hs_e != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl, _hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + if (_hs_e != NULL) { \ + _hs_e->prev = ((_hs_tail != NULL) ? \ + ELMT_FROM_HH((head)->hh.tbl, _hs_tail) : NULL); \ + } \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + if (_hs_tail != NULL) { \ + _hs_tail->next = NULL; \ + } \ + if (_hs_nmerges <= 1U) { \ + _hs_looping = 0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head, ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2U; \ + } \ + HASH_FSCK(hh, head, "HASH_SRT"); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt = NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if ((src) != NULL) { \ + for (_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for (_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh != NULL; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh != NULL) { \ + _last_elt_hh->next = _elt; \ + } \ + if ((dst) == NULL) { \ + DECLTYPE_ASSIGN(dst, _elt); \ + HASH_MAKE_TABLE(hh_dst, dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt], _dst_hh); \ + HASH_BLOOM_ADD(_dst_hh->tbl, _dst_hh->hashv); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst, dst, "HASH_SELECT"); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if ((head) != NULL) { \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head) = NULL; \ + } \ +} while (0) + +#define HASH_OVERHEAD(hh,head) \ + (((head) != NULL) ? ( \ + (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ + ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ + sizeof(UT_hash_table) + \ + (HASH_BLOOM_BYTELEN))) : 0U) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ + (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1u +#define HASH_BLOOM_SIGNATURE 0xb12220f2u + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + uint8_t bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + const void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/utlist.h b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/utlist.h new file mode 100644 index 00000000..2f4c0840 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/libcoap/include/coap2/utlist.h @@ -0,0 +1,1073 @@ +/* +Copyright (c) 2007-2017, Troy D. Hanson http://troydhanson.github.com/uthash/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 2.0.2 + +#include + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) this code uses whatever method is needed + or, for VS2008 where neither is available, uses casting workarounds. */ +#if !defined(LDECLTYPE) && !defined(NO_DECLTYPE) +#if defined(_MSC_VER) /* MS compiler */ +#if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#endif +#elif defined(__BORLANDC__) || defined(__ICCARM__) || defined(__LCC__) || defined(__WATCOMC__) +#define NO_DECLTYPE +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define IF_NO_DECLTYPE(x) x +#define LDECLTYPE(x) char* +#define UTLIST_SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define UTLIST_NEXT(elt,list,next) ((char*)((list)->next)) +#define UTLIST_NEXTASGN(elt,list,to,next) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +/* #define UTLIST_PREV(elt,list,prev) ((char*)((list)->prev)) */ +#define UTLIST_PREVASGN(elt,list,to,prev) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define UTLIST_RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define UTLIST_CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define IF_NO_DECLTYPE(x) +#define UTLIST_SV(elt,list) +#define UTLIST_NEXT(elt,list,next) ((elt)->next) +#define UTLIST_NEXTASGN(elt,list,to,next) ((elt)->next)=(to) +/* #define UTLIST_PREV(elt,list,prev) ((elt)->prev) */ +#define UTLIST_PREVASGN(elt,list,to,prev) ((elt)->prev)=(to) +#define UTLIST_RS(list) +#define UTLIST_CASTASGN(a,b) (a)=(b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) \ + LL_SORT2(list, cmp, next) + +#define LL_SORT2(list, cmp, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q,list); _ls_q = UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,NULL,next); UTLIST_RS(list); \ + } \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + + +#define DL_SORT(list, cmp) \ + DL_SORT2(list, cmp, prev, next) + +#define DL_SORT2(list, cmp, prev, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + IF_NO_DECLTYPE(LDECLTYPE(list) _tmp;) \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q,list); _ls_q = UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while ((_ls_psize > 0) || ((_ls_qsize > 0) && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + } else if ((_ls_qsize == 0) || (!_ls_q)) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list,_ls_e); \ + } \ + UTLIST_SV(_ls_e,list); UTLIST_PREVASGN(_ls_e,list,_ls_tail,prev); UTLIST_RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + UTLIST_CASTASGN((list)->prev, _ls_tail); \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,NULL,next); UTLIST_RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + +#define CDL_SORT(list, cmp) \ + CDL_SORT2(list, cmp, prev, next) + +#define CDL_SORT2(list, cmp, prev, next) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + UTLIST_CASTASGN(_ls_p,list); \ + UTLIST_CASTASGN(_ls_oldhead,list); \ + (list) = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + UTLIST_SV(_ls_q,list); \ + if (UTLIST_NEXT(_ls_q,list,next) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = UTLIST_NEXT(_ls_q,list,next); \ + } \ + UTLIST_RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; UTLIST_SV(_ls_p,list); _ls_p = \ + UTLIST_NEXT(_ls_p,list,next); UTLIST_RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; UTLIST_SV(_ls_q,list); _ls_q = \ + UTLIST_NEXT(_ls_q,list,next); UTLIST_RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_ls_e,next); UTLIST_RS(list); \ + } else { \ + UTLIST_CASTASGN(list,_ls_e); \ + } \ + UTLIST_SV(_ls_e,list); UTLIST_PREVASGN(_ls_e,list,_ls_tail,prev); UTLIST_RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + UTLIST_CASTASGN((list)->prev,_ls_tail); \ + UTLIST_CASTASGN(_tmp,list); \ + UTLIST_SV(_ls_tail,list); UTLIST_NEXTASGN(_ls_tail,list,_tmp,next); UTLIST_RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } \ +} while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head,add) \ + LL_PREPEND2(head,add,next) + +#define LL_PREPEND2(head,add,next) \ +do { \ + (add)->next = (head); \ + (head) = (add); \ +} while (0) + +#define LL_CONCAT(head1,head2) \ + LL_CONCAT2(head1,head2,next) + +#define LL_CONCAT2(head1,head2,next) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head1) { \ + _tmp = (head1); \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(head2); \ + } else { \ + (head1)=(head2); \ + } \ +} while (0) + +#define LL_APPEND(head,add) \ + LL_APPEND2(head,add,next) + +#define LL_APPEND2(head,add,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + (add)->next=NULL; \ + if (head) { \ + _tmp = (head); \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(add); \ + } else { \ + (head)=(add); \ + } \ +} while (0) + +#define LL_INSERT_INORDER(head,add,cmp) \ + LL_INSERT_INORDER2(head,add,cmp,next) + +#define LL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + LL_LOWER_BOUND(head, _tmp, add, cmp); \ + LL_APPEND_ELEM(head, _tmp, add); \ + } else { \ + (head) = (add); \ + (head)->next = NULL; \ + } \ +} while (0) + +#define LL_LOWER_BOUND(head,elt,like,cmp) \ + LL_LOWER_BOUND2(head,elt,like,cmp,next) + +#define LL_LOWER_BOUND2(head,elt,like,cmp,next) \ + do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ + if (cmp((elt)->next, like) >= 0) { \ + break; \ + } \ + } \ + } \ + } while (0) + +#define LL_DELETE(head,del) \ + LL_DELETE2(head,del,next) + +#define LL_DELETE2(head,del,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (del)->next; \ + } \ + } \ +} while (0) + +#define LL_COUNT(head,el,counter) \ + LL_COUNT2(head,el,counter,next) \ + +#define LL_COUNT2(head,el,counter,next) \ +do { \ + (counter) = 0; \ + LL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define LL_FOREACH(head,el) \ + LL_FOREACH2(head,el,next) + +#define LL_FOREACH2(head,el,next) \ + for ((el) = (head); el; (el) = (el)->next) + +#define LL_FOREACH_SAFE(head,el,tmp) \ + LL_FOREACH_SAFE2(head,el,tmp,next) + +#define LL_FOREACH_SAFE2(head,el,tmp,next) \ + for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +#define LL_SEARCH_SCALAR(head,out,field,val) \ + LL_SEARCH_SCALAR2(head,out,field,val,next) + +#define LL_SEARCH_SCALAR2(head,out,field,val,next) \ +do { \ + LL_FOREACH2(head,out,next) { \ + if ((out)->field == (val)) break; \ + } \ +} while (0) + +#define LL_SEARCH(head,out,elt,cmp) \ + LL_SEARCH2(head,out,elt,cmp,next) + +#define LL_SEARCH2(head,out,elt,cmp,next) \ +do { \ + LL_FOREACH2(head,out,next) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while (0) + +#define LL_REPLACE_ELEM2(head, el, add, next) \ +do { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ +} while (0) + +#define LL_REPLACE_ELEM(head, el, add) \ + LL_REPLACE_ELEM2(head, el, add, next) + +#define LL_PREPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + LDECLTYPE(head) _tmp; \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + _tmp = (head); \ + while (_tmp->next && (_tmp->next != (el))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = (add); \ + } \ + } \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ +} while (0) \ + +#define LL_PREPEND_ELEM(head, el, add) \ + LL_PREPEND_ELEM2(head, el, add, next) + +#define LL_APPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (el)->next = (add); \ + } else { \ + LL_PREPEND2(head, add, next); \ + } \ +} while (0) \ + +#define LL_APPEND_ELEM(head, el, add) \ + LL_APPEND_ELEM2(head, el, add, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef LL_CONCAT2 +#define LL_CONCAT2(head1,head2,next) \ +do { \ + char *_tmp; \ + if (head1) { \ + _tmp = (char*)(head1); \ + while ((head1)->next) { (head1) = (head1)->next; } \ + (head1)->next = (head2); \ + UTLIST_RS(head1); \ + } else { \ + (head1)=(head2); \ + } \ +} while (0) + +#undef LL_APPEND2 +#define LL_APPEND2(head,add,next) \ +do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { (add)->next = (add)->next->next; } \ + (add)->next->next=(add); \ + } else { \ + (head)=(add); \ + } \ + (add)->next=NULL; \ +} while (0) + +#undef LL_INSERT_INORDER2 +#define LL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + if ((head) == NULL || (cmp(head, add)) >= 0) { \ + (add)->next = (head); \ + (head) = (add); \ + } else { \ + char *_tmp = (char*)(head); \ + while ((head)->next != NULL && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->next = (head)->next; \ + (head)->next = (add); \ + UTLIST_RS(head); \ + } \ +} while (0) + +#undef LL_DELETE2 +#define LL_DELETE2(head,del,next) \ +do { \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + char *_tmp = (char*)(head); \ + while ((head)->next && ((head)->next != (del))) { \ + (head) = (head)->next; \ + } \ + if ((head)->next) { \ + (head)->next = ((del)->next); \ + } \ + UTLIST_RS(head); \ + } \ +} while (0) + +#undef LL_REPLACE_ELEM2 +#define LL_REPLACE_ELEM2(head, el, add, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = head; \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el)->next; \ +} while (0) + +#undef LL_PREPEND_ELEM2 +#define LL_PREPEND_ELEM2(head, el, add, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->next = (head); \ + while ((add)->next->next && ((add)->next->next != (el))) { \ + (add)->next = (add)->next->next; \ + } \ + if ((add)->next->next) { \ + (add)->next->next = (add); \ + } \ + } \ + (add)->next = (el); \ + } else { \ + LL_APPEND2(head, add, next); \ + } \ +} while (0) \ + +#endif /* NO_DECLTYPE */ + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head,add) \ + DL_PREPEND2(head,add,prev,next) + +#define DL_PREPEND2(head,add,prev,next) \ +do { \ + (add)->next = (head); \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define DL_APPEND(head,add) \ + DL_APPEND2(head,add,prev,next) + +#define DL_APPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head)=(add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0) + +#define DL_INSERT_INORDER(head,add,cmp) \ + DL_INSERT_INORDER2(head,add,cmp,next) + +#define DL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + DL_LOWER_BOUND(head, _tmp, add, cmp); \ + DL_APPEND_ELEM(head, _tmp, add); \ + } else { \ + (head) = (add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0) + +#define DL_LOWER_BOUND(head,elt,like,cmp) \ + DL_LOWER_BOUND2(head,elt,like,cmp,next) + +#define DL_LOWER_BOUND2(head,elt,like,cmp,next) \ +do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != NULL; (elt) = (elt)->next) { \ + if ((cmp((elt)->next, like)) >= 0) { \ + break; \ + } \ + } \ + } \ +} while (0) + +#define DL_CONCAT(head1,head2) \ + DL_CONCAT2(head1,head2,prev,next) + +#define DL_CONCAT2(head1,head2,prev,next) \ +do { \ + LDECLTYPE(head1) _tmp; \ + if (head2) { \ + if (head1) { \ + UTLIST_CASTASGN(_tmp, (head2)->prev); \ + (head2)->prev = (head1)->prev; \ + (head1)->prev->next = (head2); \ + UTLIST_CASTASGN((head1)->prev, _tmp); \ + } else { \ + (head1)=(head2); \ + } \ + } \ +} while (0) + +#define DL_DELETE(head,del) \ + DL_DELETE2(head,del,prev,next) + +#define DL_DELETE2(head,del,prev,next) \ +do { \ + assert((head) != NULL); \ + assert((del)->prev != NULL); \ + if ((del)->prev == (del)) { \ + (head)=NULL; \ + } else if ((del)==(head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ +} while (0) + +#define DL_COUNT(head,el,counter) \ + DL_COUNT2(head,el,counter,next) \ + +#define DL_COUNT2(head,el,counter,next) \ +do { \ + (counter) = 0; \ + DL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define DL_FOREACH(head,el) \ + DL_FOREACH2(head,el,next) + +#define DL_FOREACH2(head,el,next) \ + for ((el) = (head); el; (el) = (el)->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head,el,tmp) \ + DL_FOREACH_SAFE2(head,el,tmp,next) + +#define DL_FOREACH_SAFE2(head,el,tmp,next) \ + for ((el) = (head); (el) && ((tmp) = (el)->next, 1); (el) = (tmp)) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH +#define DL_SEARCH_SCALAR2 LL_SEARCH_SCALAR2 +#define DL_SEARCH2 LL_SEARCH2 + +#define DL_REPLACE_ELEM2(head, el, add, prev, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((head) == (el)) { \ + (head) = (add); \ + (add)->next = (el)->next; \ + if ((el)->next == NULL) { \ + (add)->prev = (add); \ + } else { \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + } \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->prev->next = (add); \ + if ((el)->next == NULL) { \ + (head)->prev = (add); \ + } else { \ + (add)->next->prev = (add); \ + } \ + } \ +} while (0) + +#define DL_REPLACE_ELEM(head, el, add) \ + DL_REPLACE_ELEM2(head, el, add, prev, next) + +#define DL_PREPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } else { \ + (add)->prev->next = (add); \ + } \ + } else { \ + DL_APPEND2(head, add, prev, next); \ + } \ +} while (0) \ + +#define DL_PREPEND_ELEM(head, el, add) \ + DL_PREPEND_ELEM2(head, el, add, prev, next) + +#define DL_APPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + if ((add)->next) { \ + (add)->next->prev = (add); \ + } else { \ + (head)->prev = (add); \ + } \ + } else { \ + DL_PREPEND2(head, add, prev, next); \ + } \ +} while (0) \ + +#define DL_APPEND_ELEM(head, el, add) \ + DL_APPEND_ELEM2(head, el, add, prev, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef DL_INSERT_INORDER2 +#define DL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + if ((head) == NULL) { \ + (add)->prev = (add); \ + (add)->next = NULL; \ + (head) = (add); \ + } else if ((cmp(head, add)) >= 0) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (head) = (add); \ + } else { \ + char *_tmp = (char*)(head); \ + while ((char*)(head)->next != _tmp && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->prev = (head); \ + (add)->next = (head)->next; \ + (head)->next = (add); \ + UTLIST_RS(head); \ + if ((add)->next) { \ + (add)->next->prev = (add); \ + } else { \ + (head)->prev = (add); \ + } \ + } \ +} while (0) +#endif /* NO_DECLTYPE */ + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_APPEND(head,add) \ + CDL_APPEND2(head,add,prev,next) + +#define CDL_APPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + (head) = (add); \ + } \ +} while (0) + +#define CDL_PREPEND(head,add) \ + CDL_PREPEND2(head,add,prev,next) + +#define CDL_PREPEND2(head,add,prev,next) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define CDL_INSERT_INORDER(head,add,cmp) \ + CDL_INSERT_INORDER2(head,add,cmp,next) + +#define CDL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + LDECLTYPE(head) _tmp; \ + if (head) { \ + CDL_LOWER_BOUND(head, _tmp, add, cmp); \ + CDL_APPEND_ELEM(head, _tmp, add); \ + } else { \ + (head) = (add); \ + (head)->next = (head); \ + (head)->prev = (head); \ + } \ +} while (0) + +#define CDL_LOWER_BOUND(head,elt,like,cmp) \ + CDL_LOWER_BOUND2(head,elt,like,cmp,next) + +#define CDL_LOWER_BOUND2(head,elt,like,cmp,next) \ +do { \ + if ((head) == NULL || (cmp(head, like)) >= 0) { \ + (elt) = NULL; \ + } else { \ + for ((elt) = (head); (elt)->next != (head); (elt) = (elt)->next) { \ + if ((cmp((elt)->next, like)) >= 0) { \ + break; \ + } \ + } \ + } \ +} while (0) + +#define CDL_DELETE(head,del) \ + CDL_DELETE2(head,del,prev,next) + +#define CDL_DELETE2(head,del,prev,next) \ +do { \ + if (((head)==(del)) && ((head)->next == (head))) { \ + (head) = NULL; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) (head)=(del)->next; \ + } \ +} while (0) + +#define CDL_COUNT(head,el,counter) \ + CDL_COUNT2(head,el,counter,next) \ + +#define CDL_COUNT2(head, el, counter,next) \ +do { \ + (counter) = 0; \ + CDL_FOREACH2(head,el,next) { ++(counter); } \ +} while (0) + +#define CDL_FOREACH(head,el) \ + CDL_FOREACH2(head,el,next) + +#define CDL_FOREACH2(head,el,next) \ + for ((el)=(head);el;(el)=(((el)->next==(head)) ? NULL : (el)->next)) + +#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ + CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) + +#define CDL_FOREACH_SAFE2(head,el,tmp1,tmp2,prev,next) \ + for ((el) = (head), (tmp1) = (head) ? (head)->prev : NULL; \ + (el) && ((tmp2) = (el)->next, 1); \ + (el) = ((el) == (tmp1) ? NULL : (tmp2))) + +#define CDL_SEARCH_SCALAR(head,out,field,val) \ + CDL_SEARCH_SCALAR2(head,out,field,val,next) + +#define CDL_SEARCH_SCALAR2(head,out,field,val,next) \ +do { \ + CDL_FOREACH2(head,out,next) { \ + if ((out)->field == (val)) break; \ + } \ +} while (0) + +#define CDL_SEARCH(head,out,elt,cmp) \ + CDL_SEARCH2(head,out,elt,cmp,next) + +#define CDL_SEARCH2(head,out,elt,cmp,next) \ +do { \ + CDL_FOREACH2(head,out,next) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while (0) + +#define CDL_REPLACE_ELEM2(head, el, add, prev, next) \ +do { \ + assert((head) != NULL); \ + assert((el) != NULL); \ + assert((add) != NULL); \ + if ((el)->next == (el)) { \ + (add)->next = (add); \ + (add)->prev = (add); \ + (head) = (add); \ + } else { \ + (add)->next = (el)->next; \ + (add)->prev = (el)->prev; \ + (add)->next->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } \ +} while (0) + +#define CDL_REPLACE_ELEM(head, el, add) \ + CDL_REPLACE_ELEM2(head, el, add, prev, next) + +#define CDL_PREPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el); \ + (add)->prev = (el)->prev; \ + (el)->prev = (add); \ + (add)->prev->next = (add); \ + if ((head) == (el)) { \ + (head) = (add); \ + } \ + } else { \ + CDL_APPEND2(head, add, prev, next); \ + } \ +} while (0) + +#define CDL_PREPEND_ELEM(head, el, add) \ + CDL_PREPEND_ELEM2(head, el, add, prev, next) + +#define CDL_APPEND_ELEM2(head, el, add, prev, next) \ +do { \ + if (el) { \ + assert((head) != NULL); \ + assert((add) != NULL); \ + (add)->next = (el)->next; \ + (add)->prev = (el); \ + (el)->next = (add); \ + (add)->next->prev = (add); \ + } else { \ + CDL_PREPEND2(head, add, prev, next); \ + } \ +} while (0) + +#define CDL_APPEND_ELEM(head, el, add) \ + CDL_APPEND_ELEM2(head, el, add, prev, next) + +#ifdef NO_DECLTYPE +/* Here are VS2008 / NO_DECLTYPE replacements for a few functions */ + +#undef CDL_INSERT_INORDER2 +#define CDL_INSERT_INORDER2(head,add,cmp,next) \ +do { \ + if ((head) == NULL) { \ + (add)->prev = (add); \ + (add)->next = (add); \ + (head) = (add); \ + } else if ((cmp(head, add)) >= 0) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (add)->prev->next = (add); \ + (head)->prev = (add); \ + (head) = (add); \ + } else { \ + char *_tmp = (char*)(head); \ + while ((char*)(head)->next != _tmp && (cmp((head)->next, add)) < 0) { \ + (head) = (head)->next; \ + } \ + (add)->prev = (head); \ + (add)->next = (head)->next; \ + (add)->next->prev = (add); \ + (head)->next = (add); \ + UTLIST_RS(head); \ + } \ +} while (0) +#endif /* NO_DECLTYPE */ + +#endif /* UTLIST_H */ diff --git a/tools/sdk/esp32c3/include/coap/port/include/coap/coap.h b/tools/sdk/esp32c3/include/coap/port/include/coap/coap.h new file mode 100644 index 00000000..f048ca85 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/port/include/coap/coap.h @@ -0,0 +1,50 @@ +/* Modify head file implementation for ESP32 platform. + * + * Uses libcoap software implementation for failover when concurrent + * define operations are in use. + * + * coap.h -- main header file for CoAP stack of libcoap + * + * Copyright (C) 2010-2012,2015-2016 Olaf Bergmann + * 2015 Carsten Schoenert + * + * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef _COAP_H_ +#define _COAP_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "libcoap.h" + +#include "address.h" +#include "async.h" +#include "bits.h" +#include "block.h" +#include "coap_dtls.h" +#include "coap_event.h" +#include "coap_io.h" +#include "coap_time.h" +#include "coap_debug.h" +#include "encode.h" +#include "mem.h" +#include "net.h" +#include "option.h" +#include "pdu.h" +#include "prng.h" +#include "resource.h" +#include "str.h" +#include "subscribe.h" +#include "uri.h" + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/port/include/coap/coap_dtls.h b/tools/sdk/esp32c3/include/coap/port/include/coap/coap_dtls.h new file mode 100644 index 00000000..2dd0e88d --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/port/include/coap/coap_dtls.h @@ -0,0 +1,631 @@ +/* + * coap_dtls.h -- (Datagram) Transport Layer Support for libcoap + * + * Copyright (C) 2016 Olaf Bergmann + * Copyright (C) 2017 Jean-Claude Michelou + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_DTLS_H_ +#define COAP_DTLS_H_ + +#include "coap_time.h" +#include "str.h" + +struct coap_context_t; +struct coap_session_t; +struct coap_dtls_pki_t; + +/** + * @defgroup dtls DTLS Support + * API functions for interfacing with DTLS libraries. + * @{ + */ + +/** + * Check whether DTLS is available. + * + * @return @c 1 if support for DTLS is enabled, or @c 0 otherwise. + */ +int coap_dtls_is_supported(void); + +/** + * Check whether TLS is available. + * + * @return @c 1 if support for TLS is enabled, or @c 0 otherwise. + */ +int coap_tls_is_supported(void); + +typedef enum coap_tls_library_t { + COAP_TLS_LIBRARY_NOTLS = 0, /**< No DTLS library */ + COAP_TLS_LIBRARY_TINYDTLS, /**< Using TinyDTLS library */ + COAP_TLS_LIBRARY_OPENSSL, /**< Using OpenSSL library */ + COAP_TLS_LIBRARY_GNUTLS, /**< Using GnuTLS library */ + COAP_TLS_LIBRARY_MBEDTLS, /**< Using MbedTLS library */ +} coap_tls_library_t; + +/** + * The structure used for returning the underlying (D)TLS library + * information. + */ +typedef struct coap_tls_version_t { + uint64_t version; /**< (D)TLS runtime Library Version */ + coap_tls_library_t type; /**< Library type. One of COAP_TLS_LIBRARY_* */ + uint64_t built_version; /**< (D)TLS Built against Library Version */ +} coap_tls_version_t; + +/** + * Determine the type and version of the underlying (D)TLS library. + * + * @return The version and type of library libcoap was compiled against. + */ +coap_tls_version_t *coap_get_tls_library_version(void); + +/** + * Additional Security setup handler that can be set up by + * coap_context_set_pki(). + * Invoked when libcoap has done the validation checks at the TLS level, + * but the application needs to do some additional checks/changes/updates. + * + * @param tls_session The security session definition - e.g. SSL * for OpenSSL. + * NULL if server call-back. + * This will be dependent on the underlying TLS library - + * see coap_get_tls_library_version() + * @param setup_data A structure containing setup data originally passed into + * coap_context_set_pki() or coap_new_client_session_pki(). + * + * @return @c 1 if successful, else @c 0. + */ +typedef int (*coap_dtls_security_setup_t)(void* tls_session, + struct coap_dtls_pki_t *setup_data); + +/** + * CN Validation call-back that can be set up by coap_context_set_pki(). + * Invoked when libcoap has done the validation checks at the TLS level, + * but the application needs to check that the CN is allowed. + * CN is the SubjectAltName in the cert, if not present, then the leftmost + * Common Name (CN) component of the subject name. + * + * @param cn The determined CN from the certificate + * @param asn1_public_cert The ASN.1 DER encoded X.509 certificate + * @param asn1_length The ASN.1 length + * @param coap_session The CoAP session associated with the certificate update + * @param depth Depth in cert chain. If 0, then client cert, else a CA + * @param validated TLS layer can find no issues if 1 + * @param arg The same as was passed into coap_context_set_pki() + * in setup_data->cn_call_back_arg + * + * @return @c 1 if accepted, else @c 0 if to be rejected. + */ +typedef int (*coap_dtls_cn_callback_t)(const char *cn, + const uint8_t *asn1_public_cert, + size_t asn1_length, + struct coap_session_t *coap_session, + unsigned depth, + int validated, + void *arg); + +/** + * The enum used for determining the provided PKI ASN.1 (DER) Private Key + * formats. + */ +typedef enum coap_asn1_privatekey_type_t { + COAP_ASN1_PKEY_NONE, /**< NONE */ + COAP_ASN1_PKEY_RSA, /**< RSA type */ + COAP_ASN1_PKEY_RSA2, /**< RSA2 type */ + COAP_ASN1_PKEY_DSA, /**< DSA type */ + COAP_ASN1_PKEY_DSA1, /**< DSA1 type */ + COAP_ASN1_PKEY_DSA2, /**< DSA2 type */ + COAP_ASN1_PKEY_DSA3, /**< DSA3 type */ + COAP_ASN1_PKEY_DSA4, /**< DSA4 type */ + COAP_ASN1_PKEY_DH, /**< DH type */ + COAP_ASN1_PKEY_DHX, /**< DHX type */ + COAP_ASN1_PKEY_EC, /**< EC type */ + COAP_ASN1_PKEY_HMAC, /**< HMAC type */ + COAP_ASN1_PKEY_CMAC, /**< CMAC type */ + COAP_ASN1_PKEY_TLS1_PRF, /**< TLS1_PRF type */ + COAP_ASN1_PKEY_HKDF /**< HKDF type */ +} coap_asn1_privatekey_type_t; + +/** + * The enum used for determining the PKI key formats. + */ +typedef enum coap_pki_key_t { + COAP_PKI_KEY_PEM = 0, /**< The PKI key type is PEM file */ + COAP_PKI_KEY_ASN1, /**< The PKI key type is ASN.1 (DER) */ + COAP_PKI_KEY_PEM_BUF, /**< The PKI key type is PEM buffer */ +} coap_pki_key_t; + +/** + * The structure that holds the PKI PEM definitions. + */ +typedef struct coap_pki_key_pem_t { + const char *ca_file; /**< File location of Common CA in PEM format */ + const char *public_cert; /**< File location of Public Cert in PEM format */ + const char *private_key; /**< File location of Private Key in PEM format */ +} coap_pki_key_pem_t; + +/** + * The structure that holds the PKI PEM buffer definitions. + */ +typedef struct coap_pki_key_pem_buf_t { + const uint8_t *ca_cert; /**< PEM buffer Common CA Cert */ + const uint8_t *public_cert; /**< PEM buffer Public Cert */ + const uint8_t *private_key; /**< PEM buffer Private Key */ + size_t ca_cert_len; /**< PEM buffer CA Cert length */ + size_t public_cert_len; /**< PEM buffer Public Cert length */ + size_t private_key_len; /**< PEM buffer Private Key length */ +} coap_pki_key_pem_buf_t; + +/** + * The structure that holds the PKI ASN.1 (DER) definitions. + */ +typedef struct coap_pki_key_asn1_t { + const uint8_t *ca_cert; /**< ASN1 (DER) Common CA Cert */ + const uint8_t *public_cert; /**< ASN1 (DER) Public Cert */ + const uint8_t *private_key; /**< ASN1 (DER) Private Key */ + size_t ca_cert_len; /**< ASN1 CA Cert length */ + size_t public_cert_len; /**< ASN1 Public Cert length */ + size_t private_key_len; /**< ASN1 Private Key length */ + coap_asn1_privatekey_type_t private_key_type; /**< Private Key Type */ +} coap_pki_key_asn1_t; + +/** + * The structure that holds the PKI key information. + */ +typedef struct coap_dtls_key_t { + coap_pki_key_t key_type; /**< key format type */ + union { + coap_pki_key_pem_t pem; /**< for PEM file keys */ + coap_pki_key_pem_buf_t pem_buf; /**< for PEM memory keys */ + coap_pki_key_asn1_t asn1; /**< for ASN.1 (DER) file keys */ + } key; +} coap_dtls_key_t; + +/** + * Server Name Indication (SNI) Validation call-back that can be set up by + * coap_context_set_pki(). + * Invoked if the SNI is not previously seen and prior to sending a certificate + * set back to the client so that the appropriate certificate set can be used + * based on the requesting SNI. + * + * @param sni The requested SNI + * @param arg The same as was passed into coap_context_set_pki() + * in setup_data->sni_call_back_arg + * + * @return New set of certificates to use, or @c NULL if SNI is to be rejected. + */ +typedef coap_dtls_key_t *(*coap_dtls_sni_callback_t)(const char *sni, + void* arg); + + +#define COAP_DTLS_PKI_SETUP_VERSION 1 /**< Latest PKI setup version */ + +/** + * The structure used for defining the PKI setup data to be used. + */ +typedef struct coap_dtls_pki_t { + uint8_t version; /** Set to 1 to support this version of the struct */ + + /* Options to enable different TLS functionality in libcoap */ + uint8_t verify_peer_cert; /**< 1 if peer cert is to be verified */ + uint8_t require_peer_cert; /**< 1 if peer cert is required */ + uint8_t allow_self_signed; /**< 1 if self signed certs are allowed */ + uint8_t allow_expired_certs; /**< 1 if expired certs are allowed */ + uint8_t cert_chain_validation; /**< 1 if to check cert_chain_verify_depth */ + uint8_t cert_chain_verify_depth; /**< recommended depth is 3 */ + uint8_t check_cert_revocation; /**< 1 if revocation checks wanted */ + uint8_t allow_no_crl; /**< 1 ignore if CRL not there */ + uint8_t allow_expired_crl; /**< 1 if expired crl is allowed */ + uint8_t allow_bad_md_hash; /**< 1 if expired certs are allowed */ + uint8_t allow_short_rsa_length; /**< 1 if expired certs are allowed */ + uint8_t reserved[4]; /**< Reserved - must be set to 0 for + future compatibility */ + /* Size of 4 chosen to align to next + * parameter, so if newly defined option + * it can use one of the reserverd slot so + * no need to change + * COAP_DTLS_PKI_SETUP_VERSION and just + * decrement the reserved[] count. + */ + + /** CN check call-back function. + * If not NULL, is called when the TLS connection has passed the configured + * TLS options above for the application to verify if the CN is valid. + */ + coap_dtls_cn_callback_t validate_cn_call_back; + void *cn_call_back_arg; /**< Passed in to the CN call-back function */ + + /** SNI check call-back function. + * If not @p NULL, called if the SNI is not previously seen and prior to + * sending a certificate set back to the client so that the appropriate + * certificate set can be used based on the requesting SNI. + */ + coap_dtls_sni_callback_t validate_sni_call_back; + void *sni_call_back_arg; /**< Passed in to the sni call-back function */ + + /** Additional Security call-back handler that is invoked when libcoap has + * done the standerd, defined validation checks at the TLS level, + * If not @p NULL, called from within the TLS Client Hello connection + * setup. + */ + coap_dtls_security_setup_t additional_tls_setup_call_back; + + char* client_sni; /**< If not NULL, SNI to use in client TLS setup. + Owned by the client app and must remain valid + during the call to coap_new_client_session_pki() */ + + coap_dtls_key_t pki_key; /**< PKI key definition */ +} coap_dtls_pki_t; + +/** @} */ + +/** + * @defgroup dtls_internal DTLS Support (Internal) + * Internal API functions for interfacing with DTLS libraries. + * @{ + */ + +/** + * Creates a new DTLS context for the given @p coap_context. This function + * returns a pointer to a new DTLS context object or @c NULL on error. + * + * Internal function. + * + * @param coap_context The CoAP context where the DTLS object shall be used. + * + * @return A DTLS context object or @c NULL on error. + */ +void * +coap_dtls_new_context(struct coap_context_t *coap_context); + +typedef enum coap_dtls_role_t { + COAP_DTLS_ROLE_CLIENT, /**< Internal function invoked for client */ + COAP_DTLS_ROLE_SERVER /**< Internal function invoked for server */ +} coap_dtls_role_t; + +/** + * Set the DTLS context's default PSK information. + * This does the PSK specifics following coap_dtls_new_context(). + * If @p COAP_DTLS_ROLE_SERVER, then identity hint will also get set. + * If @p COAP_DTLS_ROLE_SERVER, then the information will get put into the + * TLS library's context (from which sessions are derived). + * If @p COAP_DTLS_ROLE_CLIENT, then the information will get put into the + * TLS library's session. + * + * Internal function. + * + * @param coap_context The CoAP context. + * @param identity_hint The default PSK server identity hint sent to a client. + * Required parameter. If @p NULL, will be set to "". + * Empty string is a valid hint. + * This parameter is ignored if COAP_DTLS_ROLE_CLIENT + * @param role One of @p COAP_DTLS_ROLE_CLIENT or @p COAP_DTLS_ROLE_SERVER + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_psk(struct coap_context_t *coap_context, + const char *identity_hint, + coap_dtls_role_t role); + +/** + * Set the DTLS context's default server PKI information. + * This does the PKI specifics following coap_dtls_new_context(). + * If @p COAP_DTLS_ROLE_SERVER, then the information will get put into the + * TLS library's context (from which sessions are derived). + * If @p COAP_DTLS_ROLE_CLIENT, then the information will get put into the + * TLS library's session. + * + * Internal function. + * + * @param coap_context The CoAP context. + * @param setup_data Setup information defining how PKI is to be setup. + * Required parameter. If @p NULL, PKI will not be + * set up. + * @param role One of @p COAP_DTLS_ROLE_CLIENT or @p COAP_DTLS_ROLE_SERVER + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_pki(struct coap_context_t *coap_context, + coap_dtls_pki_t *setup_data, + coap_dtls_role_t role); + +/** + * Set the dtls context's default Root CA information for a client or server. + * + * Internal function. + * + * @param coap_context The current coap_context_t object. + * @param ca_file If not @p NULL, is the full path name of a PEM encoded + * file containing all the Root CAs to be used. + * @param ca_dir If not @p NULL, points to a directory containing PEM + * encoded files containing all the Root CAs to be used. + * + * @return @c 1 if successful, else @c 0. + */ + +int +coap_dtls_context_set_pki_root_cas(struct coap_context_t *coap_context, + const char *ca_file, + const char *ca_dir); + +/** + * Check whether one of the coap_dtls_context_set_{psk|pki}() functions have + * been called. + * + * Internal function. + * + * @param coap_context The current coap_context_t object. + * + * @return @c 1 if coap_dtls_context_set_{psk|pki}() called, else @c 0. + */ + +int coap_dtls_context_check_keys_enabled(struct coap_context_t *coap_context); + +/** + * Releases the storage allocated for @p dtls_context. + * + * Internal function. + * + * @param dtls_context The DTLS context as returned by coap_dtls_new_context(). + */ +void coap_dtls_free_context(void *dtls_context); + +/** + * Create a new client-side session. This should send a HELLO to the server. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. +*/ +void *coap_dtls_new_client_session(struct coap_session_t *coap_session); + +/** + * Create a new DTLS server-side session. + * Called after coap_dtls_hello() has returned @c 1, signalling that a validated + * HELLO was received from a client. + * This should send a HELLO to the server. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the DTLS session. + */ +void *coap_dtls_new_server_session(struct coap_session_t *coap_session); + +/** + * Terminates the DTLS session (may send an ALERT if necessary) then frees the + * underlying TLS library object containing security parameters for the session. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_free_session(struct coap_session_t *coap_session); + +/** + * Notify of a change in the CoAP session's MTU, for example after + * a PMTU update. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_session_update_mtu(struct coap_session_t *coap_session); + +/** + * Send data to a DTLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data pointer to data. + * @param data_len Number of bytes to send. + * + * @return @c 0 if this would be blocking, @c -1 if there is an error or the + * number of cleartext bytes sent. + */ +int coap_dtls_send(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Check if timeout is handled per CoAP session or per CoAP context. + * + * Internal function. + * + * @return @c 1 of timeout and retransmit is per context, @c 0 if it is + * per session. + */ +int coap_dtls_is_context_timeout(void); + +/** + * Do all pending retransmits and get next timeout + * + * Internal function. + * + * @param dtls_context The DTLS context. + * + * @return @c 0 if no event is pending or date of the next retransmit. + */ +coap_tick_t coap_dtls_get_context_timeout(void *dtls_context); + +/** + * Get next timeout for this session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param now The current time in ticks. + * + * @return @c 0 If no event is pending or ticks time of the next retransmit. + */ +coap_tick_t coap_dtls_get_timeout(struct coap_session_t *coap_session, + coap_tick_t now); + +/** + * Handle a DTLS timeout expiration. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_dtls_handle_timeout(struct coap_session_t *coap_session); + +/** + * Handling incoming data from a DTLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Encrypted datagram. + * @param data_len Encrypted datagram size. + * + * @return Result of coap_handle_dgram on the decrypted CoAP PDU + * or @c -1 for error. + */ +int coap_dtls_receive(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Handling client HELLO messages from a new candiate peer. + * Note that session->tls is empty. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Encrypted datagram. + * @param data_len Encrypted datagram size. + * + * @return @c 0 if a cookie verification message has been sent, @c 1 if the + * HELLO contains a valid cookie and a server session should be created, + * @c -1 if the message is invalid. + */ +int coap_dtls_hello(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len); + +/** + * Get DTLS overhead over cleartext PDUs. + * + * Internal function. + * + * @param coap_session The CoAP session. + * + * @return Maximum number of bytes added by DTLS layer. + */ +unsigned int coap_dtls_get_overhead(struct coap_session_t *coap_session); + +/** + * Create a new TLS client-side session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param connected Updated with whether the connection is connected yet or not. + * @c 0 is not connected, @c 1 is connected. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. +*/ +void *coap_tls_new_client_session(struct coap_session_t *coap_session, int *connected); + +/** + * Create a TLS new server-side session. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param connected Updated with whether the connection is connected yet or not. + * @c 0 is not connected, @c 1 is connected. + * + * @return Opaque handle to underlying TLS library object containing security + * parameters for the session. + */ +void *coap_tls_new_server_session(struct coap_session_t *coap_session, int *connected); + +/** + * Terminates the TLS session (may send an ALERT if necessary) then frees the + * underlying TLS library object containing security parameters for the session. + * + * Internal function. + * + * @param coap_session The CoAP session. + */ +void coap_tls_free_session( struct coap_session_t *coap_session ); + +/** + * Send data to a TLS peer, with implicit flush. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Pointer to data. + * @param data_len Number of bytes to send. + * + * @return @c 0 if this should be retried, @c -1 if there is an error + * or the number of cleartext bytes sent. + */ +ssize_t coap_tls_write(struct coap_session_t *coap_session, + const uint8_t *data, + size_t data_len + ); + +/** + * Read some data from a TLS peer. + * + * Internal function. + * + * @param coap_session The CoAP session. + * @param data Pointer to data. + * @param data_len Maximum number of bytes to read. + * + * @return @c 0 if this should be retried, @c -1 if there is an error + * or the number of cleartext bytes read. + */ +ssize_t coap_tls_read(struct coap_session_t *coap_session, + uint8_t *data, + size_t data_len + ); + +/** + * Initialize the underlying (D)TLS Library layer. + * + * Internal function. + * + */ +void coap_dtls_startup(void); + +/** @} */ + +/** + * @ingroup logging + * Sets the (D)TLS logging level to the specified @p level. + * Note: coap_log_level() will influence output if at a specified level. + * + * @param level The logging level to use - LOG_* + */ +void coap_dtls_set_log_level(int level); + +/** + * @ingroup logging + * Get the current (D)TLS logging. + * + * @return The current log level (one of LOG_*). + */ +int coap_dtls_get_log_level(void); + + +#endif /* COAP_DTLS_H */ diff --git a/tools/sdk/esp32c3/include/coap/port/include/coap_config.h b/tools/sdk/esp32c3/include/coap/port/include/coap_config.h new file mode 100644 index 00000000..1efa37aa --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/port/include/coap_config.h @@ -0,0 +1,42 @@ +/* + * libcoap configure implementation for ESP32 platform. + * + * Uses libcoap software implementation for failover when concurrent + * configure operations are in use. + * + * coap.h -- main header file for CoAP stack of libcoap + * + * Copyright (C) 2010-2012,2015-2016 Olaf Bergmann + * 2015 Carsten Schoenert + * + * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef _CONFIG_H_ +#define _CONFIG_H_ + +/* Always enabled in ESP-IDF */ +#ifndef WITH_POSIX +#define WITH_POSIX +#endif + +#include "coap_config_posix.h" + +#define HAVE_STDIO_H +#define HAVE_ASSERT_H + +#define PACKAGE_STRING PACKAGE_NAME PACKAGE_VERSION + +/* it's just provided by libc. i hope we don't get too many of those, as + * actually we'd need autotools again to find out what environment we're + * building in */ +#define HAVE_STRNLEN 1 + +#define HAVE_LIMITS_H + +#define COAP_RESOURCES_NOHASH + +#endif /* _CONFIG_H_ */ diff --git a/tools/sdk/esp32c3/include/coap/port/include/coap_config_posix.h b/tools/sdk/esp32c3/include/coap/port/include/coap_config_posix.h new file mode 100644 index 00000000..3f6b7c60 --- /dev/null +++ b/tools/sdk/esp32c3/include/coap/port/include/coap_config_posix.h @@ -0,0 +1,61 @@ +/* + * libcoap configure implementation for ESP32 platform. + * + * Uses libcoap software implementation for failover when concurrent + * configure operations are in use. + * + * coap.h -- main header file for CoAP stack of libcoap + * + * Copyright (C) 2010-2012,2015-2016 Olaf Bergmann + * 2015 Carsten Schoenert + * + * Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD + * + * This file is part of the CoAP library libcoap. Please see README for terms + * of use. + */ + +#ifndef COAP_CONFIG_POSIX_H_ +#define COAP_CONFIG_POSIX_H_ + +#ifdef WITH_POSIX + +#include +#include + +#define HAVE_SYS_SOCKET_H +#define HAVE_MALLOC +#define HAVE_ARPA_INET_H +#define HAVE_TIME_H +#define HAVE_NETDB_H +#define HAVE_NETINET_IN_H +#define HAVE_STRUCT_CMSGHDR + +#define ipi_spec_dst ipi_addr +struct in6_pktinfo { + struct in6_addr ipi6_addr; /* src/dst IPv6 address */ + unsigned int ipi6_ifindex; /* send/recv interface index */ +}; +#define IN6_IS_ADDR_V4MAPPED(a) \ + ((((__const uint32_t *) (a))[0] == 0) \ + && (((__const uint32_t *) (a))[1] == 0) \ + && (((__const uint32_t *) (a))[2] == htonl (0xffff))) + +/* As not defined, just need to define is as something innocuous */ +#define IPV6_PKTINFO IPV6_CHECKSUM + +#define PACKAGE_NAME "libcoap-posix" +#define PACKAGE_VERSION "?" + +#ifdef CONFIG_MBEDTLS_TLS_ENABLED +#define HAVE_MBEDTLS +#endif /* CONFIG_MBEDTLS_TLS_ENABLED */ +#define COAP_CONSTRAINED_STACK 1 +#define ESPIDF_VERSION + +#define _POSIX_TIMERS 1 + +#define gai_strerror(x) "gai_strerror() not supported" + +#endif /* WITH_POSIX */ +#endif /* COAP_CONFIG_POSIX_H_ */ diff --git a/tools/sdk/esp32c3/include/config/sdkconfig.h b/tools/sdk/esp32c3/include/config/sdkconfig.h new file mode 100644 index 00000000..f1c25868 --- /dev/null +++ b/tools/sdk/esp32c3/include/config/sdkconfig.h @@ -0,0 +1,601 @@ +/* + * Automatically generated file. DO NOT EDIT. + * Espressif IoT Development Framework (ESP-IDF) Configuration Header + */ +#pragma once +#define CONFIG_IDF_CMAKE 1 +#define CONFIG_IDF_TARGET_ARCH_RISCV 1 +#define CONFIG_IDF_TARGET "esp32c3" +#define CONFIG_IDF_TARGET_ESP32C3 1 +#define CONFIG_IDF_FIRMWARE_CHIP_ID 0x0005 +#define CONFIG_SDK_TOOLPREFIX "riscv32-esp-elf-" +#define CONFIG_APP_BUILD_TYPE_APP_2NDBOOT 1 +#define CONFIG_APP_BUILD_GENERATE_BINARIES 1 +#define CONFIG_APP_BUILD_BOOTLOADER 1 +#define CONFIG_APP_BUILD_USE_FLASH_SECTIONS 1 +#define CONFIG_APP_COMPILE_TIME_DATE 1 +#define CONFIG_APP_RETRIEVE_LEN_ELF_SHA 16 +#define CONFIG_BOOTLOADER_OFFSET_IN_FLASH 0x0 +#define CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE 1 +#define CONFIG_BOOTLOADER_LOG_LEVEL_INFO 1 +#define CONFIG_BOOTLOADER_LOG_LEVEL 3 +#define CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V 1 +#define CONFIG_BOOTLOADER_WDT_ENABLE 1 +#define CONFIG_BOOTLOADER_WDT_TIME_MS 9000 +#define CONFIG_BOOTLOADER_RESERVE_RTC_SIZE 0x0 +#define CONFIG_SECURE_BOOT_SUPPORTS_RSA 1 +#define CONFIG_SECURE_TARGET_HAS_SECURE_ROM_DL_MODE 1 +#define CONFIG_BOOT_ROM_LOG_ALWAYS_ON 1 +#define CONFIG_ESPTOOLPY_BAUD_OTHER_VAL 115200 +#define CONFIG_ESPTOOLPY_FLASHMODE_DIO 1 +#define CONFIG_ESPTOOLPY_FLASHMODE "dio" +#define CONFIG_ESPTOOLPY_FLASHFREQ_80M 1 +#define CONFIG_ESPTOOLPY_FLASHFREQ "80m" +#define CONFIG_ESPTOOLPY_FLASHSIZE_2MB 1 +#define CONFIG_ESPTOOLPY_FLASHSIZE "2MB" +#define CONFIG_ESPTOOLPY_FLASHSIZE_DETECT 1 +#define CONFIG_ESPTOOLPY_BEFORE_RESET 1 +#define CONFIG_ESPTOOLPY_BEFORE "default_reset" +#define CONFIG_ESPTOOLPY_AFTER_RESET 1 +#define CONFIG_ESPTOOLPY_AFTER "hard_reset" +#define CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B 1 +#define CONFIG_ESPTOOLPY_MONITOR_BAUD_OTHER_VAL 115200 +#define CONFIG_ESPTOOLPY_MONITOR_BAUD 115200 +#define CONFIG_PARTITION_TABLE_SINGLE_APP 1 +#define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" +#define CONFIG_PARTITION_TABLE_FILENAME "partitions_singleapp.csv" +#define CONFIG_PARTITION_TABLE_OFFSET 0x8000 +#define CONFIG_PARTITION_TABLE_MD5 1 +#define CONFIG_ENABLE_ARDUINO_DEPENDS 1 +#define CONFIG_AUTOSTART_ARDUINO 1 +#define CONFIG_ARDUINO_RUN_CORE0 1 +#define CONFIG_ARDUINO_RUNNING_CORE 0 +#define CONFIG_ARDUINO_LOOP_STACK_SIZE 8192 +#define CONFIG_ARDUINO_EVENT_RUN_CORE0 1 +#define CONFIG_ARDUINO_EVENT_RUNNING_CORE 0 +#define CONFIG_ARDUINO_UDP_RUN_CORE0 1 +#define CONFIG_ARDUINO_UDP_TASK_PRIORITY 3 +#define CONFIG_ARDUINO_UDP_RUNNING_CORE 0 +#define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL_ERROR 1 +#define CONFIG_ARDUHAL_LOG_DEFAULT_LEVEL 1 +#define CONFIG_ARDUHAL_PARTITION_SCHEME_DEFAULT 1 +#define CONFIG_ARDUHAL_PARTITION_SCHEME "default" +#define CONFIG_COMPILER_OPTIMIZATION_DEFAULT 1 +#define CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE 1 +#define CONFIG_COMPILER_HIDE_PATHS_MACROS 1 +#define CONFIG_COMPILER_STACK_CHECK_MODE_NONE 1 +#define CONFIG_APPTRACE_DEST_NONE 1 +#define CONFIG_APPTRACE_LOCK_ENABLE 1 +#define CONFIG_BT_ENABLED 1 +#define CONFIG_BT_CTRL_ESP32C3 1 +#define CONFIG_BT_SOC_SUPPORT_5_0 1 +#define CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_EFF 0 +#define CONFIG_BTDM_CTRL_PCM_ROLE_EFF 0 +#define CONFIG_BTDM_CTRL_PCM_POLAR_EFF 0 +#define CONFIG_BTDM_CTRL_BLE_MAX_CONN_EFF 0 +#define CONFIG_BTDM_CTRL_BR_EDR_MAX_ACL_CONN_EFF 0 +#define CONFIG_BTDM_CTRL_BR_EDR_MAX_SYNC_CONN_EFF 0 +#define CONFIG_BTDM_CTRL_PINNED_TO_CORE 0 +#define CONFIG_BTDM_BLE_SLEEP_CLOCK_ACCURACY_INDEX_EFF 1 +#define CONFIG_BT_CTRL_MODE_EFF 1 +#define CONFIG_BT_CTRL_BLE_MAX_ACT 10 +#define CONFIG_BT_CTRL_BLE_MAX_ACT_EFF 10 +#define CONFIG_BT_CTRL_BLE_STATIC_ACL_TX_BUF_NB 0 +#define CONFIG_BT_CTRL_PINNED_TO_CORE 0 +#define CONFIG_BT_CTRL_HCI_MODE_VHCI 1 +#define CONFIG_BT_CTRL_HCI_TL 1 +#define CONFIG_BT_CTRL_ADV_DUP_FILT_MAX 30 +#define CONFIG_BT_CTRL_HW_CCA_EFF 0 +#define CONFIG_BT_CTRL_CE_LENGTH_TYPE_ORIG 1 +#define CONFIG_BT_CTRL_CE_LENGTH_TYPE_EFF 0 +#define CONFIG_BT_CTRL_TX_ANTENNA_INDEX_0 1 +#define CONFIG_BT_CTRL_TX_ANTENNA_INDEX_EFF 0 +#define CONFIG_BT_CTRL_RX_ANTENNA_INDEX_0 1 +#define CONFIG_BT_CTRL_RX_ANTENNA_INDEX_EFF 0 +#define CONFIG_BT_CTRL_DFT_TX_POWER_LEVEL_P3 1 +#define CONFIG_BT_CTRL_DFT_TX_POWER_LEVEL_EFF 10 +#define CONFIG_BT_CTRL_BLE_ADV_REPORT_FLOW_CTRL_SUPP 1 +#define CONFIG_BT_CTRL_BLE_ADV_REPORT_FLOW_CTRL_NUM 100 +#define CONFIG_BT_CTRL_BLE_ADV_REPORT_DISCARD_THRSHOLD 20 +#define CONFIG_BT_CTRL_BLE_SCAN_DUPL 1 +#define CONFIG_BT_CTRL_SCAN_DUPL_TYPE_DEVICE 1 +#define CONFIG_BT_CTRL_SCAN_DUPL_TYPE 0 +#define CONFIG_BT_CTRL_SCAN_DUPL_CACHE_SIZE 100 +#define CONFIG_BT_CTRL_COEX_PHY_CODED_TX_RX_TLIM_DIS 1 +#define CONFIG_BT_CTRL_COEX_PHY_CODED_TX_RX_TLIM_EFF 0 +#define CONFIG_BT_CTRL_SLEEP_MODE_EFF 0 +#define CONFIG_BT_CTRL_SLEEP_CLOCK_EFF 0 +#define CONFIG_BT_CTRL_HCI_TL_EFF 1 +#define CONFIG_BT_BLUEDROID_ENABLED 1 +#define CONFIG_BT_BTC_TASK_STACK_SIZE 3072 +#define CONFIG_BT_BLUEDROID_PINNED_TO_CORE 0 +#define CONFIG_BT_BTU_TASK_STACK_SIZE 4096 +#define CONFIG_BT_BLE_ENABLED 1 +#define CONFIG_BT_GATTS_ENABLE 1 +#define CONFIG_BT_BLE_BLUFI_ENABLE 1 +#define CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_AUTO 1 +#define CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_MODE 0 +#define CONFIG_BT_GATTC_ENABLE 1 +#define CONFIG_BT_BLE_SMP_ENABLE 1 +#define CONFIG_BT_LOG_HCI_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_HCI_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_BTM_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_BTM_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_L2CAP_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_SDP_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_SDP_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_GAP_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_GAP_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_BNEP_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_BNEP_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_PAN_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_PAN_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_A2D_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_A2D_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_AVDT_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_AVDT_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_AVCT_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_AVCT_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_AVRC_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_AVRC_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_MCA_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_MCA_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_HID_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_HID_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_APPL_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_APPL_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_GATT_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_GATT_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_SMP_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_SMP_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_BTIF_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_BTIF_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_BTC_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_BTC_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_OSI_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_OSI_TRACE_LEVEL 2 +#define CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_WARNING 1 +#define CONFIG_BT_LOG_BLUFI_TRACE_LEVEL 2 +#define CONFIG_BT_ACL_CONNECTIONS 4 +#define CONFIG_BT_SMP_ENABLE 1 +#define CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT 30 +#define CONFIG_BT_BLE_RPA_SUPPORTED 1 +#define CONFIG_BT_BLE_50_FEATURES_SUPPORTED 1 +#define CONFIG_BT_RESERVE_DRAM 0xdb5c +#define CONFIG_COAP_MBEDTLS_PSK 1 +#define CONFIG_COAP_LOG_DEFAULT_LEVEL 0 +#define CONFIG_ADC_DISABLE_DAC 1 +#define CONFIG_SPI_MASTER_ISR_IN_IRAM 1 +#define CONFIG_SPI_SLAVE_ISR_IN_IRAM 1 +#define CONFIG_EFUSE_MAX_BLK_LEN 256 +#define CONFIG_ESP_TLS_USING_MBEDTLS 1 +#define CONFIG_ESP_TLS_USE_DS_PERIPHERAL 1 +#define CONFIG_ESP_TLS_SERVER 1 +#define CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160 1 +#define CONFIG_ESP32C3_DEFAULT_CPU_FREQ_MHZ 160 +#define CONFIG_ESP32C3_REV_MIN_0 1 +#define CONFIG_ESP32C3_REV_MIN 0 +#define CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_FOUR 1 +#define CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES 4 +#define CONFIG_ESP32C3_DEBUG_OCDAWARE 1 +#define CONFIG_ESP32C3_BROWNOUT_DET 1 +#define CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_7 1 +#define CONFIG_ESP32C3_BROWNOUT_DET_LVL 7 +#define CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC_SYSTIMER 1 +#define CONFIG_ESP32C3_RTC_CLK_SRC_INT_RC 1 +#define CONFIG_ESP32C3_RTC_CLK_CAL_CYCLES 576 +#define CONFIG_ESP32C3_LIGHTSLEEP_GPIO_RESET_WORKAROUND 1 +#define CONFIG_ESP_ERR_TO_NAME_LOOKUP 1 +#define CONFIG_ETH_ENABLED 1 +#define CONFIG_ETH_USE_SPI_ETHERNET 1 +#define CONFIG_ESP_EVENT_POST_FROM_ISR 1 +#define CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR 1 +#define CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS 1 +#define CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH 1 +#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 512 +#define CONFIG_HTTPD_MAX_URI_LEN 512 +#define CONFIG_HTTPD_ERR_RESP_NO_DELAY 1 +#define CONFIG_HTTPD_PURGE_BUF_LEN 32 +#define CONFIG_HTTPD_WS_SUPPORT 1 +#define CONFIG_ESP_HTTPS_SERVER_ENABLE 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_BT 1 +#define CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH 1 +#define CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL 120 +#define CONFIG_ESP_NETIF_TCPIP_LWIP 1 +#define CONFIG_ESP_NETIF_TCPIP_ADAPTER_COMPATIBLE_LAYER 1 +#define CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT 1 +#define CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE 1 +#define CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK 1 +#define CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP 1 +#define CONFIG_ESP_SYSTEM_PD_FLASH 1 +#define CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU 1 +#define CONFIG_ESP_SYSTEM_MEMPROT_FEATURE 1 +#define CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK 1 +#define CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE 32 +#define CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE 2304 +#define CONFIG_ESP_MAIN_TASK_STACK_SIZE 3584 +#define CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0 1 +#define CONFIG_ESP_MAIN_TASK_AFFINITY 0x0 +#define CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE 2048 +#define CONFIG_ESP_CONSOLE_UART_DEFAULT 1 +#define CONFIG_ESP_CONSOLE_UART 1 +#define CONFIG_ESP_CONSOLE_UART_NUM 0 +#define CONFIG_ESP_CONSOLE_UART_BAUDRATE 115200 +#define CONFIG_ESP_INT_WDT 1 +#define CONFIG_ESP_INT_WDT_TIMEOUT_MS 300 +#define CONFIG_ESP_TASK_WDT 1 +#define CONFIG_ESP_TASK_WDT_TIMEOUT_S 5 +#define CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 1 +#define CONFIG_ESP_IPC_TASK_STACK_SIZE 1024 +#define CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER 1 +#define CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER 1 +#define CONFIG_ESP_TIMER_TASK_STACK_SIZE 3584 +#define CONFIG_ESP_TIMER_INTERRUPT_LEVEL 1 +#define CONFIG_ESP_TIMER_IMPL_SYSTIMER 1 +#define CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE 1 +#define CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM 10 +#define CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM 32 +#define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER 1 +#define CONFIG_ESP32_WIFI_TX_BUFFER_TYPE 1 +#define CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM 32 +#define CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED 1 +#define CONFIG_ESP32_WIFI_TX_BA_WIN 6 +#define CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED 1 +#define CONFIG_ESP32_WIFI_RX_BA_WIN 6 +#define CONFIG_ESP32_WIFI_NVS_ENABLED 1 +#define CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN 752 +#define CONFIG_ESP32_WIFI_MGMT_SBUF_NUM 32 +#define CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE 1 +#define CONFIG_ESP_WIFI_FTM_INITIATOR_SUPPORT 1 +#define CONFIG_ESP_WIFI_FTM_RESPONDER_SUPPORT 1 +#define CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER 20 +#define CONFIG_ESP32_PHY_MAX_TX_POWER 20 +#define CONFIG_ESP_COREDUMP_ENABLE_TO_NONE 1 +#define CONFIG_FATFS_CODEPAGE_437 1 +#define CONFIG_FATFS_CODEPAGE 437 +#define CONFIG_FATFS_LFN_HEAP 1 +#define CONFIG_FATFS_MAX_LFN 255 +#define CONFIG_FATFS_API_ENCODING_ANSI_OEM 1 +#define CONFIG_FATFS_FS_LOCK 0 +#define CONFIG_FATFS_TIMEOUT_MS 10000 +#define CONFIG_FATFS_PER_FILE_CACHE 1 +#define CONFIG_FMB_COMM_MODE_TCP_EN 1 +#define CONFIG_FMB_TCP_PORT_DEFAULT 502 +#define CONFIG_FMB_TCP_PORT_MAX_CONN 5 +#define CONFIG_FMB_TCP_CONNECTION_TOUT_SEC 20 +#define CONFIG_FMB_COMM_MODE_RTU_EN 1 +#define CONFIG_FMB_COMM_MODE_ASCII_EN 1 +#define CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND 150 +#define CONFIG_FMB_MASTER_DELAY_MS_CONVERT 200 +#define CONFIG_FMB_QUEUE_LENGTH 20 +#define CONFIG_FMB_PORT_TASK_STACK_SIZE 4096 +#define CONFIG_FMB_SERIAL_BUF_SIZE 256 +#define CONFIG_FMB_SERIAL_ASCII_BITS_PER_SYMB 8 +#define CONFIG_FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS 1000 +#define CONFIG_FMB_PORT_TASK_PRIO 10 +#define CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT 1 +#define CONFIG_FMB_CONTROLLER_SLAVE_ID 0x00112233 +#define CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT 20 +#define CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE 20 +#define CONFIG_FMB_CONTROLLER_STACK_SIZE 4096 +#define CONFIG_FMB_EVENT_QUEUE_TIMEOUT 20 +#define CONFIG_FMB_TIMER_PORT_ENABLED 1 +#define CONFIG_FMB_TIMER_GROUP 0 +#define CONFIG_FMB_TIMER_INDEX 0 +#define CONFIG_FREERTOS_UNICORE 1 +#define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF +#define CONFIG_FREERTOS_CORETIMER_0 1 +#define CONFIG_FREERTOS_OPTIMIZED_SCHEDULER 1 +#define CONFIG_FREERTOS_HZ 1000 +#define CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION 1 +#define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1 +#define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1 +#define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1 +#define CONFIG_FREERTOS_ASSERT_FAIL_ABORT 1 +#define CONFIG_FREERTOS_IDLE_TASK_STACKSIZE 2304 +#define CONFIG_FREERTOS_ISR_STACKSIZE 1536 +#define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 +#define CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION 1 +#define CONFIG_FREERTOS_TIMER_TASK_PRIORITY 1 +#define CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH 2048 +#define CONFIG_FREERTOS_TIMER_QUEUE_LENGTH 10 +#define CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE 0 +#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1 +#define CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER 1 +#define CONFIG_FREERTOS_DEBUG_OCDAWARE 1 +#define CONFIG_HEAP_POISONING_DISABLED 1 +#define CONFIG_HEAP_TRACING_OFF 1 +#define CONFIG_LOG_DEFAULT_LEVEL_ERROR 1 +#define CONFIG_LOG_DEFAULT_LEVEL 1 +#define CONFIG_LOG_TIMESTAMP_SOURCE_RTOS 1 +#define CONFIG_LWIP_LOCAL_HOSTNAME "espressif" +#define CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES 1 +#define CONFIG_LWIP_TIMERS_ONDEMAND 1 +#define CONFIG_LWIP_MAX_SOCKETS 10 +#define CONFIG_LWIP_SO_REUSE 1 +#define CONFIG_LWIP_SO_REUSE_RXTOALL 1 +#define CONFIG_LWIP_SO_RCVBUF 1 +#define CONFIG_LWIP_IP4_FRAG 1 +#define CONFIG_LWIP_IP6_FRAG 1 +#define CONFIG_LWIP_ESP_GRATUITOUS_ARP 1 +#define CONFIG_LWIP_GARP_TMR_INTERVAL 60 +#define CONFIG_LWIP_TCPIP_RECVMBOX_SIZE 32 +#define CONFIG_LWIP_DHCP_DOES_ARP_CHECK 1 +#define CONFIG_LWIP_DHCPS_LEASE_UNIT 60 +#define CONFIG_LWIP_DHCPS_MAX_STATION_NUM 8 +#define CONFIG_LWIP_IPV6 1 +#define CONFIG_LWIP_NETIF_LOOPBACK 1 +#define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8 +#define CONFIG_LWIP_MAX_ACTIVE_TCP 16 +#define CONFIG_LWIP_MAX_LISTENING_TCP 16 +#define CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION 1 +#define CONFIG_LWIP_TCP_MAXRTX 12 +#define CONFIG_LWIP_TCP_SYNMAXRTX 12 +#define CONFIG_LWIP_TCP_MSS 1440 +#define CONFIG_LWIP_TCP_TMR_INTERVAL 250 +#define CONFIG_LWIP_TCP_MSL 60000 +#define CONFIG_LWIP_TCP_SND_BUF_DEFAULT 5744 +#define CONFIG_LWIP_TCP_WND_DEFAULT 5744 +#define CONFIG_LWIP_TCP_RECVMBOX_SIZE 6 +#define CONFIG_LWIP_TCP_QUEUE_OOSEQ 1 +#define CONFIG_LWIP_TCP_OVERSIZE_MSS 1 +#define CONFIG_LWIP_TCP_RTO_TIME 1500 +#define CONFIG_LWIP_MAX_UDP_PCBS 16 +#define CONFIG_LWIP_UDP_RECVMBOX_SIZE 6 +#define CONFIG_LWIP_CHECKSUM_CHECK_ICMP 1 +#define CONFIG_LWIP_TCPIP_TASK_STACK_SIZE 3072 +#define CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY 1 +#define CONFIG_LWIP_TCPIP_TASK_AFFINITY 0x7FFFFFFF +#define CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE 3 +#define CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS 5 +#define CONFIG_LWIP_MAX_RAW_PCBS 16 +#define CONFIG_LWIP_DHCP_MAX_NTP_SERVERS 1 +#define CONFIG_LWIP_SNTP_UPDATE_DELAY 3600000 +#define CONFIG_LCP_ECHOINTERVAL 0 +#define CONFIG_LCP_MAXECHOFAILS 3 +#define CONFIG_LWIP_ESP_LWIP_ASSERT 1 +#define CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT 1 +#define CONFIG_LWIP_HOOK_IP6_ROUTE_NONE 1 +#define CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE 1 +#define CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC 1 +#define CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN 1 +#define CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN 16384 +#define CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN 4096 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE 1 +#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL 1 +#define CONFIG_MBEDTLS_HARDWARE_AES 1 +#define CONFIG_MBEDTLS_HARDWARE_MPI 1 +#define CONFIG_MBEDTLS_HARDWARE_SHA 1 +#define CONFIG_MBEDTLS_HAVE_TIME 1 +#define CONFIG_MBEDTLS_ECDSA_DETERMINISTIC 1 +#define CONFIG_MBEDTLS_SHA512_C 1 +#define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1 +#define CONFIG_MBEDTLS_TLS_SERVER 1 +#define CONFIG_MBEDTLS_TLS_CLIENT 1 +#define CONFIG_MBEDTLS_TLS_ENABLED 1 +#define CONFIG_MBEDTLS_PSK_MODES 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_PSK 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_PSK 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_PSK 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA_PSK 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_DHE_RSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA 1 +#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA 1 +#define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1 +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1 1 +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_1 1 +#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1 +#define CONFIG_MBEDTLS_SSL_ALPN 1 +#define CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS 1 +#define CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS 1 +#define CONFIG_MBEDTLS_AES_C 1 +#define CONFIG_MBEDTLS_CAMELLIA_C 1 +#define CONFIG_MBEDTLS_RC4_DISABLED 1 +#define CONFIG_MBEDTLS_CCM_C 1 +#define CONFIG_MBEDTLS_GCM_C 1 +#define CONFIG_MBEDTLS_PEM_PARSE_C 1 +#define CONFIG_MBEDTLS_PEM_WRITE_C 1 +#define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1 +#define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1 +#define CONFIG_MBEDTLS_ECP_C 1 +#define CONFIG_MBEDTLS_ECDH_C 1 +#define CONFIG_MBEDTLS_ECDSA_C 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1 +#define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1 +#define CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI 1 +#define CONFIG_MDNS_MAX_SERVICES 10 +#define CONFIG_MDNS_TASK_PRIORITY 1 +#define CONFIG_MDNS_TASK_STACK_SIZE 4096 +#define CONFIG_MDNS_TASK_AFFINITY_CPU0 1 +#define CONFIG_MDNS_TASK_AFFINITY 0x0 +#define CONFIG_MDNS_SERVICE_ADD_TIMEOUT_MS 2000 +#define CONFIG_MDNS_TIMER_PERIOD_MS 100 +#define CONFIG_MQTT_PROTOCOL_311 1 +#define CONFIG_MQTT_TRANSPORT_SSL 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET 1 +#define CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE 1 +#define CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF 1 +#define CONFIG_NEWLIB_STDIN_LINE_ENDING_CR 1 +#define CONFIG_OPENSSL_ERROR_STACK 1 +#define CONFIG_OPENSSL_ASSERT_EXIT 1 +#define CONFIG_PTHREAD_TASK_PRIO_DEFAULT 5 +#define CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT 3072 +#define CONFIG_PTHREAD_STACK_MIN 768 +#define CONFIG_PTHREAD_TASK_CORE_DEFAULT -1 +#define CONFIG_PTHREAD_TASK_NAME_DEFAULT "pthread" +#define CONFIG_SPI_FLASH_ROM_DRIVER_PATCH 1 +#define CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS 1 +#define CONFIG_SPI_FLASH_YIELD_DURING_ERASE 1 +#define CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS 20 +#define CONFIG_SPI_FLASH_ERASE_YIELD_TICKS 1 +#define CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE 8192 +#define CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_GD_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP 1 +#define CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP 1 +#define CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE 1 +#define CONFIG_SPIFFS_MAX_PARTITIONS 3 +#define CONFIG_SPIFFS_CACHE 1 +#define CONFIG_SPIFFS_CACHE_WR 1 +#define CONFIG_SPIFFS_PAGE_CHECK 1 +#define CONFIG_SPIFFS_GC_MAX_RUNS 10 +#define CONFIG_SPIFFS_PAGE_SIZE 256 +#define CONFIG_SPIFFS_OBJ_NAME_LEN 32 +#define CONFIG_SPIFFS_USE_MAGIC 1 +#define CONFIG_SPIFFS_USE_MAGIC_LENGTH 1 +#define CONFIG_SPIFFS_META_LENGTH 4 +#define CONFIG_SPIFFS_USE_MTIME 1 +#define CONFIG_WS_BUFFER_SIZE 1024 +#define CONFIG_UNITY_ENABLE_FLOAT 1 +#define CONFIG_UNITY_ENABLE_DOUBLE 1 +#define CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER 1 +#define CONFIG_VFS_SUPPORT_IO 1 +#define CONFIG_VFS_SUPPORT_DIR 1 +#define CONFIG_VFS_SUPPORT_SELECT 1 +#define CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT 1 +#define CONFIG_VFS_SUPPORT_TERMIOS 1 +#define CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS 1 +#define CONFIG_VFS_SEMIHOSTFS_HOST_PATH_MAX_LEN 128 +#define CONFIG_WL_SECTOR_SIZE_4096 1 +#define CONFIG_WL_SECTOR_SIZE 4096 +#define CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES 16 +#define CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT 30 +#define CONFIG_WPA_MBEDTLS_CRYPTO 1 +#define CONFIG_LITTLEFS_MAX_PARTITIONS 3 +#define CONFIG_LITTLEFS_PAGE_SIZE 256 +#define CONFIG_LITTLEFS_OBJ_NAME_LEN 64 +#define CONFIG_LITTLEFS_READ_SIZE 128 +#define CONFIG_LITTLEFS_WRITE_SIZE 128 +#define CONFIG_LITTLEFS_LOOKAHEAD_SIZE 128 +#define CONFIG_LITTLEFS_CACHE_SIZE 512 +#define CONFIG_LITTLEFS_BLOCK_CYCLES 512 +#define CONFIG_LITTLEFS_USE_MTIME 1 +#define CONFIG_LITTLEFS_MTIME_USE_SECONDS 1 + +/* List of deprecated options */ +#define CONFIG_A2D_TRACE_LEVEL_WARNING CONFIG_BT_LOG_A2D_TRACE_LEVEL_WARNING +#define CONFIG_ADC2_DISABLE_DAC CONFIG_ADC_DISABLE_DAC +#define CONFIG_APPL_TRACE_LEVEL_WARNING CONFIG_BT_LOG_APPL_TRACE_LEVEL_WARNING +#define CONFIG_AVCT_TRACE_LEVEL_WARNING CONFIG_BT_LOG_AVCT_TRACE_LEVEL_WARNING +#define CONFIG_AVDT_TRACE_LEVEL_WARNING CONFIG_BT_LOG_AVDT_TRACE_LEVEL_WARNING +#define CONFIG_AVRC_TRACE_LEVEL_WARNING CONFIG_BT_LOG_AVRC_TRACE_LEVEL_WARNING +#define CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT CONFIG_BT_BLE_ESTAB_LINK_CONN_TOUT +#define CONFIG_BLE_SMP_ENABLE CONFIG_BT_BLE_SMP_ENABLE +#define CONFIG_BLUEDROID_ENABLED CONFIG_BT_BLUEDROID_ENABLED +#define CONFIG_BLUFI_TRACE_LEVEL_WARNING CONFIG_BT_LOG_BLUFI_TRACE_LEVEL_WARNING +#define CONFIG_BTC_TASK_STACK_SIZE CONFIG_BT_BTC_TASK_STACK_SIZE +#define CONFIG_BTC_TRACE_LEVEL_WARNING CONFIG_BT_LOG_BTC_TRACE_LEVEL_WARNING +#define CONFIG_BTIF_TRACE_LEVEL_WARNING CONFIG_BT_LOG_BTIF_TRACE_LEVEL_WARNING +#define CONFIG_BTM_TRACE_LEVEL_WARNING CONFIG_BT_LOG_BTM_TRACE_LEVEL_WARNING +#define CONFIG_BTU_TASK_STACK_SIZE CONFIG_BT_BTU_TASK_STACK_SIZE +#define CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEFAULT +#define CONFIG_CONSOLE_UART_DEFAULT CONFIG_ESP_CONSOLE_UART_DEFAULT +#define CONFIG_ESP32C3_MEMPROT_FEATURE CONFIG_ESP_SYSTEM_MEMPROT_FEATURE +#define CONFIG_ESP32C3_MEMPROT_FEATURE_LOCK CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK +#define CONFIG_ESP32S2_ALLOW_RTC_FAST_MEM_AS_HEAP CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP +#define CONFIG_ESP32S2_MEMPROT_FEATURE CONFIG_ESP_SYSTEM_MEMPROT_FEATURE +#define CONFIG_ESP32S2_MEMPROT_FEATURE_LOCK CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK +#define CONFIG_ESP32S2_PANIC_PRINT_REBOOT CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT +#define CONFIG_ESP32_ALLOW_RTC_FAST_MEM_AS_HEAP CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP +#define CONFIG_ESP32_APPTRACE_DEST_NONE CONFIG_APPTRACE_DEST_NONE +#define CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE CONFIG_ESP_COREDUMP_ENABLE_TO_NONE +#define CONFIG_ESP32_PANIC_PRINT_REBOOT CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT +#define CONFIG_ESP32_PTHREAD_STACK_MIN CONFIG_PTHREAD_STACK_MIN +#define CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT CONFIG_PTHREAD_TASK_NAME_DEFAULT +#define CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT CONFIG_PTHREAD_TASK_PRIO_DEFAULT +#define CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT +#define CONFIG_ESP_GRATUITOUS_ARP CONFIG_LWIP_ESP_GRATUITOUS_ARP +#define CONFIG_FLASHMODE_DIO CONFIG_ESPTOOLPY_FLASHMODE_DIO +#define CONFIG_GAP_TRACE_LEVEL_WARNING CONFIG_BT_LOG_GAP_TRACE_LEVEL_WARNING +#define CONFIG_GARP_TMR_INTERVAL CONFIG_LWIP_GARP_TMR_INTERVAL +#define CONFIG_GATTC_ENABLE CONFIG_BT_GATTC_ENABLE +#define CONFIG_GATTS_ENABLE CONFIG_BT_GATTS_ENABLE +#define CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO CONFIG_BT_GATTS_SEND_SERVICE_CHANGE_AUTO +#define CONFIG_GATT_TRACE_LEVEL_WARNING CONFIG_BT_LOG_GATT_TRACE_LEVEL_WARNING +#define CONFIG_HCI_TRACE_LEVEL_WARNING CONFIG_BT_LOG_HCI_TRACE_LEVEL_WARNING +#define CONFIG_HID_TRACE_LEVEL_WARNING CONFIG_BT_LOG_HID_TRACE_LEVEL_WARNING +#define CONFIG_INT_WDT CONFIG_ESP_INT_WDT +#define CONFIG_INT_WDT_TIMEOUT_MS CONFIG_ESP_INT_WDT_TIMEOUT_MS +#define CONFIG_IPC_TASK_STACK_SIZE CONFIG_ESP_IPC_TASK_STACK_SIZE +#define CONFIG_L2CAP_TRACE_LEVEL_WARNING CONFIG_BT_LOG_L2CAP_TRACE_LEVEL_WARNING +#define CONFIG_LOG_BOOTLOADER_LEVEL_INFO CONFIG_BOOTLOADER_LOG_LEVEL_INFO +#define CONFIG_MAIN_TASK_STACK_SIZE CONFIG_ESP_MAIN_TASK_STACK_SIZE +#define CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE +#define CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT +#define CONFIG_MB_CONTROLLER_SLAVE_ID CONFIG_FMB_CONTROLLER_SLAVE_ID +#define CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT +#define CONFIG_MB_CONTROLLER_STACK_SIZE CONFIG_FMB_CONTROLLER_STACK_SIZE +#define CONFIG_MB_EVENT_QUEUE_TIMEOUT CONFIG_FMB_EVENT_QUEUE_TIMEOUT +#define CONFIG_MB_MASTER_DELAY_MS_CONVERT CONFIG_FMB_MASTER_DELAY_MS_CONVERT +#define CONFIG_MB_MASTER_TIMEOUT_MS_RESPOND CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND +#define CONFIG_MB_QUEUE_LENGTH CONFIG_FMB_QUEUE_LENGTH +#define CONFIG_MB_SERIAL_BUF_SIZE CONFIG_FMB_SERIAL_BUF_SIZE +#define CONFIG_MB_SERIAL_TASK_PRIO CONFIG_FMB_PORT_TASK_PRIO +#define CONFIG_MB_SERIAL_TASK_STACK_SIZE CONFIG_FMB_PORT_TASK_STACK_SIZE +#define CONFIG_MB_TIMER_GROUP CONFIG_FMB_TIMER_GROUP +#define CONFIG_MB_TIMER_INDEX CONFIG_FMB_TIMER_INDEX +#define CONFIG_MB_TIMER_PORT_ENABLED CONFIG_FMB_TIMER_PORT_ENABLED +#define CONFIG_MCA_TRACE_LEVEL_WARNING CONFIG_BT_LOG_MCA_TRACE_LEVEL_WARNING +#define CONFIG_MONITOR_BAUD_115200B CONFIG_ESPTOOLPY_MONITOR_BAUD_115200B +#define CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE +#define CONFIG_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEFAULT +#define CONFIG_OSI_TRACE_LEVEL_WARNING CONFIG_BT_LOG_OSI_TRACE_LEVEL_WARNING +#define CONFIG_PAN_TRACE_LEVEL_WARNING CONFIG_BT_LOG_PAN_TRACE_LEVEL_WARNING +#define CONFIG_POST_EVENTS_FROM_IRAM_ISR CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR +#define CONFIG_POST_EVENTS_FROM_ISR CONFIG_ESP_EVENT_POST_FROM_ISR +#define CONFIG_RFCOMM_TRACE_LEVEL_WARNING CONFIG_BT_LOG_RFCOMM_TRACE_LEVEL_WARNING +#define CONFIG_SDP_TRACE_LEVEL_WARNING CONFIG_BT_LOG_SDP_TRACE_LEVEL_WARNING +#define CONFIG_SEMIHOSTFS_HOST_PATH_MAX_LEN CONFIG_VFS_SEMIHOSTFS_HOST_PATH_MAX_LEN +#define CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS +#define CONFIG_SMP_TRACE_LEVEL_WARNING CONFIG_BT_LOG_SMP_TRACE_LEVEL_WARNING +#define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS +#define CONFIG_STACK_CHECK_NONE CONFIG_COMPILER_STACK_CHECK_MODE_NONE +#define CONFIG_SUPPORT_TERMIOS CONFIG_VFS_SUPPORT_TERMIOS +#define CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT +#define CONFIG_SW_COEXIST_ENABLE CONFIG_ESP32_WIFI_SW_COEXIST_ENABLE +#define CONFIG_SYSTEM_EVENT_QUEUE_SIZE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE +#define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE +#define CONFIG_TASK_WDT CONFIG_ESP_TASK_WDT +#define CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0 CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0 +#define CONFIG_TASK_WDT_TIMEOUT_S CONFIG_ESP_TASK_WDT_TIMEOUT_S +#define CONFIG_TCPIP_RECVMBOX_SIZE CONFIG_LWIP_TCPIP_RECVMBOX_SIZE +#define CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY +#define CONFIG_TCPIP_TASK_STACK_SIZE CONFIG_LWIP_TCPIP_TASK_STACK_SIZE +#define CONFIG_TCP_MAXRTX CONFIG_LWIP_TCP_MAXRTX +#define CONFIG_TCP_MSL CONFIG_LWIP_TCP_MSL +#define CONFIG_TCP_MSS CONFIG_LWIP_TCP_MSS +#define CONFIG_TCP_OVERSIZE_MSS CONFIG_LWIP_TCP_OVERSIZE_MSS +#define CONFIG_TCP_QUEUE_OOSEQ CONFIG_LWIP_TCP_QUEUE_OOSEQ +#define CONFIG_TCP_RECVMBOX_SIZE CONFIG_LWIP_TCP_RECVMBOX_SIZE +#define CONFIG_TCP_SND_BUF_DEFAULT CONFIG_LWIP_TCP_SND_BUF_DEFAULT +#define CONFIG_TCP_SYNMAXRTX CONFIG_LWIP_TCP_SYNMAXRTX +#define CONFIG_TCP_WND_DEFAULT CONFIG_LWIP_TCP_WND_DEFAULT +#define CONFIG_TIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH +#define CONFIG_TIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY +#define CONFIG_TIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH +#define CONFIG_TIMER_TASK_STACK_SIZE CONFIG_ESP_TIMER_TASK_STACK_SIZE +#define CONFIG_TOOLPREFIX CONFIG_SDK_TOOLPREFIX +#define CONFIG_UDP_RECVMBOX_SIZE CONFIG_LWIP_UDP_RECVMBOX_SIZE +#define CONFIG_ARDUINO_IDF_COMMIT "1cb31e509" +#define CONFIG_ARDUINO_IDF_BRANCH "master" diff --git a/tools/sdk/esp32c3/include/console/argtable3/argtable3.h b/tools/sdk/esp32c3/include/console/argtable3/argtable3.h new file mode 100644 index 00000000..abb2009c --- /dev/null +++ b/tools/sdk/esp32c3/include/console/argtable3/argtable3.h @@ -0,0 +1,306 @@ +/******************************************************************************* + * This file is part of the argtable3 library. + * + * Copyright (C) 1998-2001,2003-2011,2013 Stewart Heitmann + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of STEWART HEITMANN nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL STEWART HEITMANN BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************/ + +#ifndef ARGTABLE3 +#define ARGTABLE3 + +#include /* FILE */ +#include /* struct tm */ + +#ifdef __cplusplus +extern "C" { +#endif + +#define ARG_REX_ICASE 1 + +/* bit masks for arg_hdr.flag */ +enum +{ + ARG_TERMINATOR=0x1, + ARG_HASVALUE=0x2, + ARG_HASOPTVALUE=0x4 +}; + +typedef void (arg_resetfn)(void *parent); +typedef int (arg_scanfn)(void *parent, const char *argval); +typedef int (arg_checkfn)(void *parent); +typedef void (arg_errorfn)(void *parent, FILE *fp, int error, const char *argval, const char *progname); + + +/* +* The arg_hdr struct defines properties that are common to all arg_xxx structs. +* The argtable library requires each arg_xxx struct to have an arg_hdr +* struct as its first data member. +* The argtable library functions then use this data to identify the +* properties of the command line option, such as its option tags, +* datatype string, and glossary strings, and so on. +* Moreover, the arg_hdr struct contains pointers to custom functions that +* are provided by each arg_xxx struct which perform the tasks of parsing +* that particular arg_xxx arguments, performing post-parse checks, and +* reporting errors. +* These functions are private to the individual arg_xxx source code +* and are the pointer to them are initiliased by that arg_xxx struct's +* constructor function. The user could alter them after construction +* if desired, but the original intention is for them to be set by the +* constructor and left unaltered. +*/ +struct arg_hdr +{ + char flag; /* Modifier flags: ARG_TERMINATOR, ARG_HASVALUE. */ + const char *shortopts; /* String defining the short options */ + const char *longopts; /* String defiing the long options */ + const char *datatype; /* Description of the argument data type */ + const char *glossary; /* Description of the option as shown by arg_print_glossary function */ + int mincount; /* Minimum number of occurences of this option accepted */ + int maxcount; /* Maximum number of occurences if this option accepted */ + void *parent; /* Pointer to parent arg_xxx struct */ + arg_resetfn *resetfn; /* Pointer to parent arg_xxx reset function */ + arg_scanfn *scanfn; /* Pointer to parent arg_xxx scan function */ + arg_checkfn *checkfn; /* Pointer to parent arg_xxx check function */ + arg_errorfn *errorfn; /* Pointer to parent arg_xxx error function */ + void *priv; /* Pointer to private header data for use by arg_xxx functions */ +}; + +struct arg_rem +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ +}; + +struct arg_lit +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args */ +}; + +struct arg_int +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args */ + int *ival; /* Array of parsed argument values */ +}; + +struct arg_dbl +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args */ + double *dval; /* Array of parsed argument values */ +}; + +struct arg_str +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args */ + const char **sval; /* Array of parsed argument values */ +}; + +struct arg_rex +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args */ + const char **sval; /* Array of parsed argument values */ +}; + +struct arg_file +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of matching command line args*/ + const char **filename; /* Array of parsed filenames (eg: /home/foo.bar) */ + const char **basename; /* Array of parsed basenames (eg: foo.bar) */ + const char **extension; /* Array of parsed extensions (eg: .bar) */ +}; + +struct arg_date +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + const char *format; /* strptime format string used to parse the date */ + int count; /* Number of matching command line args */ + struct tm *tmval; /* Array of parsed time values */ +}; + +enum {ARG_ELIMIT=1, ARG_EMALLOC, ARG_ENOMATCH, ARG_ELONGOPT, ARG_EMISSARG}; +struct arg_end +{ + struct arg_hdr hdr; /* The mandatory argtable header struct */ + int count; /* Number of errors encountered */ + int *error; /* Array of error codes */ + void **parent; /* Array of pointers to offending arg_xxx struct */ + const char **argval; /* Array of pointers to offending argv[] string */ +}; + + +/**** arg_xxx constructor functions *********************************/ + +struct arg_rem* arg_rem(const char* datatype, const char* glossary); + +struct arg_lit* arg_lit0(const char* shortopts, + const char* longopts, + const char* glossary); +struct arg_lit* arg_lit1(const char* shortopts, + const char* longopts, + const char *glossary); +struct arg_lit* arg_litn(const char* shortopts, + const char* longopts, + int mincount, + int maxcount, + const char *glossary); + +struct arg_key* arg_key0(const char* keyword, + int flags, + const char* glossary); +struct arg_key* arg_key1(const char* keyword, + int flags, + const char* glossary); +struct arg_key* arg_keyn(const char* keyword, + int flags, + int mincount, + int maxcount, + const char* glossary); + +struct arg_int* arg_int0(const char* shortopts, + const char* longopts, + const char* datatype, + const char* glossary); +struct arg_int* arg_int1(const char* shortopts, + const char* longopts, + const char* datatype, + const char *glossary); +struct arg_int* arg_intn(const char* shortopts, + const char* longopts, + const char *datatype, + int mincount, + int maxcount, + const char *glossary); + +struct arg_dbl* arg_dbl0(const char* shortopts, + const char* longopts, + const char* datatype, + const char* glossary); +struct arg_dbl* arg_dbl1(const char* shortopts, + const char* longopts, + const char* datatype, + const char *glossary); +struct arg_dbl* arg_dbln(const char* shortopts, + const char* longopts, + const char *datatype, + int mincount, + int maxcount, + const char *glossary); + +struct arg_str* arg_str0(const char* shortopts, + const char* longopts, + const char* datatype, + const char* glossary); +struct arg_str* arg_str1(const char* shortopts, + const char* longopts, + const char* datatype, + const char *glossary); +struct arg_str* arg_strn(const char* shortopts, + const char* longopts, + const char* datatype, + int mincount, + int maxcount, + const char *glossary); + +struct arg_rex* arg_rex0(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int flags, + const char* glossary); +struct arg_rex* arg_rex1(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int flags, + const char *glossary); +struct arg_rex* arg_rexn(const char* shortopts, + const char* longopts, + const char* pattern, + const char* datatype, + int mincount, + int maxcount, + int flags, + const char *glossary); + +struct arg_file* arg_file0(const char* shortopts, + const char* longopts, + const char* datatype, + const char* glossary); +struct arg_file* arg_file1(const char* shortopts, + const char* longopts, + const char* datatype, + const char *glossary); +struct arg_file* arg_filen(const char* shortopts, + const char* longopts, + const char* datatype, + int mincount, + int maxcount, + const char *glossary); + +struct arg_date* arg_date0(const char* shortopts, + const char* longopts, + const char* format, + const char* datatype, + const char* glossary); +struct arg_date* arg_date1(const char* shortopts, + const char* longopts, + const char* format, + const char* datatype, + const char *glossary); +struct arg_date* arg_daten(const char* shortopts, + const char* longopts, + const char* format, + const char* datatype, + int mincount, + int maxcount, + const char *glossary); + +struct arg_end* arg_end(int maxerrors); + + +/**** other functions *******************************************/ +int arg_nullcheck(void **argtable); +int arg_parse(int argc, char **argv, void **argtable); +void arg_print_option(FILE *fp, const char *shortopts, const char *longopts, const char *datatype, const char *suffix); +void arg_print_syntax(FILE *fp, void **argtable, const char *suffix); +void arg_print_syntaxv(FILE *fp, void **argtable, const char *suffix); +void arg_print_glossary(FILE *fp, void **argtable, const char *format); +void arg_print_glossary_gnu(FILE *fp, void **argtable); +void arg_print_errors(FILE* fp, struct arg_end* end, const char* progname); +void arg_freetable(void **argtable, size_t n); +void arg_print_formatted(FILE *fp, const unsigned lmargin, const unsigned rmargin, const char *text); + +/**** deprecated functions, for back-compatibility only ********/ +void arg_free(void **argtable); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/esp32c3/include/console/esp_console.h b/tools/sdk/esp32c3/include/console/esp_console.h new file mode 100644 index 00000000..29aab8b4 --- /dev/null +++ b/tools/sdk/esp32c3/include/console/esp_console.h @@ -0,0 +1,354 @@ +// Copyright 2016-2019 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. +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "sdkconfig.h" +#include "esp_err.h" + +// Forward declaration. Definition in linenoise/linenoise.h. +typedef struct linenoiseCompletions linenoiseCompletions; + +/** + * @brief Parameters for console initialization + */ +typedef struct { + size_t max_cmdline_length; //!< length of command line buffer, in bytes + size_t max_cmdline_args; //!< maximum number of command line arguments to parse + int hint_color; //!< ASCII color code of hint text + int hint_bold; //!< Set to 1 to print hint text in bold +} esp_console_config_t; + +/** + * @brief Default console configuration value + * + */ +#define ESP_CONSOLE_CONFIG_DEFAULT() \ + { \ + .max_cmdline_length = 256, \ + .max_cmdline_args = 32, \ + .hint_color = 39, \ + .hint_bold = 0 \ + } + +/** + * @brief Parameters for console REPL (Read Eval Print Loop) + * + */ +typedef struct { + uint32_t max_history_len; //!< maximum length for the history + const char *history_save_path; //!< file path used to save history commands, set to NULL won't save to file system + uint32_t task_stack_size; //!< repl task stack size + uint32_t task_priority; //!< repl task priority + const char *prompt; //!< prompt (NULL represents default: "esp> ") +} esp_console_repl_config_t; + +/** + * @brief Default console repl configuration value + * + */ +#define ESP_CONSOLE_REPL_CONFIG_DEFAULT() \ +{ \ + .max_history_len = 32, \ + .history_save_path = NULL, \ + .task_stack_size = 4096, \ + .task_priority = 2, \ + .prompt = NULL, \ +} + +/** + * @brief Parameters for console device: UART + * + */ +typedef struct { + int channel; //!< UART channel number (count from zero) + int baud_rate; //!< Comunication baud rate + int tx_gpio_num; //!< GPIO number for TX path, -1 means using default one + int rx_gpio_num; //!< GPIO number for RX path, -1 means using default one +} esp_console_dev_uart_config_t; + +#ifdef CONFIG_ESP_CONSOLE_UART_CUSTOM +#define ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT() \ +{ \ + .channel = CONFIG_ESP_CONSOLE_UART_NUM, \ + .baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE, \ + .tx_gpio_num = CONFIG_ESP_CONSOLE_UART_TX_GPIO, \ + .rx_gpio_num = CONFIG_ESP_CONSOLE_UART_RX_GPIO, \ +} +#else +#define ESP_CONSOLE_DEV_UART_CONFIG_DEFAULT() \ +{ \ + .channel = CONFIG_ESP_CONSOLE_UART_NUM, \ + .baud_rate = CONFIG_ESP_CONSOLE_UART_BAUDRATE, \ + .tx_gpio_num = -1, \ + .rx_gpio_num = -1, \ +} +#endif + +/** + * @brief Parameters for console device: USB CDC + * + * @note It's an empty structure for now, reserved for future + * + */ +typedef struct { + +} esp_console_dev_usb_cdc_config_t; + +#define ESP_CONSOLE_DEV_CDC_CONFIG_DEFAULT() \ +{ \ +} + +/** + * @brief initialize console module + * @param config console configuration + * @note Call this once before using other console module features + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if out of memory + * - ESP_ERR_INVALID_STATE if already initialized + * - ESP_ERR_INVALID_ARG if the configuration is invalid + */ +esp_err_t esp_console_init(const esp_console_config_t *config); + +/** + * @brief de-initialize console module + * @note Call this once when done using console module functions + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if not initialized yet + */ +esp_err_t esp_console_deinit(void); + +/** + * @brief Console command main function + * @param argc number of arguments + * @param argv array with argc entries, each pointing to a zero-terminated string argument + * @return console command return code, 0 indicates "success" + */ +typedef int (*esp_console_cmd_func_t)(int argc, char **argv); + +/** + * @brief Console command description + */ +typedef struct { + /** + * Command name. Must not be NULL, must not contain spaces. + * The pointer must be valid until the call to esp_console_deinit. + */ + const char *command; + /** + * Help text for the command, shown by help command. + * If set, the pointer must be valid until the call to esp_console_deinit. + * If not set, the command will not be listed in 'help' output. + */ + const char *help; + /** + * Hint text, usually lists possible arguments. + * If set to NULL, and 'argtable' field is non-NULL, hint will be generated + * automatically + */ + const char *hint; + /** + * Pointer to a function which implements the command. + */ + esp_console_cmd_func_t func; + /** + * Array or structure of pointers to arg_xxx structures, may be NULL. + * Used to generate hint text if 'hint' is set to NULL. + * Array/structure which this field points to must end with an arg_end. + * Only used for the duration of esp_console_cmd_register call. + */ + void *argtable; +} esp_console_cmd_t; + +/** + * @brief Register console command + * @param cmd pointer to the command description; can point to a temporary value + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if out of memory + * - ESP_ERR_INVALID_ARG if command description includes invalid arguments + */ +esp_err_t esp_console_cmd_register(const esp_console_cmd_t *cmd); + +/** + * @brief Run command line + * @param cmdline command line (command name followed by a number of arguments) + * @param[out] cmd_ret return code from the command (set if command was run) + * @return + * - ESP_OK, if command was run + * - ESP_ERR_INVALID_ARG, if the command line is empty, or only contained + * whitespace + * - ESP_ERR_NOT_FOUND, if command with given name wasn't registered + * - ESP_ERR_INVALID_STATE, if esp_console_init wasn't called + */ +esp_err_t esp_console_run(const char *cmdline, int *cmd_ret); + +/** + * @brief Split command line into arguments in place + * @verbatim + * - This function finds whitespace-separated arguments in the given input line. + * + * 'abc def 1 20 .3' -> [ 'abc', 'def', '1', '20', '.3' ] + * + * - Argument which include spaces may be surrounded with quotes. In this case + * spaces are preserved and quotes are stripped. + * + * 'abc "123 456" def' -> [ 'abc', '123 456', 'def' ] + * + * - Escape sequences may be used to produce backslash, double quote, and space: + * + * 'a\ b\\c\"' -> [ 'a b\c"' ] + * @endverbatim + * @note Pointers to at most argv_size - 1 arguments are returned in argv array. + * The pointer after the last one (i.e. argv[argc]) is set to NULL. + * + * @param line pointer to buffer to parse; it is modified in place + * @param argv array where the pointers to arguments are written + * @param argv_size number of elements in argv_array (max. number of arguments) + * @return number of arguments found (argc) + */ +size_t esp_console_split_argv(char *line, char **argv, size_t argv_size); + +/** + * @brief Callback which provides command completion for linenoise library + * + * When using linenoise for line editing, command completion support + * can be enabled like this: + * + * linenoiseSetCompletionCallback(&esp_console_get_completion); + * + * @param buf the string typed by the user + * @param lc linenoiseCompletions to be filled in + */ +void esp_console_get_completion(const char *buf, linenoiseCompletions *lc); + +/** + * @brief Callback which provides command hints for linenoise library + * + * When using linenoise for line editing, hints support can be enabled as + * follows: + * + * linenoiseSetHintsCallback((linenoiseHintsCallback*) &esp_console_get_hint); + * + * The extra cast is needed because linenoiseHintsCallback is defined as + * returning a char* instead of const char*. + * + * @param buf line typed by the user + * @param[out] color ANSI color code to be used when displaying the hint + * @param[out] bold set to 1 if hint has to be displayed in bold + * @return string containing the hint text. This string is persistent and should + * not be freed (i.e. linenoiseSetFreeHintsCallback should not be used). + */ +const char *esp_console_get_hint(const char *buf, int *color, int *bold); + +/** + * @brief Register a 'help' command + * + * Default 'help' command prints the list of registered commands along with + * hints and help strings. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE, if esp_console_init wasn't called + */ +esp_err_t esp_console_register_help_command(void); + +/****************************************************************************** + * Console REPL + ******************************************************************************/ + +/** + * @brief Type defined for console REPL + * + */ +typedef struct esp_console_repl_s esp_console_repl_t; + +/** + * @brief Console REPL base structure + * + */ +struct esp_console_repl_s { + /** + * @brief Delete console REPL environment + * @param[in] repl REPL handle returned from esp_console_new_repl_xxx + * @return + * - ESP_OK on success + * - ESP_FAIL on errors + */ + esp_err_t (*del)(esp_console_repl_t *repl); +}; + +/** + * @brief Establish a console REPL environment over UART driver + * + * @param[in] dev_config UART device configuration + * @param[in] repl_config REPL configuration + * @param[out] ret_repl return REPL handle after initialization succeed, return NULL otherwise + * + * @note This is a all-in-one function to establish the environment needed for REPL, includes: + * - Install the UART driver on the console UART (8n1, 115200, REF_TICK clock source) + * - Configures the stdin/stdout to go through the UART driver + * - Initializes linenoise + * - Spawn new thread to run REPL in the background + * + * @attention This function is meant to be used in the examples to make the code more compact. + * Applications which use console functionality should be based on + * the underlying linenoise and esp_console functions. + * + * @return + * - ESP_OK on success + * - ESP_FAIL Parameter error + */ +esp_err_t esp_console_new_repl_uart(const esp_console_dev_uart_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl); + +/** + * @brief Establish a console REPL environment over USB CDC + * + * @param[in] dev_config USB CDC configuration + * @param[in] repl_config REPL configuration + * @param[out] ret_repl return REPL handle after initialization succeed, return NULL otherwise + * + * @note This is a all-in-one function to establish the environment needed for REPL, includes: + * - Initializes linenoise + * - Spawn new thread to run REPL in the background + * + * @attention This function is meant to be used in the examples to make the code more compact. + * Applications which use console functionality should be based on + * the underlying linenoise and esp_console functions. + * + * @return + * - ESP_OK on success + * - ESP_FAIL Parameter error + */ +esp_err_t esp_console_new_repl_usb_cdc(const esp_console_dev_usb_cdc_config_t *dev_config, const esp_console_repl_config_t *repl_config, esp_console_repl_t **ret_repl); + +/** + * @brief Start REPL environment + * @param[in] repl REPL handle returned from esp_console_new_repl_xxx + * @note Once the REPL got started, it won't be stopped until user call repl->del(repl) to destory the REPL environment. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE, if repl has started already + */ +esp_err_t esp_console_start_repl(esp_console_repl_t *repl); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/console/linenoise/linenoise.h b/tools/sdk/esp32c3/include/console/linenoise/linenoise.h new file mode 100644 index 00000000..58756a52 --- /dev/null +++ b/tools/sdk/esp32c3/include/console/linenoise/linenoise.h @@ -0,0 +1,79 @@ +/* linenoise.h -- VERSION 1.0 + * + * Guerrilla line editing library against the idea that a line editing lib + * needs to be 20,000 lines of C code. + * + * See linenoise.c for more information. + * + * ------------------------------------------------------------------------ + * + * Copyright (c) 2010-2014, Salvatore Sanfilippo + * Copyright (c) 2010-2013, Pieter Noordhuis + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef __LINENOISE_H +#define __LINENOISE_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +typedef struct linenoiseCompletions { + size_t len; + char **cvec; +} linenoiseCompletions; + +typedef void(linenoiseCompletionCallback)(const char *, linenoiseCompletions *); +typedef char*(linenoiseHintsCallback)(const char *, int *color, int *bold); +typedef void(linenoiseFreeHintsCallback)(void *); +void linenoiseSetCompletionCallback(linenoiseCompletionCallback *); +void linenoiseSetHintsCallback(linenoiseHintsCallback *); +void linenoiseSetFreeHintsCallback(linenoiseFreeHintsCallback *); +void linenoiseAddCompletion(linenoiseCompletions *, const char *); + +int linenoiseProbe(void); +char *linenoise(const char *prompt); +void linenoiseFree(void *ptr); +int linenoiseHistoryAdd(const char *line); +int linenoiseHistorySetMaxLen(int len); +int linenoiseHistorySave(const char *filename); +int linenoiseHistoryLoad(const char *filename); +void linenoiseHistoryFree(void); +void linenoiseClearScreen(void); +void linenoiseSetMultiLine(int ml); +void linenoiseSetDumbMode(int set); +void linenoisePrintKeyCodes(void); +void linenoiseAllowEmpty(bool); + +#ifdef __cplusplus +} +#endif + +#endif /* __LINENOISE_H */ diff --git a/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/adc.h b/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/adc.h new file mode 100644 index 00000000..2678a9e6 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/adc.h @@ -0,0 +1,100 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include "driver/adc_common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*--------------------------------------------------------------- + Common setting +---------------------------------------------------------------*/ +/*************************************/ +/* Digital controller filter setting */ +/*************************************/ +/** + * @brief Reset adc digital controller filter. + * + * @param idx Filter index. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_filter_reset(adc_digi_filter_idx_t idx); + +/** + * @brief Set adc digital controller filter configuration. + * + * @param idx Filter index. + * @param config See ``adc_digi_filter_t``. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_filter_set_config(adc_digi_filter_idx_t idx, adc_digi_filter_t *config); + +/** + * @brief Get adc digital controller filter configuration. + * + * @param idx Filter index. + * @param config See ``adc_digi_filter_t``. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_filter_get_config(adc_digi_filter_idx_t idx, adc_digi_filter_t *config); + +/** + * @brief Enable/disable adc digital controller filter. + * Filtering the ADC data to obtain smooth data at higher sampling rates. + * + * @param idx Filter index. + * @param enable Enable/Disable filter. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_filter_enable(adc_digi_filter_idx_t idx, bool enable); + +/**************************************/ +/* Digital controller monitor setting */ +/**************************************/ + +/** + * @brief Config monitor of adc digital controller. + * + * @param idx Monitor index. + * @param config See ``adc_digi_monitor_t``. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_monitor_set_config(adc_digi_monitor_idx_t idx, adc_digi_monitor_t *config); + +/** + * @brief Enable/disable monitor of adc digital controller. + * + * @param idx Monitor index. + * @param enable True or false enable monitor. + * + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_monitor_enable(adc_digi_monitor_idx_t idx, bool enable); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/temp_sensor.h b/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/temp_sensor.h new file mode 100644 index 00000000..2eccefcf --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/esp32c3/include/driver/temp_sensor.h @@ -0,0 +1,99 @@ +// Copyright 2010-2018 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. + +#pragma once + +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + TSENS_DAC_L0 = 0, /*!< offset = -2, measure range: 50℃ ~ 125℃, error < 3℃. */ + TSENS_DAC_L1, /*!< offset = -1, measure range: 20℃ ~ 100℃, error < 2℃. */ + TSENS_DAC_L2, /*!< offset = 0, measure range:-10℃ ~ 80℃, error < 1℃. */ + TSENS_DAC_L3, /*!< offset = 1, measure range:-30℃ ~ 50℃, error < 2℃. */ + TSENS_DAC_L4, /*!< offset = 2, measure range:-40℃ ~ 20℃, error < 3℃. */ + TSENS_DAC_MAX, + TSENS_DAC_DEFAULT = TSENS_DAC_L2, +} temp_sensor_dac_offset_t; + +/** + * @brief Configuration for temperature sensor reading + */ +typedef struct { + temp_sensor_dac_offset_t dac_offset; /*!< The temperature measurement range is configured with a built-in temperature offset DAC. */ + uint8_t clk_div; /*!< Default: 6 */ +} temp_sensor_config_t; + +#define TSENS_CONFIG_DEFAULT() {.dac_offset = TSENS_DAC_L2, \ + .clk_div = 6} + +/** + * @brief Set parameter of temperature sensor. + * @param tsens + * @return + * - ESP_OK Success + */ +esp_err_t temp_sensor_set_config(temp_sensor_config_t tsens); + +/** + * @brief Get parameter of temperature sensor. + * @param tsens + * @return + * - ESP_OK Success + */ +esp_err_t temp_sensor_get_config(temp_sensor_config_t *tsens); + +/** + * @brief Start temperature sensor measure. + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG + */ +esp_err_t temp_sensor_start(void); + +/** + * @brief Stop temperature sensor measure. + * @return + * - ESP_OK Success + */ +esp_err_t temp_sensor_stop(void); + +/** + * @brief Read temperature sensor raw data. + * @param tsens_out Pointer to raw data, Range: 0 ~ 255 + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG `tsens_out` is NULL + * - ESP_ERR_INVALID_STATE temperature sensor dont start + */ +esp_err_t temp_sensor_read_raw(uint32_t *tsens_out); + +/** + * @brief Read temperature sensor data that is converted to degrees Celsius. + * @note Should not be called from interrupt. + * @param celsius The measure output value. + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG ARG is NULL. + * - ESP_ERR_INVALID_STATE The ambient temperature is out of range. + */ +esp_err_t temp_sensor_read_celsius(float *celsius); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/adc2_wifi_private.h b/tools/sdk/esp32c3/include/driver/include/driver/adc2_wifi_private.h new file mode 100644 index 00000000..c4f62265 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/adc2_wifi_private.h @@ -0,0 +1,64 @@ +// Copyright 2015-2016 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_err.h" + +/** + * @brief For WIFI module to claim the usage of ADC2. + * + * Other tasks will be forbidden to use ADC2 between ``adc2_wifi_acquire`` and ``adc2_wifi_release``. + * The WIFI module may have to wait for a short time for the current conversion (if exist) to finish. + * + * @return + * - ESP_OK success + * - ESP_ERR_TIMEOUT reserved for future use. Currently the function will wait until success. + */ +esp_err_t adc2_wifi_acquire(void); + + +/** + * @brief For WIFI module to let other tasks use the ADC2 when WIFI is not work. + * + * Other tasks will be forbidden to use ADC2 between ``adc2_wifi_acquire`` and ``adc2_wifi_release``. + * Call this function to release the occupation of ADC2 by WIFI. + * + * @return always return ESP_OK. + */ +esp_err_t adc2_wifi_release(void); + +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32C3 +/** + * @brief This API help ADC2 calibration constructor be linked. + * + * @note This is a private function, Don't call `adc2_cal_include` in user code. + */ +void adc2_cal_include(void); +#else +/** + * @brief There's no calibration involved on this chip. + * + * @note This is a private function, Don't call `adc2_cal_include` in user code. + */ +#define adc2_cal_include() +#endif //CONFIG_IDF_TARGET_* + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/adc_common.h b/tools/sdk/esp32c3/include/driver/include/driver/adc_common.h new file mode 100644 index 00000000..e38da915 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/adc_common.h @@ -0,0 +1,552 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include +#include +#include "esp_err.h" +#include "sdkconfig.h" +#include "driver/gpio.h" +#include "hal/adc_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if CONFIG_IDF_TARGET_ESP32 +/**** `adc1_channel_t` will be deprecated functions, combine into `adc_channel_t` ********/ +typedef enum { + ADC1_CHANNEL_0 = 0, /*!< ADC1 channel 0 is GPIO36 */ + ADC1_CHANNEL_1, /*!< ADC1 channel 1 is GPIO37 */ + ADC1_CHANNEL_2, /*!< ADC1 channel 2 is GPIO38 */ + ADC1_CHANNEL_3, /*!< ADC1 channel 3 is GPIO39 */ + ADC1_CHANNEL_4, /*!< ADC1 channel 4 is GPIO32 */ + ADC1_CHANNEL_5, /*!< ADC1 channel 5 is GPIO33 */ + ADC1_CHANNEL_6, /*!< ADC1 channel 6 is GPIO34 */ + ADC1_CHANNEL_7, /*!< ADC1 channel 7 is GPIO35 */ + ADC1_CHANNEL_MAX, +} adc1_channel_t; +#elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 // TODO ESP32-S3 channels are wrong IDF-1776 +/**** `adc1_channel_t` will be deprecated functions, combine into `adc_channel_t` ********/ +typedef enum { + ADC1_CHANNEL_0 = 0, /*!< ADC1 channel 0 is GPIO1 */ + ADC1_CHANNEL_1, /*!< ADC1 channel 1 is GPIO2 */ + ADC1_CHANNEL_2, /*!< ADC1 channel 2 is GPIO3 */ + ADC1_CHANNEL_3, /*!< ADC1 channel 3 is GPIO4 */ + ADC1_CHANNEL_4, /*!< ADC1 channel 4 is GPIO5 */ + ADC1_CHANNEL_5, /*!< ADC1 channel 5 is GPIO6 */ + ADC1_CHANNEL_6, /*!< ADC1 channel 6 is GPIO7 */ + ADC1_CHANNEL_7, /*!< ADC1 channel 7 is GPIO8 */ + ADC1_CHANNEL_8, /*!< ADC1 channel 6 is GPIO9 */ + ADC1_CHANNEL_9, /*!< ADC1 channel 7 is GPIO10 */ + ADC1_CHANNEL_MAX, +} adc1_channel_t; +#elif CONFIG_IDF_TARGET_ESP32C3 +/**** `adc1_channel_t` will be deprecated functions, combine into `adc_channel_t` ********/ +typedef enum { + ADC1_CHANNEL_0 = 0, /*!< ADC1 channel 0 is GPIO0 */ + ADC1_CHANNEL_1, /*!< ADC1 channel 1 is GPIO1 */ + ADC1_CHANNEL_2, /*!< ADC1 channel 2 is GPIO2 */ + ADC1_CHANNEL_3, /*!< ADC1 channel 3 is GPIO3 */ + ADC1_CHANNEL_4, /*!< ADC1 channel 4 is GPIO4 */ + ADC1_CHANNEL_MAX, +} adc1_channel_t; +#endif // CONFIG_IDF_TARGET_* + +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 // TODO ESP32-S3 channels are wrong IDF-1776 +/**** `adc2_channel_t` will be deprecated functions, combine into `adc_channel_t` ********/ +typedef enum { + ADC2_CHANNEL_0 = 0, /*!< ADC2 channel 0 is GPIO4 (ESP32), GPIO11 (ESP32-S2) */ + ADC2_CHANNEL_1, /*!< ADC2 channel 1 is GPIO0 (ESP32), GPIO12 (ESP32-S2) */ + ADC2_CHANNEL_2, /*!< ADC2 channel 2 is GPIO2 (ESP32), GPIO13 (ESP32-S2) */ + ADC2_CHANNEL_3, /*!< ADC2 channel 3 is GPIO15 (ESP32), GPIO14 (ESP32-S2) */ + ADC2_CHANNEL_4, /*!< ADC2 channel 4 is GPIO13 (ESP32), GPIO15 (ESP32-S2) */ + ADC2_CHANNEL_5, /*!< ADC2 channel 5 is GPIO12 (ESP32), GPIO16 (ESP32-S2) */ + ADC2_CHANNEL_6, /*!< ADC2 channel 6 is GPIO14 (ESP32), GPIO17 (ESP32-S2) */ + ADC2_CHANNEL_7, /*!< ADC2 channel 7 is GPIO27 (ESP32), GPIO18 (ESP32-S2) */ + ADC2_CHANNEL_8, /*!< ADC2 channel 8 is GPIO25 (ESP32), GPIO19 (ESP32-S2) */ + ADC2_CHANNEL_9, /*!< ADC2 channel 9 is GPIO26 (ESP32), GPIO20 (ESP32-S2) */ + ADC2_CHANNEL_MAX, +} adc2_channel_t; +#elif CONFIG_IDF_TARGET_ESP32C3 +/**** `adc2_channel_t` will be deprecated functions, combine into `adc_channel_t` ********/ +typedef enum { + ADC2_CHANNEL_0 = 0, /*!< ADC2 channel 0 is GPIO5 */ + ADC2_CHANNEL_MAX, +} adc2_channel_t; +#endif + + +/** + * @brief ADC rtc controller attenuation option. + * + * @note This definitions are only for being back-compatible + */ +#define ADC_ATTEN_0db ADC_ATTEN_DB_0 +#define ADC_ATTEN_2_5db ADC_ATTEN_DB_2_5 +#define ADC_ATTEN_6db ADC_ATTEN_DB_6 +#define ADC_ATTEN_11db ADC_ATTEN_DB_11 + +/** + * The default (max) bit width of the ADC of current version. You can also get the maximum bitwidth + * by `SOC_ADC_MAX_BITWIDTH` defined in soc_caps.h. + */ +#define ADC_WIDTH_BIT_DEFAULT (ADC_WIDTH_MAX-1) + +//this definitions are only for being back-compatible +#define ADC_WIDTH_9Bit ADC_WIDTH_BIT_9 +#define ADC_WIDTH_10Bit ADC_WIDTH_BIT_10 +#define ADC_WIDTH_11Bit ADC_WIDTH_BIT_11 +#define ADC_WIDTH_12Bit ADC_WIDTH_BIT_12 + +#if CONFIG_IDF_TARGET_ESP32C3 +/** + * @brief Digital ADC DMA read max timeout value, it may make the ``adc_digi_read_bytes`` block forever if the OS supports + */ +#define ADC_MAX_DELAY UINT32_MAX +#endif + +/** + * @brief ADC digital controller encode option. + * + * @deprecated The ESP32-S2 doesn't use I2S DMA. Call ``adc_digi_output_format_t`` instead. + */ +typedef enum { + ADC_ENCODE_12BIT, /*!< ADC to DMA data format, , [15:12]-channel [11:0]-12 bits ADC data */ + ADC_ENCODE_11BIT, /*!< ADC to DMA data format, [15]-unit, [14:11]-channel [10:0]-11 bits ADC data */ + ADC_ENCODE_MAX, +} adc_i2s_encode_t; + +#if CONFIG_IDF_TARGET_ESP32C3 +//This feature is currently supported on ESP32C3, will be supported on other chips soon +/** + * @brief Digital ADC DMA configuration + */ +typedef struct adc_digi_init_config_s { + uint32_t max_store_buf_size; ///< Max length of the converted data that driver can store before they are processed. When this length is reached, driver will dump out all the old data and start to store them again. + uint32_t conv_num_each_intr; ///< Bytes of data that can be converted in 1 interrupt. + uint32_t adc1_chan_mask; ///< Channel list of ADC1 to be initialized. + uint32_t adc2_chan_mask; ///< Channel list of ADC2 to be initialized. +} adc_digi_init_config_t; +#endif + +/*--------------------------------------------------------------- + Common setting +---------------------------------------------------------------*/ + +/** + * @brief Enable ADC power + * @deprecated Use adc_power_acquire and adc_power_release instead. + */ +void adc_power_on(void) __attribute__((deprecated)); + +/** + * @brief Power off SAR ADC + * @deprecated Use adc_power_acquire and adc_power_release instead. + * This function will force power down for ADC. + * This function is deprecated because forcing power ADC power off may + * disrupt operation of other components which may be using the ADC. + */ +void adc_power_off(void) __attribute__((deprecated)); + +/** + * @brief Increment the usage counter for ADC module. + * ADC will stay powered on while the counter is greater than 0. + * Call adc_power_release when done using the ADC. + */ +void adc_power_acquire(void); + +/** + * @brief Decrement the usage counter for ADC module. + * ADC will stay powered on while the counter is greater than 0. + * Call this function when done using the ADC. + */ +void adc_power_release(void); + +#if !CONFIG_IDF_TARGET_ESP32C3 +/** + * @brief Initialize ADC pad + * @param adc_unit ADC unit index + * @param channel ADC channel index + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc_gpio_init(adc_unit_t adc_unit, adc_channel_t channel); +#endif //#if !CONFIG_IDF_TARGET_ESP32C3 + +/*--------------------------------------------------------------- + ADC Single Read Setting +---------------------------------------------------------------*/ +/** + * @brief Get the GPIO number of a specific ADC1 channel. + * + * @param channel Channel to get the GPIO number + * @param gpio_num output buffer to hold the GPIO number + * + * @return + * - ESP_OK if success + * - ESP_ERR_INVALID_ARG if channel not valid + */ +esp_err_t adc1_pad_get_io_num(adc1_channel_t channel, gpio_num_t *gpio_num); + +/** + * @brief Set the attenuation of a particular channel on ADC1, and configure its associated GPIO pin mux. + * + * The default ADC voltage is for attenuation 0 dB and listed in the table below. + * By setting higher attenuation it is possible to read higher voltages. + * + * Due to ADC characteristics, most accurate results are obtained within the "suggested range" + * shown in the following table. + * + * +----------+-------------+-----------------+ + * | | attenuation | suggested range | + * | SoC | (dB) | (mV) | + * +==========+=============+=================+ + * | | 0 | 100 ~ 950 | + * | +-------------+-----------------+ + * | | 2.5 | 100 ~ 1250 | + * | ESP32 +-------------+-----------------+ + * | | 6 | 150 ~ 1750 | + * | +-------------+-----------------+ + * | | 11 | 150 ~ 2450 | + * +----------+-------------+-----------------+ + * | | 0 | 0 ~ 750 | + * | +-------------+-----------------+ + * | | 2.5 | 0 ~ 1050 | + * | ESP32-S2 +-------------+-----------------+ + * | | 6 | 0 ~ 1300 | + * | +-------------+-----------------+ + * | | 11 | 0 ~ 2500 | + * +----------+-------------+-----------------+ + * + * For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended ranges. + * + * @note For any given channel, this function must be called before the first time ``adc1_get_raw()`` is called for that channel. + * + * @note This function can be called multiple times to configure multiple + * ADC channels simultaneously. You may call ``adc1_get_raw()`` only after configuring a channel. + * + * @param channel ADC1 channel to configure + * @param atten Attenuation level + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc1_config_channel_atten(adc1_channel_t channel, adc_atten_t atten); + +/** + * @brief Configure ADC1 capture width, meanwhile enable output invert for ADC1. + * The configuration is for all channels of ADC1 + * @param width_bit Bit capture width for ADC1 + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc1_config_width(adc_bits_width_t width_bit); + +/** + * @brief Take an ADC1 reading from a single channel. + * @note ESP32: + * When the power switch of SARADC1, SARADC2, HALL sensor and AMP sensor is turned on, + * the input of GPIO36 and GPIO39 will be pulled down for about 80ns. + * When enabling power for any of these peripherals, ignore input from GPIO36 and GPIO39. + * Please refer to section 3.11 of 'ECO_and_Workarounds_for_Bugs_in_ESP32' for the description of this issue. + * As a workaround, call adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), + * but will remove the glitches on GPIO36 and GPIO39. + * + * @note Call ``adc1_config_width()`` before the first time this + * function is called. + * + * @note For any given channel, adc1_config_channel_atten(channel) + * must be called before the first time this function is called. Configuring + * a new channel does not prevent a previously configured channel from being read. + * + * @param channel ADC1 channel to read + * + * @return + * - -1: Parameter error + * - Other: ADC1 channel reading. + */ +int adc1_get_raw(adc1_channel_t channel); + +#if !CONFIG_IDF_TARGET_ESP32C3 +/** + * @brief Set ADC data invert + * @param adc_unit ADC unit index + * @param inv_en whether enable data invert + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc_set_data_inv(adc_unit_t adc_unit, bool inv_en); + +/** + * @brief Set ADC source clock + * @param clk_div ADC clock divider, ADC clock is divided from APB clock + * @return + * - ESP_OK success + */ +esp_err_t adc_set_clk_div(uint8_t clk_div); + +/** + * @brief Configure ADC capture width. + * + * @param adc_unit ADC unit index + * @param width_bit Bit capture width for ADC unit. + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc_set_data_width(adc_unit_t adc_unit, adc_bits_width_t width_bit); + +/** + * @brief Configure ADC1 to be usable by the ULP + * + * This function reconfigures ADC1 to be controlled by the ULP. + * Effect of this function can be reverted using ``adc1_get_raw()`` function. + * + * Note that adc1_config_channel_atten, ``adc1_config_width()`` functions need + * to be called to configure ADC1 channels, before ADC1 is used by the ULP. + */ +void adc1_ulp_enable(void); +#endif //#if !CONFIG_IDF_TARGET_ESP32C3 + +/** + * @brief Get the GPIO number of a specific ADC2 channel. + * + * @param channel Channel to get the GPIO number + * + * @param gpio_num output buffer to hold the GPIO number + * + * @return + * - ESP_OK if success + * - ESP_ERR_INVALID_ARG if channel not valid + */ +esp_err_t adc2_pad_get_io_num(adc2_channel_t channel, gpio_num_t *gpio_num); + +/** + * @brief Configure the ADC2 channel, including setting attenuation. + * + * The default ADC voltage is for attenuation 0 dB and listed in the table below. + * By setting higher attenuation it is possible to read higher voltages. + * + * Due to ADC characteristics, most accurate results are obtained within the "suggested range" + * shown in the following table. + * + * +----------+-------------+-----------------+ + * | | attenuation | suggested range | + * | SoC | (dB) | (mV) | + * +==========+=============+=================+ + * | | 0 | 100 ~ 950 | + * | +-------------+-----------------+ + * | | 2.5 | 100 ~ 1250 | + * | ESP32 +-------------+-----------------+ + * | | 6 | 150 ~ 1750 | + * | +-------------+-----------------+ + * | | 11 | 150 ~ 2450 | + * +----------+-------------+-----------------+ + * | | 0 | 0 ~ 750 | + * | +-------------+-----------------+ + * | | 2.5 | 0 ~ 1050 | + * | ESP32-S2 +-------------+-----------------+ + * | | 6 | 0 ~ 1300 | + * | +-------------+-----------------+ + * | | 11 | 0 ~ 2500 | + * +----------+-------------+-----------------+ + * + * For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended ranges. + * + * @note This function also configures the input GPIO pin mux to + * connect it to the ADC2 channel. It must be called before calling + * ``adc2_get_raw()`` for this channel. + * + * @note For any given channel, this function must be called before the first time ``adc2_get_raw()`` is called for that channel. + * + * @param channel ADC2 channel to configure + * @param atten Attenuation level + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t adc2_config_channel_atten(adc2_channel_t channel, adc_atten_t atten); + +/** + * @brief Take an ADC2 reading on a single channel + * + * @note ESP32: + * When the power switch of SARADC1, SARADC2, HALL sensor and AMP sensor is turned on, + * the input of GPIO36 and GPIO39 will be pulled down for about 80ns. + * When enabling power for any of these peripherals, ignore input from GPIO36 and GPIO39. + * Please refer to section 3.11 of 'ECO_and_Workarounds_for_Bugs_in_ESP32' for the description of this issue. + * As a workaround, call adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), + * but will remove the glitches on GPIO36 and GPIO39. + * + * + * @note ESP32: + * For a given channel, ``adc2_config_channel_atten()`` + * must be called before the first time this function is called. If Wi-Fi is started via ``esp_wifi_start()``, this + * function will always fail with ``ESP_ERR_TIMEOUT``. + * + * @note ESP32-S2: + * ADC2 support hardware arbiter. The arbiter is to improve the use efficiency of ADC2. After the control right is robbed by the high priority, + * the low priority controller will read the invalid ADC2 data. Default priority: Wi-Fi > RTC > Digital; + * + * @param channel ADC2 channel to read + * @param width_bit Bit capture width for ADC2 + * @param raw_out the variable to hold the output data. + * + * @return + * - ESP_OK if success + * - ESP_ERR_TIMEOUT ADC2 is being used by other controller and the request timed out. + * - ESP_ERR_INVALID_STATE The controller status is invalid. Please try again. + */ +esp_err_t adc2_get_raw(adc2_channel_t channel, adc_bits_width_t width_bit, int *raw_out); + +/** + * @brief Output ADC1 or ADC2's reference voltage to ``adc2_channe_t``'s IO. + * + * This function routes the internal reference voltage of ADCn to one of + * ADC2's channels. This reference voltage can then be manually measured + * for calibration purposes. + * + * @note ESP32 only supports output of ADC2's internal reference voltage. + * @param[in] adc_unit ADC unit index + * @param[in] gpio GPIO number (Only ADC2's channels IO are supported) + * + * @return + * - ESP_OK: v_ref successfully routed to selected GPIO + * - ESP_ERR_INVALID_ARG: Unsupported GPIO + */ +esp_err_t adc_vref_to_gpio(adc_unit_t adc_unit, gpio_num_t gpio); + +/** + * @brief Output ADC2 reference voltage to ``adc2_channe_t``'s IO. + * + * This function routes the internal reference voltage of ADCn to one of + * ADC2's channels. This reference voltage can then be manually measured + * for calibration purposes. + * + * @deprecated Use ``adc_vref_to_gpio`` instead. + * + * @param[in] gpio GPIO number (ADC2's channels are supported) + * + * @return + * - ESP_OK: v_ref successfully routed to selected GPIO + * - ESP_ERR_INVALID_ARG: Unsupported GPIO + */ +esp_err_t adc2_vref_to_gpio(gpio_num_t gpio) __attribute__((deprecated)); + +/*--------------------------------------------------------------- + Digital controller setting +---------------------------------------------------------------*/ +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 +//These APIs are only supported on ESP32 and ESP32-S2. On ESP32-C3 and later chips, please use ``adc_digi_initialize`` and ``adc_digi_deinitialize`` +/** + * @brief ADC digital controller initialization. + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_init(void); + +/** + * @brief ADC digital controller deinitialization. + * @return + * - ESP_OK Success + */ +esp_err_t adc_digi_deinit(void); +#endif + +/** + * @brief Setting the digital controller. + * + * @param config Pointer to digital controller paramter. Refer to ``adc_digi_config_t``. + * + * @return + * - ESP_ERR_INVALID_STATE Driver state is invalid. + * - ESP_ERR_INVALID_ARG If the combination of arguments is invalid. + * - ESP_OK On success + */ +esp_err_t adc_digi_controller_config(const adc_digi_config_t *config); + +#if CONFIG_IDF_TARGET_ESP32C3 +//This feature is currently supported on ESP32C3, will be supported on other chips soon +/*--------------------------------------------------------------- + DMA setting +---------------------------------------------------------------*/ +/** + * @brief Initialize the Digital ADC. + * + * @param init_config Pointer to Digital ADC initilization config. Refer to ``adc_digi_init_config_t``. + * + * @return + * - ESP_ERR_INVALID_ARG If the combination of arguments is invalid. + * - ESP_ERR_NOT_FOUND No free interrupt found with the specified flags + * - ESP_ERR_NO_MEM If out of memory + * - ESP_OK On success + */ +esp_err_t adc_digi_initialize(const adc_digi_init_config_t *init_config); + +/** + * @brief Start the Digital ADC and DMA peripherals. After this, the hardware starts working. + * + * @return + * - ESP_ERR_INVALID_STATE Driver state is invalid. + * - ESP_OK On success + */ +esp_err_t adc_digi_start(void); + +/** + * @brief Stop the Digital ADC and DMA peripherals. After this, the hardware stops working. + * + * @return + * - ESP_ERR_INVALID_STATE Driver state is invalid. + * - ESP_OK On success + */ +esp_err_t adc_digi_stop(void); + +/** + * @brief Read bytes from Digital ADC through DMA. + * + * @param[out] buf Buffer to read from ADC. + * @param[in] length_max Expected length of data read from the ADC. + * @param[out] out_length Real length of data read from the ADC via this API. + * @param[in] timeout_ms Time to wait for data via this API, in millisecond. + * + * @return + * - ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate. + * - ESP_ERR_TIMEOUT Operation timed out + * - ESP_OK On success + */ +esp_err_t adc_digi_read_bytes(uint8_t *buf, uint32_t length_max, uint32_t *out_length, uint32_t timeout_ms); + +/** + * @brief Deinitialize the Digital ADC. + * + * @return + * - ESP_ERR_INVALID_STATE Driver state is invalid. + * - ESP_OK On success + */ +esp_err_t adc_digi_deinitialize(void); + +#endif //#if CONFIG_IDF_TARGET_ESP32C3 + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/can.h b/tools/sdk/esp32c3/include/driver/include/driver/can.h new file mode 100644 index 00000000..e28a9c44 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/can.h @@ -0,0 +1,74 @@ +// Copyright 2015-2018 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#warning driver/can.h is deprecated, please use driver/twai.h instead + +#include "hal/can_types.h" +#include "driver/twai.h" + +/* ---------------------------- Compatibility ------------------------------- */ + +#define CAN_GENERAL_CONFIG_DEFAULT(tx_io_num, rx_io_num, op_mode) TWAI_GENERAL_CONFIG_DEFAULT(tx_io_num, rx_io_num, op_mode) + +#define CAN_ALERT_TX_IDLE TWAI_ALERT_TX_IDLE +#define CAN_ALERT_TX_SUCCESS TWAI_ALERT_TX_SUCCESS +#define CAN_ALERT_BELOW_ERR_WARN TWAI_ALERT_BELOW_ERR_WARN +#define CAN_ALERT_ERR_ACTIVE TWAI_ALERT_ERR_ACTIVE +#define CAN_ALERT_RECOVERY_IN_PROGRESS TWAI_ALERT_RECOVERY_IN_PROGRESS +#define CAN_ALERT_BUS_RECOVERED TWAI_ALERT_BUS_RECOVERED +#define CAN_ALERT_ARB_LOST TWAI_ALERT_ARB_LOST +#define CAN_ALERT_ABOVE_ERR_WARN TWAI_ALERT_ABOVE_ERR_WARN +#define CAN_ALERT_BUS_ERROR TWAI_ALERT_BUS_ERROR +#define CAN_ALERT_TX_FAILED TWAI_ALERT_TX_FAILED +#define CAN_ALERT_RX_QUEUE_FULL TWAI_ALERT_RX_QUEUE_FULL +#define CAN_ALERT_ERR_PASS TWAI_ALERT_ERR_PASS +#define CAN_ALERT_BUS_OFF TWAI_ALERT_BUS_OFF +#define CAN_ALERT_ALL TWAI_ALERT_ALL +#define CAN_ALERT_NONE TWAI_ALERT_NONE +#define CAN_ALERT_AND_LOG TWAI_ALERT_AND_LOG + +#define CAN_IO_UNUSED TWAI_IO_UNUSED + +#define CAN_STATE_STOPPED TWAI_STATE_STOPPED +#define CAN_STATE_RUNNING TWAI_STATE_RUNNING +#define CAN_STATE_BUS_OFF TWAI_STATE_BUS_OFF +#define CAN_STATE_RECOVERING TWAI_STATE_RECOVERING + +typedef twai_state_t can_state_t; +typedef twai_general_config_t can_general_config_t; +typedef twai_status_info_t can_status_info_t; + + +#define can_driver_install(g_config, t_config, f_config) twai_driver_install(g_config, t_config, f_config) +#define can_driver_uninstall() twai_driver_uninstall() +#define can_start() twai_start() +#define can_stop() twai_stop() +#define can_transmit(message, ticks_to_wait) twai_transmit(message, ticks_to_wait) +#define can_receive(message, ticks_to_wait) twai_receive(message, ticks_to_wait) +#define can_read_alerts(alerts, ticks_to_wait) twai_read_alerts(alerts, ticks_to_wait) +#define can_reconfigure_alerts(alerts_enabled, current_alerts) twai_reconfigure_alerts(alerts_enabled, current_alerts) +#define can_initiate_recovery() twai_initiate_recovery() +#define can_get_status_info(status_info) twai_get_status_info(status_info) +#define can_clear_transmit_queue() twai_clear_transmit_queue() +#define can_clear_receive_queue() twai_clear_receive_queue() + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/dac_common.h b/tools/sdk/esp32c3/include/driver/include/driver/dac_common.h new file mode 100644 index 00000000..b1aefc95 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/dac_common.h @@ -0,0 +1,98 @@ +// Copyright 2015-2016 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "esp_err.h" +#include "driver/gpio.h" +#include "hal/dac_types.h" + +/** + * @brief Get the GPIO number of a specific DAC channel. + * + * @param channel Channel to get the gpio number + * @param gpio_num output buffer to hold the gpio number + * @return + * - ESP_OK if success + */ +esp_err_t dac_pad_get_io_num(dac_channel_t channel, gpio_num_t *gpio_num); + +/** + * @brief Set DAC output voltage. + * DAC output is 8-bit. Maximum (255) corresponds to VDD3P3_RTC. + * + * @note Need to configure DAC pad before calling this function. + * DAC channel 1 is attached to GPIO25, DAC channel 2 is attached to GPIO26 + * @param channel DAC channel + * @param dac_value DAC output value + * + * @return + * - ESP_OK success + */ +esp_err_t dac_output_voltage(dac_channel_t channel, uint8_t dac_value); + +/** + * @brief DAC pad output enable + * + * @param channel DAC channel + * @note DAC channel 1 is attached to GPIO25, DAC channel 2 is attached to GPIO26 + * I2S left channel will be mapped to DAC channel 2 + * I2S right channel will be mapped to DAC channel 1 + */ +esp_err_t dac_output_enable(dac_channel_t channel); + +/** + * @brief DAC pad output disable + * + * @param channel DAC channel + * @note DAC channel 1 is attached to GPIO25, DAC channel 2 is attached to GPIO26 + * @return + * - ESP_OK success + */ +esp_err_t dac_output_disable(dac_channel_t channel); + +/** + * @brief Enable cosine wave generator output. + * + * @return + * - ESP_OK success + */ +esp_err_t dac_cw_generator_enable(void); + +/** + * @brief Disable cosine wave generator output. + * + * @return + * - ESP_OK success + */ +esp_err_t dac_cw_generator_disable(void); + +/** + * @brief Config the cosine wave generator function in DAC module. + * + * @param cw Configuration. + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG The parameter is NULL. + */ +esp_err_t dac_cw_generator_config(dac_cw_config_t *cw); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/dedic_gpio.h b/tools/sdk/esp32c3/include/driver/include/driver/dedic_gpio.h new file mode 100644 index 00000000..f7d9b4a6 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/dedic_gpio.h @@ -0,0 +1,173 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include +#include "esp_err.h" +#include "esp_attr.h" +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Type of Dedicated GPIO bundle + */ +typedef struct dedic_gpio_bundle_t *dedic_gpio_bundle_handle_t; + +/** + * @brief Type of Dedicated GPIO bundle configuration + */ +typedef struct { + const int *gpio_array; /*!< Array of GPIO numbers, gpio_array[0] ~ gpio_array[size-1] <=> low_dedic_channel_num ~ high_dedic_channel_num */ + size_t array_size; /*!< Number of GPIOs in gpio_array */ + struct { + int in_en: 1; /*!< Enable input */ + int in_invert: 1; /*!< Invert input signal */ + int out_en: 1; /*!< Enable output */ + int out_invert: 1; /*!< Invert output signal */ + } flags; /*!< Flags to control specific behaviour of GPIO bundle */ +} dedic_gpio_bundle_config_t; + +/** + * @brief Create GPIO bundle and return the handle + * + * @param[in] config Configuration of GPIO bundle + * @param[out] ret_bundle Returned handle of the new created GPIO bundle + * @return + * - ESP_OK: Create GPIO bundle successfully + * - ESP_ERR_INVALID_ARG: Create GPIO bundle failed because of invalid argument + * - ESP_ERR_NO_MEM: Create GPIO bundle failed because of no capable memory + * - ESP_ERR_NOT_FOUND: Create GPIO bundle failed because of no enough continuous dedicated channels + * - ESP_FAIL: Create GPIO bundle failed because of other error + * + * @note One has to enable at least input or output mode in "config" parameter. + */ +esp_err_t dedic_gpio_new_bundle(const dedic_gpio_bundle_config_t *config, dedic_gpio_bundle_handle_t *ret_bundle); + +/** + * @brief Destory GPIO bundle + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @return + * - ESP_OK: Destory GPIO bundle successfully + * - ESP_ERR_INVALID_ARG: Destory GPIO bundle failed because of invalid argument + * - ESP_FAIL: Destory GPIO bundle failed because of other error + */ +esp_err_t dedic_gpio_del_bundle(dedic_gpio_bundle_handle_t bundle); + +/**@{*/ +/** + * @brief Get allocated channel mask + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @param[out] mask Returned mask value for on specific direction (in or out) + * @return + * - ESP_OK: Get channel mask successfully + * - ESP_ERR_INVALID_ARG: Get channel mask failed because of invalid argument + * - ESP_FAIL: Get channel mask failed because of other error + * + * @note Each bundle should have at least one mask (in or/and out), based on bundle configuration. + * @note With the returned mask, user can directly invoke LL function like "cpu_ll_write_dedic_gpio_mask" + * or write assembly code with dedicated GPIO instructions, to get better performance on GPIO manipulation. + */ +esp_err_t dedic_gpio_get_out_mask(dedic_gpio_bundle_handle_t bundle, uint32_t *mask); +esp_err_t dedic_gpio_get_in_mask(dedic_gpio_bundle_handle_t bundle, uint32_t *mask); +/**@}*/ + +/** + * @brief Write value to GPIO bundle + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @param[in] mask Mask of the GPIOs to be written in the given bundle + * @param[in] value Value to write to given GPIO bundle, low bit represents low member in the bundle + * + * @note The mask is seen from the view of GPIO bundle. + * For example, bundleA contains [GPIO10, GPIO12, GPIO17], to set GPIO17 individually, the mask should be 0x04. + * @note For performance reasons, this function doesn't check the validity of any parameters, and is placed in IRAM. + */ +void dedic_gpio_bundle_write(dedic_gpio_bundle_handle_t bundle, uint32_t mask, uint32_t value) IRAM_ATTR; + +/** + * @brief Read the value that output from the given GPIO bundle + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @return Value that output from the GPIO bundle, low bit represents low member in the bundle + * + * @note For performance reasons, this function doesn't check the validity of any parameters, and is placed in IRAM. + */ +uint32_t dedic_gpio_bundle_read_out(dedic_gpio_bundle_handle_t bundle) IRAM_ATTR; + +/** + * @brief Read the value that input to the given GPIO bundle + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @return Value that input to the GPIO bundle, low bit represents low member in the bundle + * + * @note For performance reasons, this function doesn't check the validity of any parameters, and is placed in IRAM. + */ +uint32_t dedic_gpio_bundle_read_in(dedic_gpio_bundle_handle_t bundle) IRAM_ATTR; + +#if SOC_DEDIC_GPIO_HAS_INTERRUPT + +/** + * @brief Supported type of dedicated GPIO interrupt + */ +typedef enum { + DEDIC_GPIO_INTR_NONE, /*!< No interrupt */ + DEDIC_GPIO_INTR_LOW_LEVEL = 2, /*!< Interrupt on low level */ + DEDIC_GPIO_INTR_HIGH_LEVEL, /*!< Interrupt on high level */ + DEDIC_GPIO_INTR_NEG_EDGE, /*!< Interrupt on negedge */ + DEDIC_GPIO_INTR_POS_EDGE, /*!< Interrupt on posedge */ + DEDIC_GPIO_INTR_BOTH_EDGE /*!< Interrupt on both negedge and posedge */ +} dedic_gpio_intr_type_t; + +/** + * @brief Type of dedicated GPIO ISR callback function + * + * @param bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @param index Index of the GPIO in its corresponding bundle (count from 0) + * @param args User defined arguments for the callback function. It's passed through `dedic_gpio_bundle_set_interrupt_and_callback` + * @return If a high priority task is woken up by the callback function + */ +typedef bool (*dedic_gpio_isr_callback_t)(dedic_gpio_bundle_handle_t bundle, uint32_t index, void *args); + +/** + * @brief Set interrupt and callback function for GPIO bundle + * + * @param[in] bundle Handle of GPIO bundle that returned from "dedic_gpio_new_bundle" + * @param[in] mask Mask of the GPIOs in the given bundle + * @param[in] intr_type Interrupt type, set to DEDIC_GPIO_INTR_NONE can disable interrupt + * @param[in] cb_isr Callback function, which got invoked in ISR context. A NULL pointer here will bypass the callback + * @param[in] cb_args User defined argument to be passed to the callback function + * + * @note This function is only valid for bundle with input mode enabled. See "dedic_gpio_bundle_config_t" + * @note The mask is seen from the view of GPIO Bundle. + * For example, bundleA contains [GPIO10, GPIO12, GPIO17], to set GPIO17 individually, the mask should be 0x04. + * + * @return + * - ESP_OK: Set GPIO interrupt and callback function successfully + * - ESP_ERR_INVALID_ARG: Set GPIO interrupt and callback function failed because of invalid argument + * - ESP_FAIL: Set GPIO interrupt and callback function failed because of other error + */ +esp_err_t dedic_gpio_bundle_set_interrupt_and_callback(dedic_gpio_bundle_handle_t bundle, uint32_t mask, dedic_gpio_intr_type_t intr_type, dedic_gpio_isr_callback_t cb_isr, void *cb_args); + +#endif // SOC_DEDIC_GPIO_HAS_INTERRUPT + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/gpio.h b/tools/sdk/esp32c3/include/driver/include/driver/gpio.h new file mode 100644 index 00000000..c166ffa2 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/gpio.h @@ -0,0 +1,555 @@ +// Copyright 2015-2019 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. + +#pragma once +#include "sdkconfig.h" +#include "esp_err.h" +#include +#include +#include "esp_attr.h" +#include "esp_intr_alloc.h" +#include "soc/soc_caps.h" +#include "soc/gpio_periph.h" +#include "hal/gpio_types.h" + +// |================================= WARNING ====================================================== | +// | Including ROM header file in a PUBLIC API file will be REMOVED in the next major release (5.x). | +// | User should include "esp_rom_gpio.h" in their code if they have to use those ROM API. | +// |================================================================================================ | +#if CONFIG_IDF_TARGET_ESP32 +#include "esp32/rom/gpio.h" +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/rom/gpio.h" +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/rom/gpio.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/gpio.h" +#endif + +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/rtc_io_reg.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define GPIO_PIN_COUNT (SOC_GPIO_PIN_COUNT) +/// Check whether it is a valid GPIO number +#define GPIO_IS_VALID_GPIO(gpio_num) (((1ULL << (gpio_num)) & SOC_GPIO_VALID_GPIO_MASK) != 0) +/// Check whether it can be a valid GPIO number of output mode +#define GPIO_IS_VALID_OUTPUT_GPIO(gpio_num) (((1ULL << (gpio_num)) & SOC_GPIO_VALID_OUTPUT_GPIO_MASK) != 0) + + +typedef intr_handle_t gpio_isr_handle_t; + +/** + * @brief GPIO common configuration + * + * Configure GPIO's Mode,pull-up,PullDown,IntrType + * + * @param pGPIOConfig Pointer to GPIO configure struct + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * + */ +esp_err_t gpio_config(const gpio_config_t *pGPIOConfig); + +/** + * @brief Reset an gpio to default state (select gpio function, enable pullup and disable input and output). + * + * @param gpio_num GPIO number. + * + * @note This function also configures the IOMUX for this pin to the GPIO + * function, and disconnects any other peripheral output configured via GPIO + * Matrix. + * + * @return Always return ESP_OK. + */ +esp_err_t gpio_reset_pin(gpio_num_t gpio_num); + +/** + * @brief GPIO set interrupt trigger type + * + * @param gpio_num GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param intr_type Interrupt type, select from gpio_int_type_t + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * + */ +esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type); + +/** + * @brief Enable GPIO module interrupt signal + * + * @note Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi with sleep mode enabled. + * Please refer to the comments of `adc1_get_raw`. + * Please refer to section 3.11 of 'ECO_and_Workarounds_for_Bugs_in_ESP32' for the description of this issue. + * As a workaround, call adc_power_acquire() in the app. This will result in higher power consumption (by ~1mA), + * but will remove the glitches on GPIO36 and GPIO39. + * + * @param gpio_num GPIO number. If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * + */ +esp_err_t gpio_intr_enable(gpio_num_t gpio_num); + +/** + * @brief Disable GPIO module interrupt signal + * + * @param gpio_num GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG Parameter error + * + */ +esp_err_t gpio_intr_disable(gpio_num_t gpio_num); + +/** + * @brief GPIO set output level + * + * @param gpio_num GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param level Output level. 0: low ; 1: high + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO number error + * + */ +esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level); + +/** + * @brief GPIO get input level + * + * @warning If the pad is not configured for input (or input and output) the returned value is always 0. + * + * @param gpio_num GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); + * + * @return + * - 0 the GPIO input level is 0 + * - 1 the GPIO input level is 1 + * + */ +int gpio_get_level(gpio_num_t gpio_num); + +/** + * @brief GPIO set direction + * + * Configure GPIO direction,such as output_only,input_only,output_and_input + * + * @param gpio_num Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param mode GPIO direction + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO error + * + */ +esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode); + +/** + * @brief Configure GPIO pull-up/pull-down resistors + * + * Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. + * + * @param gpio_num GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param pull GPIO pull up/down mode. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG : Parameter error + * + */ +esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull); + +/** + * @brief Enable GPIO wake-up function. + * + * @param gpio_num GPIO number. + * + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type); + +/** + * @brief Disable GPIO wake-up function. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num); + +/** + * @brief Register GPIO interrupt handler, the handler is an ISR. + * The handler will be attached to the same CPU core that this function is running on. + * + * This ISR function is called whenever any GPIO interrupt occurs. See + * the alternative gpio_install_isr_service() and + * gpio_isr_handler_add() API in order to have the driver support + * per-GPIO ISRs. + * + * @param fn Interrupt handler function. + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @param arg Parameter for handler function + * @param handle Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here. + * + * \verbatim embed:rst:leading-asterisk + * To disable or remove the ISR, pass the returned handle to the :doc:`interrupt allocation functions `. + * \endverbatim + * + * @return + * - ESP_OK Success ; + * - ESP_ERR_INVALID_ARG GPIO error + * - ESP_ERR_NOT_FOUND No free interrupt found with the specified flags + */ +esp_err_t gpio_isr_register(void (*fn)(void *), void *arg, int intr_alloc_flags, gpio_isr_handle_t *handle); + +/** + * @brief Enable pull-up on GPIO. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_pullup_en(gpio_num_t gpio_num); + +/** + * @brief Disable pull-up on GPIO. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_pullup_dis(gpio_num_t gpio_num); + +/** + * @brief Enable pull-down on GPIO. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_pulldown_en(gpio_num_t gpio_num); + +/** + * @brief Disable pull-down on GPIO. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num); + +/** + * @brief Install the driver's GPIO ISR handler service, which allows per-pin GPIO interrupt handlers. + * + * This function is incompatible with gpio_isr_register() - if that function is used, a single global ISR is registered for all GPIO interrupts. If this function is used, the ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_handler_add() function. + * + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM No memory to install this service + * - ESP_ERR_INVALID_STATE ISR service already installed. + * - ESP_ERR_NOT_FOUND No free interrupt found with the specified flags + * - ESP_ERR_INVALID_ARG GPIO error + */ +esp_err_t gpio_install_isr_service(int intr_alloc_flags); + +/** + * @brief Uninstall the driver's GPIO ISR service, freeing related resources. + */ +void gpio_uninstall_isr_service(void); + +/** + * @brief Add ISR handler for the corresponding GPIO pin. + * + * Call this function after using gpio_install_isr_service() to + * install the driver's GPIO ISR handler service. + * + * The pin ISR handlers no longer need to be declared with IRAM_ATTR, + * unless you pass the ESP_INTR_FLAG_IRAM flag when allocating the + * ISR in gpio_install_isr_service(). + * + * This ISR handler will be called from an ISR. So there is a stack + * size limit (configurable as "ISR stack size" in menuconfig). This + * limit is smaller compared to a global GPIO interrupt handler due + * to the additional level of indirection. + * + * @param gpio_num GPIO number + * @param isr_handler ISR handler function for the corresponding GPIO number. + * @param args parameter for ISR handler. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_isr_handler_add(gpio_num_t gpio_num, gpio_isr_t isr_handler, void *args); + +/** + * @brief Remove ISR handler for the corresponding GPIO pin. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized. + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_isr_handler_remove(gpio_num_t gpio_num); + +/** + * @brief Set GPIO pad drive capability + * + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Drive capability of the pad + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength); + +/** + * @brief Get GPIO pad drive capability + * + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Pointer to accept drive capability of the pad + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t *strength); + +/** + * @brief Enable gpio pad hold function. + * + * The gpio pad hold function works in both input and output modes, but must be output-capable gpios. + * If pad hold enabled: + * in output mode: the output level of the pad will be force locked and can not be changed. + * in input mode: the input value read will not change, regardless the changes of input signal. + * + * The state of digital gpio cannot be held during Deep-sleep, and it will resume the hold function + * when the chip wakes up from Deep-sleep. If the digital gpio also needs to be held during Deep-sleep, + * `gpio_deep_sleep_hold_en` should also be called. + * + * Power down or call gpio_hold_dis will disable this function. + * + * @param gpio_num GPIO number, only support output-capable GPIOs + * + * @return + * - ESP_OK Success + * - ESP_ERR_NOT_SUPPORTED Not support pad hold function + */ +esp_err_t gpio_hold_en(gpio_num_t gpio_num); + +/** + * @brief Disable gpio pad hold function. + * + * When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output + * the default level if this function is called. If you don't want the level changes, the gpio should be configured to + * a known state before this function is called. + * e.g. + * If you hold gpio18 high during Deep-sleep, after the chip is woken up and `gpio_hold_dis` is called, + * gpio18 will output low level(because gpio18 is input mode by default). If you don't want this behavior, + * you should configure gpio18 as output mode and set it to hight level before calling `gpio_hold_dis`. + * + * @param gpio_num GPIO number, only support output-capable GPIOs + * + * @return + * - ESP_OK Success + * - ESP_ERR_NOT_SUPPORTED Not support pad hold function + */ +esp_err_t gpio_hold_dis(gpio_num_t gpio_num); + +/** + * @brief Enable all digital gpio pad hold function during Deep-sleep. + * + * When the chip is in Deep-sleep mode, all digital gpio will hold the state before sleep, and when the chip is woken up, + * the status of digital gpio will not be held. Note that the pad hold feature only works when the chip is in Deep-sleep mode, + * when not in sleep mode, the digital gpio state can be changed even you have called this function. + * + * Power down or call gpio_hold_dis will disable this function, otherwise, the digital gpio hold feature works as long as the chip enter Deep-sleep. + */ +void gpio_deep_sleep_hold_en(void); + +/** + * @brief Disable all digital gpio pad hold function during Deep-sleep. + * + */ +void gpio_deep_sleep_hold_dis(void); + +/** + * @brief Set pad input to a peripheral signal through the IOMUX. + * @param gpio_num GPIO number of the pad. + * @param signal_idx Peripheral signal id to input. One of the ``*_IN_IDX`` signals in ``soc/gpio_sig_map.h``. + */ +void gpio_iomux_in(uint32_t gpio_num, uint32_t signal_idx); + +/** + * @brief Set peripheral output to an GPIO pad through the IOMUX. + * @param gpio_num gpio_num GPIO number of the pad. + * @param func The function number of the peripheral pin to output pin. + * One of the ``FUNC_X_*`` of specified pin (X) in ``soc/io_mux_reg.h``. + * @param oen_inv True if the output enable needs to be inverted, otherwise False. + */ +void gpio_iomux_out(uint8_t gpio_num, int func, bool oen_inv); + +#if SOC_GPIO_SUPPORT_FORCE_HOLD +/** + * @brief Force hold digital and rtc gpio pad. + * @note GPIO force hold, whether the chip in sleep mode or wakeup mode. + * */ +esp_err_t gpio_force_hold_all(void); + +/** + * @brief Force unhold digital and rtc gpio pad. + * @note GPIO force unhold, whether the chip in sleep mode or wakeup mode. + * */ +esp_err_t gpio_force_unhold_all(void); +#endif + +#if SOC_GPIO_SUPPORT_SLP_SWITCH +/** + * @brief Enable SLP_SEL to change GPIO status automantically in lightsleep. + * @param gpio_num GPIO number of the pad. + * + * @return + * - ESP_OK Success + * + */ +esp_err_t gpio_sleep_sel_en(gpio_num_t gpio_num); + +/** + * @brief Disable SLP_SEL to change GPIO status automantically in lightsleep. + * @param gpio_num GPIO number of the pad. + * + * @return + * - ESP_OK Success + */ +esp_err_t gpio_sleep_sel_dis(gpio_num_t gpio_num); + +/** + * @brief GPIO set direction at sleep + * + * Configure GPIO direction,such as output_only,input_only,output_and_input + * + * @param gpio_num Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param mode GPIO direction + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO error + */ +esp_err_t gpio_sleep_set_direction(gpio_num_t gpio_num, gpio_mode_t mode); + +/** + * @brief Configure GPIO pull-up/pull-down resistors at sleep + * + * Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not. + * + * @param gpio_num GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param pull GPIO pull up/down mode. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG : Parameter error + */ +esp_err_t gpio_sleep_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull); + +#if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL +/** + * @brief Emulate ESP32S2 behaviour to backup FUN_PU, FUN_PD information + * + * @note Need to be called before sleep. + * + * @return + * - ESP_OK Success + */ +esp_err_t gpio_sleep_pupd_config_apply(gpio_num_t gpio_num); + +/** + * @brief Emulate ESP32S2 behaviour to restore FUN_PU, FUN_PD information + * + * @note Need to be called after sleep. + * + * @return + * - ESP_OK Success + */ +esp_err_t gpio_sleep_pupd_config_unapply(gpio_num_t gpio_num); +#endif +#endif + +#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP + +#define GPIO_IS_DEEP_SLEEP_WAKEUP_VALID_GPIO(gpio_num) ((gpio_num & ~SOC_GPIO_DEEP_SLEEP_WAKEUP_VALID_GPIO_MASK) == 0) + +/** + * @brief Enable GPIO deep-sleep wake-up function. + * + * @param gpio_num GPIO number. + * + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + * + * @note Called by the SDK. User shouldn't call this directly in the APP. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_deep_sleep_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type); + +/** + * @brief Disable GPIO deep-sleep wake-up function. + * + * @param gpio_num GPIO number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t gpio_deep_sleep_wakeup_disable(gpio_num_t gpio_num); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/i2c.h b/tools/sdk/esp32c3/include/driver/include/driver/i2c.h new file mode 100644 index 00000000..30488fc5 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/i2c.h @@ -0,0 +1,519 @@ +// Copyright 2015-2020 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. + +#ifndef _DRIVER_I2C_H_ +#define _DRIVER_I2C_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "esp_err.h" +#include "esp_intr_alloc.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/ringbuf.h" +#include "driver/gpio.h" +#include "soc/soc_caps.h" +#include "hal/i2c_types.h" + +#define I2C_APB_CLK_FREQ APB_CLK_FREQ /*!< I2C source clock is APB clock, 80MHz */ + +#define I2C_NUM_0 (0) /*!< I2C port 0 */ +#define I2C_NUM_1 (1) /*!< I2C port 1 */ +#define I2C_NUM_MAX (SOC_I2C_NUM) /*!< I2C port max */ + +typedef void *i2c_cmd_handle_t; /*!< I2C command handle */ + +/** + * @brief I2C driver install + * + * @param i2c_num I2C port number + * @param mode I2C mode( master or slave ) + * @param slv_rx_buf_len receiving buffer size for slave mode + * @note + * Only slave mode will use this value, driver will ignore this value in master mode. + * @param slv_tx_buf_len sending buffer size for slave mode + * @note + * Only slave mode will use this value, driver will ignore this value in master mode. + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @note + * In master mode, if the cache is likely to be disabled(such as write flash) and the slave is time-sensitive, + * `ESP_INTR_FLAG_IRAM` is suggested to be used. In this case, please use the memory allocated from internal RAM in i2c read and write function, + * because we can not access the psram(if psram is enabled) in interrupt handle function when cache is disabled. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Driver install error + */ +esp_err_t i2c_driver_install(i2c_port_t i2c_num, i2c_mode_t mode, size_t slv_rx_buf_len, size_t slv_tx_buf_len, int intr_alloc_flags); + +/** + * @brief I2C driver delete + * + * @param i2c_num I2C port number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_driver_delete(i2c_port_t i2c_num); + +/** + * @brief I2C parameter initialization + * + * @param i2c_num I2C port number + * @param i2c_conf pointer to I2C parameter settings + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_param_config(i2c_port_t i2c_num, const i2c_config_t *i2c_conf); + +/** + * @brief reset I2C tx hardware fifo + * + * @param i2c_num I2C port number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_reset_tx_fifo(i2c_port_t i2c_num); + +/** + * @brief reset I2C rx fifo + * + * @param i2c_num I2C port number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_reset_rx_fifo(i2c_port_t i2c_num); + +/** + * @brief I2C isr handler register + * + * @param i2c_num I2C port number + * @param fn isr handler function + * @param arg parameter for isr handler function + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @param handle handle return from esp_intr_alloc. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_isr_register(i2c_port_t i2c_num, void (*fn)(void *), void *arg, int intr_alloc_flags, intr_handle_t *handle); + +/** + * @brief to delete and free I2C isr. + * + * @param handle handle of isr. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_isr_free(intr_handle_t handle); + +/** + * @brief Configure GPIO signal for I2C sck and sda + * + * @param i2c_num I2C port number + * @param sda_io_num GPIO number for I2C sda signal + * @param scl_io_num GPIO number for I2C scl signal + * @param sda_pullup_en Whether to enable the internal pullup for sda pin + * @param scl_pullup_en Whether to enable the internal pullup for scl pin + * @param mode I2C mode + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_pin(i2c_port_t i2c_num, int sda_io_num, int scl_io_num, + bool sda_pullup_en, bool scl_pullup_en, i2c_mode_t mode); + +/** + * @brief Create and init I2C command link + * @note + * Before we build I2C command link, we need to call i2c_cmd_link_create() to create + * a command link. + * After we finish sending the commands, we need to call i2c_cmd_link_delete() to + * release and return the resources. + * + * @return i2c command link handler + */ +i2c_cmd_handle_t i2c_cmd_link_create(void); + +/** + * @brief Free I2C command link + * @note + * Before we build I2C command link, we need to call i2c_cmd_link_create() to create + * a command link. + * After we finish sending the commands, we need to call i2c_cmd_link_delete() to + * release and return the resources. + * + * @param cmd_handle I2C command handle + */ +void i2c_cmd_link_delete(i2c_cmd_handle_t cmd_handle); + +/** + * @brief Queue command for I2C master to generate a start signal + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_start(i2c_cmd_handle_t cmd_handle); + +/** + * @brief Queue command for I2C master to write one byte to I2C bus + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * @param data I2C one byte command to write to bus + * @param ack_en enable ack check for master + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_write_byte(i2c_cmd_handle_t cmd_handle, uint8_t data, bool ack_en); + +/** + * @brief Queue command for I2C master to write buffer to I2C bus + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * @param data data to send + * @note + * If the psram is enabled and intr_flag is `ESP_INTR_FLAG_IRAM`, please use the memory allocated from internal RAM. + * @param data_len data length + * @param ack_en enable ack check for master + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_write(i2c_cmd_handle_t cmd_handle, const uint8_t *data, size_t data_len, bool ack_en); + +/** + * @brief Queue command for I2C master to read one byte from I2C bus + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * @param data pointer accept the data byte + * @note + * If the psram is enabled and intr_flag is `ESP_INTR_FLAG_IRAM`, please use the memory allocated from internal RAM. + * @param ack ack value for read command + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_read_byte(i2c_cmd_handle_t cmd_handle, uint8_t *data, i2c_ack_type_t ack); + +/** + * @brief Queue command for I2C master to read data from I2C bus + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * @param data data buffer to accept the data from bus + * @note + * If the psram is enabled and intr_flag is `ESP_INTR_FLAG_IRAM`, please use the memory allocated from internal RAM. + * @param data_len read data length + * @param ack ack value for read command + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_read(i2c_cmd_handle_t cmd_handle, uint8_t *data, size_t data_len, i2c_ack_type_t ack); + +/** + * @brief Queue command for I2C master to generate a stop signal + * @note + * Only call this function in I2C master mode + * Call i2c_master_cmd_begin() to send all queued commands + * + * @param cmd_handle I2C cmd link + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_master_stop(i2c_cmd_handle_t cmd_handle); + +/** + * @brief I2C master send queued commands. + * This function will trigger sending all queued commands. + * The task will be blocked until all the commands have been sent out. + * The I2C APIs are not thread-safe, if you want to use one I2C port in different tasks, + * you need to take care of the multi-thread issue. + * @note + * Only call this function in I2C master mode + * + * @param i2c_num I2C port number + * @param cmd_handle I2C command handler + * @param ticks_to_wait maximum wait ticks. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Sending command error, slave doesn't ACK the transfer. + * - ESP_ERR_INVALID_STATE I2C driver not installed or not in master mode. + * - ESP_ERR_TIMEOUT Operation timeout because the bus is busy. + */ +esp_err_t i2c_master_cmd_begin(i2c_port_t i2c_num, i2c_cmd_handle_t cmd_handle, TickType_t ticks_to_wait); + +/** + * @brief I2C slave write data to internal ringbuffer, when tx fifo empty, isr will fill the hardware + * fifo from the internal ringbuffer + * @note + * Only call this function in I2C slave mode + * + * @param i2c_num I2C port number + * @param data data pointer to write into internal buffer + * @param size data size + * @param ticks_to_wait Maximum waiting ticks + * + * @return + * - ESP_FAIL(-1) Parameter error + * - Others(>=0) The number of data bytes that pushed to the I2C slave buffer. + */ +int i2c_slave_write_buffer(i2c_port_t i2c_num, const uint8_t *data, int size, TickType_t ticks_to_wait); + +/** + * @brief I2C slave read data from internal buffer. When I2C slave receive data, isr will copy received data + * from hardware rx fifo to internal ringbuffer. Then users can read from internal ringbuffer. + * @note + * Only call this function in I2C slave mode + * + * @param i2c_num I2C port number + * @param data data pointer to accept data from internal buffer + * @param max_size Maximum data size to read + * @param ticks_to_wait Maximum waiting ticks + * + * @return + * - ESP_FAIL(-1) Parameter error + * - Others(>=0) The number of data bytes that read from I2C slave buffer. + */ +int i2c_slave_read_buffer(i2c_port_t i2c_num, uint8_t *data, size_t max_size, TickType_t ticks_to_wait); + +/** + * @brief set I2C master clock period + * + * @param i2c_num I2C port number + * @param high_period clock cycle number during SCL is high level, high_period is a 14 bit value + * @param low_period clock cycle number during SCL is low level, low_period is a 14 bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_period(i2c_port_t i2c_num, int high_period, int low_period); + +/** + * @brief get I2C master clock period + * + * @param i2c_num I2C port number + * @param high_period pointer to get clock cycle number during SCL is high level, will get a 14 bit value + * @param low_period pointer to get clock cycle number during SCL is low level, will get a 14 bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_period(i2c_port_t i2c_num, int *high_period, int *low_period); + +/** + * @brief enable hardware filter on I2C bus + * Sometimes the I2C bus is disturbed by high frequency noise(about 20ns), or the rising edge of + * the SCL clock is very slow, these may cause the master state machine broken. enable hardware + * filter can filter out high frequency interference and make the master more stable. + * @note + * Enable filter will slow the SCL clock. + * + * @param i2c_num I2C port number + * @param cyc_num the APB cycles need to be filtered(0<= cyc_num <=7). + * When the period of a pulse is less than cyc_num * APB_cycle, the I2C controller will ignore this pulse. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_filter_enable(i2c_port_t i2c_num, uint8_t cyc_num); + +/** + * @brief disable filter on I2C bus + * + * @param i2c_num I2C port number + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_filter_disable(i2c_port_t i2c_num); + +/** + * @brief set I2C master start signal timing + * + * @param i2c_num I2C port number + * @param setup_time clock number between the falling-edge of SDA and rising-edge of SCL for start mark, it's a 10-bit value. + * @param hold_time clock num between the falling-edge of SDA and falling-edge of SCL for start mark, it's a 10-bit value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_start_timing(i2c_port_t i2c_num, int setup_time, int hold_time); + +/** + * @brief get I2C master start signal timing + * + * @param i2c_num I2C port number + * @param setup_time pointer to get setup time + * @param hold_time pointer to get hold time + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_start_timing(i2c_port_t i2c_num, int *setup_time, int *hold_time); + +/** + * @brief set I2C master stop signal timing + * + * @param i2c_num I2C port number + * @param setup_time clock num between the rising-edge of SCL and the rising-edge of SDA, it's a 10-bit value. + * @param hold_time clock number after the STOP bit's rising-edge, it's a 14-bit value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_stop_timing(i2c_port_t i2c_num, int setup_time, int hold_time); + +/** + * @brief get I2C master stop signal timing + * + * @param i2c_num I2C port number + * @param setup_time pointer to get setup time. + * @param hold_time pointer to get hold time. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_stop_timing(i2c_port_t i2c_num, int *setup_time, int *hold_time); + +/** + * @brief set I2C data signal timing + * + * @param i2c_num I2C port number + * @param sample_time clock number I2C used to sample data on SDA after the rising-edge of SCL, it's a 10-bit value + * @param hold_time clock number I2C used to hold the data after the falling-edge of SCL, it's a 10-bit value + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_data_timing(i2c_port_t i2c_num, int sample_time, int hold_time); + +/** + * @brief get I2C data signal timing + * + * @param i2c_num I2C port number + * @param sample_time pointer to get sample time + * @param hold_time pointer to get hold time + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_data_timing(i2c_port_t i2c_num, int *sample_time, int *hold_time); + +/** + * @brief set I2C timeout value + * @param i2c_num I2C port number + * @param timeout timeout value for I2C bus (unit: APB 80Mhz clock cycle) + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_timeout(i2c_port_t i2c_num, int timeout); + +/** + * @brief get I2C timeout value + * @param i2c_num I2C port number + * @param timeout pointer to get timeout value + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_timeout(i2c_port_t i2c_num, int *timeout); + +/** + * @brief set I2C data transfer mode + * + * @param i2c_num I2C port number + * @param tx_trans_mode I2C sending data mode + * @param rx_trans_mode I2C receving data mode + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_set_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t tx_trans_mode, i2c_trans_mode_t rx_trans_mode); + +/** + * @brief get I2C data transfer mode + * + * @param i2c_num I2C port number + * @param tx_trans_mode pointer to get I2C sending data mode + * @param rx_trans_mode pointer to get I2C receiving data mode + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2c_get_data_mode(i2c_port_t i2c_num, i2c_trans_mode_t *tx_trans_mode, i2c_trans_mode_t *rx_trans_mode); + +#ifdef __cplusplus +} +#endif + +#endif /*_DRIVER_I2C_H_*/ diff --git a/tools/sdk/esp32c3/include/driver/include/driver/i2s.h b/tools/sdk/esp32c3/include/driver/include/driver/i2s.h new file mode 100644 index 00000000..e5968ad3 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/i2s.h @@ -0,0 +1,338 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include "esp_types.h" +#include "esp_err.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "soc/i2s_periph.h" +#include "soc/rtc_periph.h" +#include "soc/soc_caps.h" +#include "hal/i2s_hal.h" +#include "hal/i2s_types.h" +#include "driver/periph_ctrl.h" +#include "esp_intr_alloc.h" +#if SOC_I2S_SUPPORTS_ADC_DAC +#include "driver/adc.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#define I2S_PIN_NO_CHANGE (-1) /*!< Use in i2s_pin_config_t for pins which should not be changed */ + +typedef intr_handle_t i2s_isr_handle_t; + +/** + * @brief Set I2S pin number + * + * @note + * The I2S peripheral output signals can be connected to multiple GPIO pads. + * However, the I2S peripheral input signal can only be connected to one GPIO pad. + * + * @param i2s_num I2S_NUM_0 or I2S_NUM_1 + * + * @param pin I2S Pin structure, or NULL to set 2-channel 8-bit internal DAC pin configuration (GPIO25 & GPIO26) + * + * Inside the pin configuration structure, set I2S_PIN_NO_CHANGE for any pin where + * the current configuration should not be changed. + * + * @note if *pin is set as NULL, this function will initialize both of the built-in DAC channels by default. + * if you don't want this to happen and you want to initialize only one of the DAC channels, you can call i2s_set_dac_mode instead. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL IO error + */ +esp_err_t i2s_set_pin(i2s_port_t i2s_num, const i2s_pin_config_t *pin); + +#if SOC_I2S_SUPPORTS_PDM +/** + * @brief Set PDM mode down-sample rate + * In PDM RX mode, there would be 2 rounds of downsample process in hardware. + * In the first downsample process, the sampling number can be 16 or 8. + * In the second downsample process, the sampling number is fixed as 8. + * So the clock frequency in PDM RX mode would be (fpcm * 64) or (fpcm * 128) accordingly. + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * @param dsr i2s RX down sample rate for PDM mode. + * + * @note After calling this function, it would call i2s_set_clk inside to update the clock frequency. + * Please call this function after I2S driver has been initialized. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM Out of memory + */ +esp_err_t i2s_set_pdm_rx_down_sample(i2s_port_t i2s_num, i2s_pdm_dsr_t dsr); +#endif + +/** + * @brief Set I2S dac mode, I2S built-in DAC is disabled by default + * + * @param dac_mode DAC mode configurations - see i2s_dac_mode_t + * + * @note Built-in DAC functions are only supported on I2S0 for current ESP32 chip. + * If either of the built-in DAC channel are enabled, the other one can not + * be used as RTC DAC function at the same time. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_set_dac_mode(i2s_dac_mode_t dac_mode); + +/** + * @brief Install and start I2S driver. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param i2s_config I2S configurations - see i2s_config_t struct + * + * @param queue_size I2S event queue size/depth. + * + * @param i2s_queue I2S event queue handle, if set NULL, driver will not use an event queue. + * + * This function must be called before any I2S driver read/write operations. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM Out of memory + */ +esp_err_t i2s_driver_install(i2s_port_t i2s_num, const i2s_config_t *i2s_config, int queue_size, void* i2s_queue); + +/** + * @brief Uninstall I2S driver. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_driver_uninstall(i2s_port_t i2s_num); + +/** + * @brief Write data to I2S DMA transmit buffer. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param src Source address to write from + * + * @param size Size of data in bytes + * + * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in. + * + * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this + * many ticks pass without space becoming available in the DMA + * transmit buffer, then the function will return (note that if the + * data is written to the DMA buffer in pieces, the overall operation + * may still take longer than this timeout.) Pass portMAX_DELAY for no + * timeout. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_write(i2s_port_t i2s_num, const void *src, size_t size, size_t *bytes_written, TickType_t ticks_to_wait); + +/** + * @brief Write data to I2S DMA transmit buffer while expanding the number of bits per sample. For example, expanding 16-bit PCM to 32-bit PCM. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param src Source address to write from + * + * @param size Size of data in bytes + * + * @param src_bits Source audio bit + * + * @param aim_bits Bit wanted, no more than 32, and must be greater than src_bits + * + * @param[out] bytes_written Number of bytes written, if timeout, the result will be less than the size passed in. + * + * @param ticks_to_wait TX buffer wait timeout in RTOS ticks. If this + * many ticks pass without space becoming available in the DMA + * transmit buffer, then the function will return (note that if the + * data is written to the DMA buffer in pieces, the overall operation + * may still take longer than this timeout.) Pass portMAX_DELAY for no + * timeout. + * + * Format of the data in source buffer is determined by the I2S + * configuration (see i2s_config_t). + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_write_expand(i2s_port_t i2s_num, const void *src, size_t size, size_t src_bits, size_t aim_bits, size_t *bytes_written, TickType_t ticks_to_wait); + +/** + * @brief Read data from I2S DMA receive buffer + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param dest Destination address to read into + * + * @param size Size of data in bytes + * + * @param[out] bytes_read Number of bytes read, if timeout, bytes read will be less than the size passed in. + * + * @param ticks_to_wait RX buffer wait timeout in RTOS ticks. If this many ticks pass without bytes becoming available in the DMA receive buffer, then the function will return (note that if data is read from the DMA buffer in pieces, the overall operation may still take longer than this timeout.) Pass portMAX_DELAY for no timeout. + * + * @note If the built-in ADC mode is enabled, we should call i2s_adc_enable and i2s_adc_disable around the whole reading process, + * to prevent the data getting corrupted. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_read(i2s_port_t i2s_num, void *dest, size_t size, size_t *bytes_read, TickType_t ticks_to_wait); + +/** + * @brief Set sample rate used for I2S RX and TX. + * + * The bit clock rate is determined by the sample rate and i2s_config_t configuration parameters (number of channels, bits_per_sample). + * + * `bit_clock = rate * (number of channels) * bits_per_sample` + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param rate I2S sample rate (ex: 8000, 44100...) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM Out of memory + */ +esp_err_t i2s_set_sample_rates(i2s_port_t i2s_num, uint32_t rate); + +/** + * @brief Stop I2S driver + * + * There is no need to call i2s_stop() before calling i2s_driver_uninstall(). + * + * Disables I2S TX/RX, until i2s_start() is called. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_stop(i2s_port_t i2s_num); + +/** + * @brief Start I2S driver + * + * It is not necessary to call this function after i2s_driver_install() (it is started automatically), however it is necessary to call it after i2s_stop(). + * + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * +* @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_start(i2s_port_t i2s_num); + +/** + * @brief Zero the contents of the TX DMA buffer. + * + * Pushes zero-byte samples into the TX DMA buffer, until it is full. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_zero_dma_buffer(i2s_port_t i2s_num); + +/** + * @brief Set clock & bit width used for I2S RX and TX. + * + * Similar to i2s_set_sample_rates(), but also sets bit width. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @param rate I2S sample rate (ex: 8000, 44100...) + * + * @param bits I2S bit width (I2S_BITS_PER_SAMPLE_16BIT, I2S_BITS_PER_SAMPLE_24BIT, I2S_BITS_PER_SAMPLE_32BIT) + * + * @param ch I2S channel, (I2S_CHANNEL_MONO, I2S_CHANNEL_STEREO) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_NO_MEM Out of memory + */ +esp_err_t i2s_set_clk(i2s_port_t i2s_num, uint32_t rate, i2s_bits_per_sample_t bits, i2s_channel_t ch); + +/** + * @brief get clock set on particular port number. + * + * @param i2s_num I2S_NUM_0, I2S_NUM_1 + * + * @return + * - actual clock set by i2s driver + */ +float i2s_get_clk(i2s_port_t i2s_num); + +#if SOC_I2S_SUPPORTS_ADC_DAC +/** + * @brief Set built-in ADC mode for I2S DMA, this function will initialize ADC pad, + * and set ADC parameters. + * @note In this mode, the ADC maximum sampling rate is 150KHz. Set the sampling rate through ``i2s_config_t``. + * @param adc_unit SAR ADC unit index + * @param adc_channel ADC channel index + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t i2s_set_adc_mode(adc_unit_t adc_unit, adc1_channel_t adc_channel); + +/** + * @brief Start to use I2S built-in ADC mode + * @note This function would acquire the lock of ADC to prevent the data getting corrupted + * during the I2S peripheral is being used to do fully continuous ADC sampling. + * + * @param i2s_num i2s port index + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver state error + */ +esp_err_t i2s_adc_enable(i2s_port_t i2s_num); + +/** + * @brief Stop to use I2S built-in ADC mode + * @param i2s_num i2s port index + * @note This function would release the lock of ADC so that other tasks can use ADC. + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver state error + */ +esp_err_t i2s_adc_disable(i2s_port_t i2s_num); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/ledc.h b/tools/sdk/esp32c3/include/driver/include/driver/ledc.h new file mode 100644 index 00000000..2ffcbd74 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/ledc.h @@ -0,0 +1,423 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "esp_err.h" +#include "esp_intr_alloc.h" +#include "soc/soc.h" +#include "hal/ledc_types.h" +#include "driver/gpio.h" +#include "driver/periph_ctrl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LEDC_APB_CLK_HZ (APB_CLK_FREQ) +#define LEDC_REF_CLK_HZ (REF_CLK_FREQ) +#define LEDC_ERR_DUTY (0xFFFFFFFF) +#define LEDC_ERR_VAL (-1) + +typedef intr_handle_t ledc_isr_handle_t; + +/** + * @brief LEDC channel configuration + * Configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC duty resolution + * + * @param ledc_conf Pointer of LEDC channel configure struct + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_channel_config(const ledc_channel_config_t* ledc_conf); + +/** + * @brief LEDC timer configuration + * Configure LEDC timer with the given source timer/frequency(Hz)/duty_resolution + * + * @param timer_conf Pointer of LEDC timer configure struct + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. + */ +esp_err_t ledc_timer_config(const ledc_timer_config_t* timer_conf); + +/** + * @brief LEDC update channel parameters + * @note Call this function to activate the LEDC updated parameters. + * After ledc_set_duty, we need to call this function to update the settings. + * @note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to + * control one LEDC channel in different tasks at the same time. + * A thread-safe version of API is ledc_set_duty_and_update + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * + */ +esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel); + +/** + * @brief Set LEDC output gpio. + * + * @param gpio_num The LEDC output gpio + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param ledc_channel LEDC channel (0-7), select from ledc_channel_t + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_set_pin(int gpio_num, ledc_mode_t speed_mode, ledc_channel_t ledc_channel); + +/** + * @brief LEDC stop. + * Disable LEDC output, and set idle level + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @param idle_level Set output idle level after LEDC stops. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_stop(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t idle_level); + +/** + * @brief LEDC set channel frequency (Hz) + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_num LEDC timer index (0-3), select from ledc_timer_t + * @param freq_hz Set the LEDC frequency + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution. + */ +esp_err_t ledc_set_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num, uint32_t freq_hz); + +/** + * @brief LEDC get channel frequency (Hz) + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_num LEDC timer index (0-3), select from ledc_timer_t + * + * @return + * - 0 error + * - Others Current LEDC frequency + */ +uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num); + +/** + * @brief LEDC set duty and hpoint value + * Only after calling ledc_update_duty will the duty update. + * @note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to + * control one LEDC channel in different tasks at the same time. + * A thread-safe version of API is ledc_set_duty_and_update + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @param duty Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] + * @param hpoint Set the LEDC hpoint value(max: 0xfffff) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_set_duty_with_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint); + +/** + * @brief LEDC get hpoint value, the counter value when the output is set high level. + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @return + * - LEDC_ERR_VAL if parameter error + * - Others Current hpoint value of LEDC channel + */ +int ledc_get_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel); + +/** + * @brief LEDC set duty + * This function do not change the hpoint value of this channel. if needed, please call ledc_set_duty_with_hpoint. + * only after calling ledc_update_duty will the duty update. + * @note ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to + * control one LEDC channel in different tasks at the same time. + * A thread-safe version of API is ledc_set_duty_and_update. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @param duty Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty); + +/** + * @brief LEDC get duty + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * + * @return + * - LEDC_ERR_DUTY if parameter error + * - Others Current LEDC duty + */ +uint32_t ledc_get_duty(ledc_mode_t speed_mode, ledc_channel_t channel); + +/** + * @brief LEDC set gradient + * Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @param duty Set the start of the gradient duty, the range of duty setting is [0, (2**duty_resolution)] + * @param fade_direction Set the direction of the gradient + * @param step_num Set the number of the gradient + * @param duty_cycle_num Set how many LEDC tick each time the gradient lasts + * @param duty_scale Set gradient change amplitude + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t ledc_set_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, ledc_duty_direction_t fade_direction, + uint32_t step_num, uint32_t duty_cycle_num, uint32_t duty_scale); + +/** + * @brief Register LEDC interrupt handler, the handler is an ISR. + * The handler will be attached to the same CPU core that this function is running on. + * + * @param fn Interrupt handler function. + * @param arg User-supplied argument passed to the handler function. + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @param handle Pointer to return handle. If non-NULL, a handle for the interrupt will + * be returned here. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Function pointer error. + */ +esp_err_t ledc_isr_register(void (*fn)(void*), void * arg, int intr_alloc_flags, ledc_isr_handle_t *handle); + +/** + * @brief Configure LEDC settings + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_sel Timer index (0-3), there are 4 timers in LEDC module + * @param clock_divider Timer clock divide value, the timer clock is divided from the selected clock source + * @param duty_resolution Resolution of duty setting in number of bits. The range of duty values is [0, (2**duty_resolution)] + * @param clk_src Select LEDC source clock. + * + * @return + * - (-1) Parameter error + * - Other Current LEDC duty + */ +esp_err_t ledc_timer_set(ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t clock_divider, uint32_t duty_resolution, ledc_clk_src_t clk_src); + +/** + * @brief Reset LEDC timer + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + */ +esp_err_t ledc_timer_rst(ledc_mode_t speed_mode, ledc_timer_t timer_sel); + +/** + * @brief Pause LEDC timer counter + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + * + */ +esp_err_t ledc_timer_pause(ledc_mode_t speed_mode, ledc_timer_t timer_sel); + +/** + * @brief Resume LEDC timer + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + */ +esp_err_t ledc_timer_resume(ledc_mode_t speed_mode, ledc_timer_t timer_sel); + +/** + * @brief Bind LEDC channel with the selected timer + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel index (0-7), select from ledc_channel_t + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + */ +esp_err_t ledc_bind_channel_timer(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_timer_t timer_sel); + +/** + * @brief Set LEDC fade function. + * @note Call ledc_fade_func_install() once before calling this function. + * Call ledc_fade_start() after this to start fading. + * @note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to + * control one LEDC channel in different tasks at the same time. + * A thread-safe version of API is ledc_set_fade_step_and_start + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. , + * @param channel LEDC channel index (0-7), select from ledc_channel_t + * @param target_duty Target duty of fading [0, (2**duty_resolution) - 1] + * @param scale Controls the increase or decrease step scale. + * @param cycle_num increase or decrease the duty every cycle_num cycles + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function not installed. + * - ESP_FAIL Fade function init error + */ +esp_err_t ledc_set_fade_with_step(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num); + +/** + * @brief Set LEDC fade function, with a limited time. + * @note Call ledc_fade_func_install() once before calling this function. + * Call ledc_fade_start() after this to start fading. + * @note ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to + * control one LEDC channel in different tasks at the same time. + * A thread-safe version of API is ledc_set_fade_step_and_start + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. , + * @param channel LEDC channel index (0-7), select from ledc_channel_t + * @param target_duty Target duty of fading.( 0 - (2 ** duty_resolution - 1))) + * @param max_fade_time_ms The maximum time of the fading ( ms ). + * + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function not installed. + * - ESP_FAIL Fade function init error + */ +esp_err_t ledc_set_fade_with_time(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, int max_fade_time_ms); + +/** + * @brief Install LEDC fade function. This function will occupy interrupt of LEDC module. + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function already installed. + */ +esp_err_t ledc_fade_func_install(int intr_alloc_flags); + +/** + * @brief Uninstall LEDC fade function. + * + */ +void ledc_fade_func_uninstall(void); + +/** + * @brief Start LEDC fading. + * @note Call ledc_fade_func_install() once before calling this function. + * Call this API right after ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel number + * @param fade_mode Whether to block until fading done. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function not installed. + * - ESP_ERR_INVALID_ARG Parameter error. + */ +esp_err_t ledc_fade_start(ledc_mode_t speed_mode, ledc_channel_t channel, ledc_fade_mode_t fade_mode); + +/** + * @brief A thread-safe API to set duty for LEDC channel and return when duty updated. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel (0-7), select from ledc_channel_t + * @param duty Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)] + * @param hpoint Set the LEDC hpoint value(max: 0xfffff) + * + */ +esp_err_t ledc_set_duty_and_update(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint); + +/** + * @brief A thread-safe API to set and start LEDC fade function, with a limited time. + * @note Call ledc_fade_func_install() once, before calling this function. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel index (0-7), select from ledc_channel_t + * @param target_duty Target duty of fading.( 0 - (2 ** duty_resolution - 1))) + * @param max_fade_time_ms The maximum time of the fading ( ms ). + * @param fade_mode choose blocking or non-blocking mode + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function not installed. + * - ESP_FAIL Fade function init error + */ +esp_err_t ledc_set_fade_time_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t max_fade_time_ms, ledc_fade_mode_t fade_mode); + +/** + * @brief A thread-safe API to set and start LEDC fade function. + * @note Call ledc_fade_func_install() once before calling this function. + * @note If a fade operation is running in progress on that channel, the driver would not allow it to be stopped. + * Other duty operations will have to wait until the fade operation has finished. + * @param speed_mode Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode. + * @param channel LEDC channel index (0-7), select from ledc_channel_t + * @param target_duty Target duty of fading [0, (2**duty_resolution) - 1] + * @param scale Controls the increase or decrease step scale. + * @param cycle_num increase or decrease the duty every cycle_num cycles + * @param fade_mode choose blocking or non-blocking mode + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Fade function not installed. + * - ESP_FAIL Fade function init error + */ +esp_err_t ledc_set_fade_step_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num, ledc_fade_mode_t fade_mode); +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/mcpwm.h b/tools/sdk/esp32c3/include/driver/include/driver/mcpwm.h new file mode 100644 index 00000000..f4ec17a2 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/mcpwm.h @@ -0,0 +1,664 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include "soc/soc_caps.h" +#if SOC_MCPWM_SUPPORTED + +#include "esp_err.h" +#include "soc/soc.h" +#include "driver/gpio.h" +#include "driver/periph_ctrl.h" +#include "esp_intr_alloc.h" +#include "hal/mcpwm_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief IO signals for the MCPWM + * + * - 6 MCPWM output pins that generate PWM signals + * - 3 MCPWM fault input pins to detect faults like overcurrent, overvoltage, etc. + * - 3 MCPWM sync input pins to synchronize MCPWM outputs signals + * - 3 MCPWM capture input pins to gather feedback from controlled motors, using e.g. hall sensors + */ +typedef enum { + MCPWM0A = 0, /*!dec/dec->inc) + * .hctrl_mode = PCNT_MODE_KEEP, //when control signal is high, keep the primary counter mode + * .pos_mode = PCNT_COUNT_INC, //increment the counter + * .neg_mode = PCNT_COUNT_DIS, //keep the counter value + * .counter_h_lim = 10, + * .counter_l_lim = -10, + * }; + * pcnt_unit_config(&pcnt_config); //init unit + * @endcode + * + * EXAMPLE OF PCNT EVENT SETTING + * ============================== + * @code{c} + * //2. Configure PCNT watchpoint event. + * pcnt_set_event_value(PCNT_UNIT_0, PCNT_EVT_THRES_1, 5); //set thres1 value + * pcnt_event_enable(PCNT_UNIT_0, PCNT_EVT_THRES_1); //enable thres1 event + * @endcode + * + * For more examples please refer to PCNT example code in IDF_PATH/examples + * + * @} + */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/periph_ctrl.h b/tools/sdk/esp32c3/include/driver/include/driver/periph_ctrl.h new file mode 100644 index 00000000..3c6ff850 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/periph_ctrl.h @@ -0,0 +1,117 @@ +// Copyright 2015-2018 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. + +#ifndef _DRIVER_PERIPH_CTRL_H_ +#define _DRIVER_PERIPH_CTRL_H_ + +#include "soc/periph_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief enable peripheral module + * + * @param[in] periph : Peripheral module name + * + * Clock for the module will be ungated, and reset de-asserted. + * + * @note If periph_module_enable is called a number of times, + * periph_module_disable has to be called the same number of times + * in order to put the peripheral into disabled state. + * + * @return NULL + * + */ +void periph_module_enable(periph_module_t periph); + +/** + * @brief disable peripheral module + * + * @param[in] periph : Peripheral module name + * + * Clock for the module will be gated, reset asserted. + * + * @note If periph_module_enable is called a number of times, + * periph_module_disable has to be called the same number of times + * in order to put the peripheral into disabled state. + * + * @return NULL + * + */ +void periph_module_disable(periph_module_t periph); + +/** + * @brief reset peripheral module + * + * @param[in] periph : Peripheral module name + * + * Reset will asserted then de-assrted for the peripheral. + * + * Calling this function does not enable or disable the clock for the module. + * + * @return NULL + * + */ +void periph_module_reset(periph_module_t periph); + +/** + * @brief enable wifi bt common module + * + * @note If wifi_bt_common_module_enable is called a number of times, + * wifi_bt_common_module_disable has to be called the same number of times + * in order to put the peripheral into disabled state. + * + * @return NULL + * + */ +void wifi_bt_common_module_enable(void); + +/** + * @brief disable wifi bt common module + * + * @note If wifi_bt_common_module_enable is called a number of times, + * wifi_bt_common_module_disable has to be called the same number of times + * in order to put the peripheral into disabled state. + * + * @return NULL + * + */ +void wifi_bt_common_module_disable(void); + +/** + * @brief enable wifi module + * + * @note Enable wifi module only. + * + * @return NULL + * + */ +void wifi_module_enable(void); + +/** + * @brief disable wifi module + * + * @note Disable wifi module only. + * + * @return NULL + * + */ +void wifi_module_disable(void); +#ifdef __cplusplus +} +#endif + +#endif /* _DRIVER_PERIPH_CTRL_H_ */ diff --git a/tools/sdk/esp32c3/include/driver/include/driver/rmt.h b/tools/sdk/esp32c3/include/driver/include/driver/rmt.h new file mode 100644 index 00000000..ef9d5810 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/rmt.h @@ -0,0 +1,924 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "esp_err.h" +#include "soc/soc_caps.h" +#include "driver/gpio.h" +#include "freertos/FreeRTOS.h" +#include "freertos/ringbuf.h" +#include "soc/rmt_struct.h" +#include "hal/rmt_types.h" + +#define RMT_CHANNEL_FLAGS_AWARE_DFS (1 << 0) /*!< Channel can work during APB clock scaling */ +#define RMT_CHANNEL_FLAGS_INVERT_SIG (1 << 1) /*!< Invert RMT signal */ + +/** @cond */ +#define RMT_CHANNEL_FLAGS_ALWAYS_ON RMT_CHANNEL_FLAGS_AWARE_DFS /*!< Deprecated name, defined here for compatibility */ +/** @endcond */ + +/** + * @brief Define memory space of each RMT channel (in words = 4 bytes) + * + */ +#define RMT_MEM_ITEM_NUM SOC_RMT_MEM_WORDS_PER_CHANNEL + +/** +* @brief Data struct of RMT TX configure parameters +*/ +typedef struct { + uint32_t carrier_freq_hz; /*!< RMT carrier frequency */ + rmt_carrier_level_t carrier_level; /*!< Level of the RMT output, when the carrier is applied */ + rmt_idle_level_t idle_level; /*!< RMT idle level */ + uint8_t carrier_duty_percent; /*!< RMT carrier duty (%) */ +#if SOC_RMT_SUPPORT_TX_LOOP_COUNT + uint32_t loop_count; /*!< Maximum loop count */ +#endif + bool carrier_en; /*!< RMT carrier enable */ + bool loop_en; /*!< Enable sending RMT items in a loop */ + bool idle_output_en; /*!< RMT idle level output enable */ +} rmt_tx_config_t; + +/** +* @brief Data struct of RMT RX configure parameters +*/ +typedef struct { + uint16_t idle_threshold; /*!< RMT RX idle threshold */ + uint8_t filter_ticks_thresh; /*!< RMT filter tick number */ + bool filter_en; /*!< RMT receiver filter enable */ +#if SOC_RMT_SUPPORT_RX_DEMODULATION + bool rm_carrier; /*!< RMT receiver remove carrier enable */ + uint32_t carrier_freq_hz; /*!< RMT carrier frequency */ + uint8_t carrier_duty_percent; /*!< RMT carrier duty (%) */ + rmt_carrier_level_t carrier_level; /*!< The level to remove the carrier */ +#endif +} rmt_rx_config_t; + +/** +* @brief Data struct of RMT configure parameters +*/ +typedef struct { + rmt_mode_t rmt_mode; /*!< RMT mode: transmitter or receiver */ + rmt_channel_t channel; /*!< RMT channel */ + gpio_num_t gpio_num; /*!< RMT GPIO number */ + uint8_t clk_div; /*!< RMT channel counter divider */ + uint8_t mem_block_num; /*!< RMT memory block number */ + uint32_t flags; /*!< RMT channel extra configurations, OR'd with RMT_CHANNEL_FLAGS_[*] */ + union { + rmt_tx_config_t tx_config; /*!< RMT TX parameter */ + rmt_rx_config_t rx_config; /*!< RMT RX parameter */ + }; +} rmt_config_t; + +/** + * @brief Default configuration for Tx channel + * + */ +#define RMT_DEFAULT_CONFIG_TX(gpio, channel_id) \ + { \ + .rmt_mode = RMT_MODE_TX, \ + .channel = channel_id, \ + .gpio_num = gpio, \ + .clk_div = 80, \ + .mem_block_num = 1, \ + .flags = 0, \ + .tx_config = { \ + .carrier_freq_hz = 38000, \ + .carrier_level = RMT_CARRIER_LEVEL_HIGH, \ + .idle_level = RMT_IDLE_LEVEL_LOW, \ + .carrier_duty_percent = 33, \ + .carrier_en = false, \ + .loop_en = false, \ + .idle_output_en = true, \ + } \ + } + +/** + * @brief Default configuration for RX channel + * + */ +#define RMT_DEFAULT_CONFIG_RX(gpio, channel_id) \ + { \ + .rmt_mode = RMT_MODE_RX, \ + .channel = channel_id, \ + .gpio_num = gpio, \ + .clk_div = 80, \ + .mem_block_num = 1, \ + .flags = 0, \ + .rx_config = { \ + .idle_threshold = 12000, \ + .filter_ticks_thresh = 100, \ + .filter_en = true, \ + } \ + } + +/** +* @brief RMT interrupt handle +* +*/ +typedef intr_handle_t rmt_isr_handle_t; + +/** +* @brief Type of RMT Tx End callback function +* +*/ +typedef void (*rmt_tx_end_fn_t)(rmt_channel_t channel, void *arg); + +/** +* @brief Structure encapsulating a RMT TX end callback +*/ +typedef struct { + rmt_tx_end_fn_t function; /*!< Function which is called on RMT TX end */ + void *arg; /*!< Optional argument passed to function */ +} rmt_tx_end_callback_t; + +/** +* @brief User callback function to convert uint8_t type data to rmt format(rmt_item32_t). +* +* This function may be called from an ISR, so, the code should be short and efficient. +* +* @param src Pointer to the buffer storing the raw data that needs to be converted to rmt format. +* @param[out] dest Pointer to the buffer storing the rmt format data. +* @param src_size The raw data size. +* @param wanted_num The number of rmt format data that wanted to get. +* @param[out] translated_size The size of the raw data that has been converted to rmt format, +* it should return 0 if no data is converted in user callback. +* @param[out] item_num The number of the rmt format data that actually converted to, +* it can be less than wanted_num if there is not enough raw data, but cannot exceed wanted_num. +* it should return 0 if no data was converted. +* +* @note +* In fact, item_num should be a multiple of translated_size, e.g. : +* When we convert each byte of uint8_t type data to rmt format data, +* the relation between item_num and translated_size should be `item_num = translated_size*8`. +*/ +typedef void (*sample_to_rmt_t)(const void *src, rmt_item32_t *dest, size_t src_size, size_t wanted_num, size_t *translated_size, size_t *item_num); + +/** +* @brief Set RMT clock divider, channel clock is divided from source clock. +* +* @param channel RMT channel +* @param div_cnt RMT counter clock divider +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_clk_div(rmt_channel_t channel, uint8_t div_cnt); + +/** +* @brief Get RMT clock divider, channel clock is divided from source clock. +* +* @param channel RMT channel +* @param div_cnt pointer to accept RMT counter divider +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_clk_div(rmt_channel_t channel, uint8_t *div_cnt); + +/** +* @brief Set RMT RX idle threshold value +* +* In receive mode, when no edge is detected on the input signal +* for longer than idle_thres channel clock cycles, +* the receive process is finished. +* +* @param channel RMT channel +* @param thresh RMT RX idle threshold +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_rx_idle_thresh(rmt_channel_t channel, uint16_t thresh); + +/** +* @brief Get RMT idle threshold value. +* +* In receive mode, when no edge is detected on the input signal +* for longer than idle_thres channel clock cycles, +* the receive process is finished. +* +* @param channel RMT channel +* @param thresh pointer to accept RMT RX idle threshold value +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_rx_idle_thresh(rmt_channel_t channel, uint16_t *thresh); + +/** +* @brief Set RMT memory block number for RMT channel +* +* This function is used to configure the amount of memory blocks allocated to channel n +* The 8 channels share a 512x32-bit RAM block which can be read and written +* by the processor cores over the APB bus, as well as read by the transmitters +* and written by the receivers. +* +* The RAM address range for channel n is start_addr_CHn to end_addr_CHn, which are defined by: +* Memory block start address is RMT_CHANNEL_MEM(n) (in soc/rmt_reg.h), +* that is, start_addr_chn = RMT base address + 0x800 + 64 ∗ 4 ∗ n, and +* end_addr_chn = RMT base address + 0x800 + 64 ∗ 4 ∗ n + 64 ∗ 4 ∗ RMT_MEM_SIZE_CHn mod 512 ∗ 4 +* +* @note +* If memory block number of one channel is set to a value greater than 1, this channel will occupy the memory +* block of the next channel. +* Channel 0 can use at most 8 blocks of memory, accordingly channel 7 can only use one memory block. +* +* @param channel RMT channel +* @param rmt_mem_num RMT RX memory block number, one block has 64 * 32 bits. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_mem_block_num(rmt_channel_t channel, uint8_t rmt_mem_num); + +/** +* @brief Get RMT memory block number +* +* @param channel RMT channel +* @param rmt_mem_num Pointer to accept RMT RX memory block number +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_mem_block_num(rmt_channel_t channel, uint8_t *rmt_mem_num); + +/** +* @brief Configure RMT carrier for TX signal. +* +* Set different values for carrier_high and carrier_low to set different frequency of carrier. +* The unit of carrier_high/low is the source clock tick, not the divided channel counter clock. +* +* @param channel RMT channel +* @param carrier_en Whether to enable output carrier. +* @param high_level High level duration of carrier +* @param low_level Low level duration of carrier. +* @param carrier_level Configure the way carrier wave is modulated for channel. +* - 1'b1:transmit on low output level +* - 1'b0:transmit on high output level +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_tx_carrier(rmt_channel_t channel, bool carrier_en, uint16_t high_level, uint16_t low_level, rmt_carrier_level_t carrier_level); + +/** +* @brief Set RMT memory in low power mode. +* +* Reduce power consumed by memory. 1:memory is in low power state. +* +* @param channel RMT channel +* @param pd_en RMT memory low power enable. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_mem_pd(rmt_channel_t channel, bool pd_en); + +/** +* @brief Get RMT memory low power mode. +* +* @param channel RMT channel +* @param pd_en Pointer to accept RMT memory low power mode. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_mem_pd(rmt_channel_t channel, bool *pd_en); + +/** +* @brief Set RMT start sending data from memory. +* +* @param channel RMT channel +* @param tx_idx_rst Set true to reset memory index for TX. +* Otherwise, transmitter will continue sending from the last index in memory. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_tx_start(rmt_channel_t channel, bool tx_idx_rst); + +/** +* @brief Set RMT stop sending. +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_tx_stop(rmt_channel_t channel); + +/** +* @brief Set RMT start receiving data. +* +* @param channel RMT channel +* @param rx_idx_rst Set true to reset memory index for receiver. +* Otherwise, receiver will continue receiving data to the last index in memory. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_rx_start(rmt_channel_t channel, bool rx_idx_rst); + +/** +* @brief Set RMT stop receiving data. +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_rx_stop(rmt_channel_t channel); + +/** +* @brief Reset RMT TX memory +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_tx_memory_reset(rmt_channel_t channel); + +/** +* @brief Reset RMT RX memory +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_rx_memory_reset(rmt_channel_t channel); + +/** +* @brief Set RMT memory owner. +* @note Setting memroy is only valid for RX channel. +* +* @param channel RMT channel +* @param owner To set when the transmitter or receiver can process the memory of channel. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_memory_owner(rmt_channel_t channel, rmt_mem_owner_t owner); + +/** +* @brief Get RMT memory owner. +* +* @param channel RMT channel +* @param owner Pointer to get memory owner. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_memory_owner(rmt_channel_t channel, rmt_mem_owner_t *owner); + +/** +* @brief Set RMT tx loop mode. +* +* @param channel RMT channel +* @param loop_en Enable RMT transmitter loop sending mode. +* If set true, transmitter will continue sending from the first data +* to the last data in channel over and over again in a loop. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_tx_loop_mode(rmt_channel_t channel, bool loop_en); + +/** +* @brief Get RMT tx loop mode. +* +* @param channel RMT channel +* @param loop_en Pointer to accept RMT transmitter loop sending mode. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_tx_loop_mode(rmt_channel_t channel, bool *loop_en); + +/** +* @brief Set RMT RX filter. +* +* In receive mode, channel will ignore input pulse when the pulse width is smaller than threshold. +* Counted in source clock, not divided counter clock. +* +* @param channel RMT channel +* @param rx_filter_en To enable RMT receiver filter. +* @param thresh Threshold of pulse width for receiver. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_rx_filter(rmt_channel_t channel, bool rx_filter_en, uint8_t thresh); + +/** +* @brief Set RMT source clock +* +* RMT module has two clock sources: +* 1. APB clock which is 80Mhz +* 2. REF tick clock, which would be 1Mhz (not supported in this version). +* +* @param channel RMT channel +* @param base_clk To choose source clock for RMT module. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_source_clk(rmt_channel_t channel, rmt_source_clk_t base_clk); + +/** +* @brief Get RMT source clock +* +* RMT module has two clock sources: +* 1. APB clock which is 80Mhz +* 2. REF tick clock, which would be 1Mhz (not supported in this version). +* +* @param channel RMT channel +* @param src_clk Pointer to accept source clock for RMT module. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_source_clk(rmt_channel_t channel, rmt_source_clk_t *src_clk); + +/** +* @brief Set RMT idle output level for transmitter +* +* @param channel RMT channel +* @param idle_out_en To enable idle level output. +* @param level To set the output signal's level for channel in idle state. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_idle_level(rmt_channel_t channel, bool idle_out_en, rmt_idle_level_t level); + +/** +* @brief Get RMT idle output level for transmitter +* +* @param channel RMT channel +* @param idle_out_en Pointer to accept value of enable idle. +* @param level Pointer to accept value of output signal's level in idle state for specified channel. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_idle_level(rmt_channel_t channel, bool *idle_out_en, rmt_idle_level_t *level); + +/** +* @brief Get RMT status +* +* @param channel RMT channel +* @param status Pointer to accept channel status. +* Please refer to RMT_CHnSTATUS_REG(n=0~7) in `rmt_reg.h` for more details of each field. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_status(rmt_channel_t channel, uint32_t *status); + +/** +* @brief Set RMT RX interrupt enable +* +* @param channel RMT channel +* @param en enable or disable RX interrupt. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_rx_intr_en(rmt_channel_t channel, bool en); + +/** +* @brief Set RMT RX error interrupt enable +* +* @param channel RMT channel +* @param en enable or disable RX err interrupt. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_err_intr_en(rmt_channel_t channel, bool en); + +/** +* @brief Set RMT TX interrupt enable +* +* @param channel RMT channel +* @param en enable or disable TX interrupt. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_tx_intr_en(rmt_channel_t channel, bool en); + +/** +* @brief Set RMT TX threshold event interrupt enable +* +* An interrupt will be triggered when the number of transmitted items reaches the threshold value +* +* @param channel RMT channel +* @param en enable or disable TX event interrupt. +* @param evt_thresh RMT event interrupt threshold value +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_tx_thr_intr_en(rmt_channel_t channel, bool en, uint16_t evt_thresh); + +/** +* @brief Configure the GPIO used by RMT channel +* +* @param channel RMT channel +* @param mode RMT mode, either RMT_MODE_TX or RMT_MODE_RX +* @param gpio_num GPIO number, which is connected with certain RMT signal +* @param invert_signal Invert RMT signal physically by GPIO matrix +* +* @return +* - ESP_ERR_INVALID_ARG Configure RMT GPIO failed because of wrong parameter +* - ESP_OK Configure RMT GPIO successfully +*/ +esp_err_t rmt_set_gpio(rmt_channel_t channel, rmt_mode_t mode, gpio_num_t gpio_num, bool invert_signal); + +/** +* @brief Configure RMT parameters +* +* @param rmt_param RMT parameter struct +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_config(const rmt_config_t *rmt_param); + +/** +* @brief Register RMT interrupt handler, the handler is an ISR. +* +* The handler will be attached to the same CPU core that this function is running on. +* +* @note If you already called rmt_driver_install to use system RMT driver, +* please do not register ISR handler again. +* +* @param fn Interrupt handler function. +* @param arg Parameter for the handler function +* @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) +* ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. +* @param handle If non-zero, a handle to later clean up the ISR gets stored here. +* +* @return +* - ESP_OK Success +* - ESP_ERR_INVALID_ARG Function pointer error. +* - ESP_FAIL System driver installed, can not register ISR handler for RMT +*/ +esp_err_t rmt_isr_register(void (*fn)(void *), void *arg, int intr_alloc_flags, rmt_isr_handle_t *handle); + +/** +* @brief Deregister previously registered RMT interrupt handler +* +* @param handle Handle obtained from rmt_isr_register +* +* @return +* - ESP_OK Success +* - ESP_ERR_INVALID_ARG Handle invalid +*/ +esp_err_t rmt_isr_deregister(rmt_isr_handle_t handle); + +/** +* @brief Fill memory data of channel with given RMT items. +* +* @param channel RMT channel +* @param item Pointer of items. +* @param item_num RMT sending items number. +* @param mem_offset Index offset of memory. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_fill_tx_items(rmt_channel_t channel, const rmt_item32_t *item, uint16_t item_num, uint16_t mem_offset); + +/** +* @brief Initialize RMT driver +* +* @param channel RMT channel +* @param rx_buf_size Size of RMT RX ringbuffer. Can be 0 if the RX ringbuffer is not used. +* @param intr_alloc_flags Flags for the RMT driver interrupt handler. Pass 0 for default flags. See esp_intr_alloc.h for details. +* If ESP_INTR_FLAG_IRAM is used, please do not use the memory allocated from psram when calling rmt_write_items. +* +* @return +* - ESP_ERR_INVALID_STATE Driver is already installed, call rmt_driver_uninstall first. +* - ESP_ERR_NO_MEM Memory allocation failure +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_driver_install(rmt_channel_t channel, size_t rx_buf_size, int intr_alloc_flags); + +/** +* @brief Uninstall RMT driver. +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_driver_uninstall(rmt_channel_t channel); + +/** +* @brief Get the current status of eight channels. +* +* @note Do not call this function if it is possible that `rmt_driver_uninstall` will be called at the same time. +* +* @param[out] channel_status store the current status of each channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter is NULL +* - ESP_OK Success +*/ +esp_err_t rmt_get_channel_status(rmt_channel_status_result_t *channel_status); + +/** +* @brief Get speed of channel's internal counter clock. +* +* @param channel RMT channel +* @param[out] clock_hz counter clock speed, in hz +* +* @return +* - ESP_ERR_INVALID_ARG Parameter is NULL +* - ESP_OK Success +*/ +esp_err_t rmt_get_counter_clock(rmt_channel_t channel, uint32_t *clock_hz); + +/** +* @brief RMT send waveform from rmt_item array. +* +* This API allows user to send waveform with any length. +* +* @param channel RMT channel +* @param rmt_item head point of RMT items array. +* If ESP_INTR_FLAG_IRAM is used, please do not use the memory allocated from psram when calling rmt_write_items. +* @param item_num RMT data item number. +* @param wait_tx_done +* - If set 1, it will block the task and wait for sending done. +* - If set 0, it will not wait and return immediately. +* +* @note +* This function will not copy data, instead, it will point to the original items, +* and send the waveform items. +* If wait_tx_done is set to true, this function will block and will not return until +* all items have been sent out. +* If wait_tx_done is set to false, this function will return immediately, and the driver +* interrupt will continue sending the items. We must make sure the item data will not be +* damaged when the driver is still sending items in driver interrupt. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_write_items(rmt_channel_t channel, const rmt_item32_t *rmt_item, int item_num, bool wait_tx_done); + +/** +* @brief Wait RMT TX finished. +* +* @param channel RMT channel +* @param wait_time Maximum time in ticks to wait for transmission to be complete. If set 0, return immediately with ESP_ERR_TIMEOUT if TX is busy (polling). +* +* @return +* - ESP_OK RMT Tx done successfully +* - ESP_ERR_TIMEOUT Exceeded the 'wait_time' given +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_FAIL Driver not installed +*/ +esp_err_t rmt_wait_tx_done(rmt_channel_t channel, TickType_t wait_time); + +/** +* @brief Get ringbuffer from RMT. +* +* Users can get the RMT RX ringbuffer handle, and process the RX data. +* +* @param channel RMT channel +* @param buf_handle Pointer to buffer handle to accept RX ringbuffer handle. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_get_ringbuf_handle(rmt_channel_t channel, RingbufHandle_t *buf_handle); + +/** +* @brief Init rmt translator and register user callback. +* The callback will convert the raw data that needs to be sent to rmt format. +* If a channel is initialized more than once, tha user callback will be replaced by the later. +* +* @param channel RMT channel . +* @param fn Point to the data conversion function. +* +* @return +* - ESP_FAIL Init fail. +* - ESP_OK Init success. +*/ +esp_err_t rmt_translator_init(rmt_channel_t channel, sample_to_rmt_t fn); + +/** +* @brief Set user context for the translator of specific channel +* +* @param channel RMT channel number +* @param context User context +* +* @return +* - ESP_FAIL Set context fail +* - ESP_OK Set context success +*/ +esp_err_t rmt_translator_set_context(rmt_channel_t channel, void *context); + +/** +* @brief Get the user context set by 'rmt_translator_set_context' +* +* @note This API must be invoked in the RMT translator callback function, +* and the first argument must be the actual parameter 'item_num' you got in that callback function. +* +* @param item_num Address of the memory which contains the number of translated items (It's from driver's internal memroy) +* @param context Returned User context +* +* @return +* - ESP_FAIL Get context fail +* - ESP_OK Get context success +*/ +esp_err_t rmt_translator_get_context(const size_t *item_num, void **context); + +/** +* @brief Translate uint8_t type of data into rmt format and send it out. +* Requires rmt_translator_init to init the translator first. +* +* @param channel RMT channel . +* @param src Pointer to the raw data. +* @param src_size The size of the raw data. +* @param wait_tx_done Set true to wait all data send done. +* +* @return +* - ESP_FAIL Send fail +* - ESP_OK Send success +*/ +esp_err_t rmt_write_sample(rmt_channel_t channel, const uint8_t *src, size_t src_size, bool wait_tx_done); + +/** +* @brief Registers a callback that will be called when transmission ends. +* +* Called by rmt_driver_isr_default in interrupt context. +* +* @note Requires rmt_driver_install to install the default ISR handler. +* +* @param function Function to be called from the default interrupt handler or NULL. +* @param arg Argument which will be provided to the callback when it is called. +* +* @return the previous callback settings (members will be set to NULL if there was none) +*/ +rmt_tx_end_callback_t rmt_register_tx_end_callback(rmt_tx_end_fn_t function, void *arg); + +#if SOC_RMT_SUPPORT_RX_PINGPONG +/** +* @brief Set RMT RX threshold event interrupt enable +* +* An interrupt will be triggered when the number of received items reaches the threshold value +* +* @param channel RMT channel +* @param en enable or disable RX event interrupt. +* @param evt_thresh RMT event interrupt threshold value +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_rx_thr_intr_en(rmt_channel_t channel, bool en, uint16_t evt_thresh); +#endif + +#if SOC_RMT_SUPPORT_TX_SYNCHRO +/** +* @brief Add channel into a synchronous group (channels in the same group can start transaction simultaneously) +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_add_channel_to_group(rmt_channel_t channel); + +/** +* @brief Remove channel out of a group +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_remove_channel_from_group(rmt_channel_t channel); +#endif + +#if SOC_RMT_SUPPORT_TX_LOOP_COUNT +/** + * @brief Set loop count for RMT TX channel + * + * @param channel RMT channel + * @param count loop count + * @return + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_OK Success + */ +esp_err_t rmt_set_tx_loop_count(rmt_channel_t channel, uint32_t count); +#endif + +/** +* @brief Reset RMT TX/RX memory index. +* +* @param channel RMT channel +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_memory_rw_rst(rmt_channel_t channel) +__attribute__((deprecated("use rmt_tx_memory_reset or rmt_rx_memory_reset instead"))); + +/** +* @brief Set mask value to RMT interrupt enable register. +* +* @param mask Bit mask to set to the register +* +*/ +void rmt_set_intr_enable_mask(uint32_t mask) +__attribute__((deprecated("interrupt should be handled by driver"))); + +/** +* @brief Clear mask value to RMT interrupt enable register. +* +* @param mask Bit mask to clear the register +* +*/ +void rmt_clr_intr_enable_mask(uint32_t mask) +__attribute__((deprecated("interrupt should be handled by driver"))); + +/** +* @brief Set RMT pin +* +* @param channel RMT channel +* @param mode TX or RX mode for RMT +* @param gpio_num GPIO number to transmit or receive the signal. +* +* @return +* - ESP_ERR_INVALID_ARG Parameter error +* - ESP_OK Success +*/ +esp_err_t rmt_set_pin(rmt_channel_t channel, rmt_mode_t mode, gpio_num_t gpio_num) +__attribute__((deprecated("use rmt_set_gpio instead"))); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/rtc_cntl.h b/tools/sdk/esp32c3/include/driver/include/driver/rtc_cntl.h new file mode 100644 index 00000000..44fd0150 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/rtc_cntl.h @@ -0,0 +1,56 @@ +// Copyright 2016-2017 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. + +#pragma once + +#include +#include "esp_err.h" +#include "esp_intr_alloc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Register a handler for specific RTC_CNTL interrupts + * + * Multiple handlers can be registered using this function. Whenever an + * RTC interrupt happens, all handlers with matching rtc_intr_mask values + * will be called. + * + * @param handler handler function to call + * @param handler_arg argument to be passed to the handler + * @param rtc_intr_mask combination of RTC_CNTL_*_INT_ENA bits indicating the + * sources to call the handler for + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM not enough memory to allocate handler structure + * - other errors returned by esp_intr_alloc + */ +esp_err_t rtc_isr_register(intr_handler_t handler, void* handler_arg, + uint32_t rtc_intr_mask); +/** + * @brief Deregister the handler previously registered using rtc_isr_register + * @param handler handler function to call (as passed to rtc_isr_register) + * @param handler_arg argument of the handler (as passed to rtc_isr_register) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if a handler matching both handler and + * handler_arg isn't registered + */ +esp_err_t rtc_isr_deregister(intr_handler_t handler, void* handler_arg); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/rtc_io.h b/tools/sdk/esp32c3/include/driver/include/driver/rtc_io.h new file mode 100644 index 00000000..ea887822 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/rtc_io.h @@ -0,0 +1,321 @@ +// Copyright 2015-2016 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. + +#ifndef _DRIVER_RTC_GPIO_H_ +#define _DRIVER_RTC_GPIO_H_ + +#include +#include "esp_err.h" +#include "driver/gpio.h" +#include "soc/soc_caps.h" +#include "soc/rtc_io_periph.h" +#include "hal/rtc_io_types.h" +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Determine if the specified GPIO is a valid RTC GPIO. + * + * @param gpio_num GPIO number + * @return true if GPIO is valid for RTC GPIO use. false otherwise. + */ +static inline bool rtc_gpio_is_valid_gpio(gpio_num_t gpio_num) +{ +#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + return (gpio_num < GPIO_PIN_COUNT && rtc_io_num_map[gpio_num] >= 0); +#else + return false; +#endif +} + +#define RTC_GPIO_IS_VALID_GPIO(gpio_num) rtc_gpio_is_valid_gpio(gpio_num) // Deprecated, use rtc_gpio_is_valid_gpio() + +/** + * @brief Get RTC IO index number by gpio number. + * + * @param gpio_num GPIO number + * @return + * >=0: Index of rtcio. + * -1 : The gpio is not rtcio. + */ +static inline int rtc_io_number_get(gpio_num_t gpio_num) +{ +#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + return rtc_io_num_map[gpio_num]; +#else + return gpio_num; +#endif +} + +#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + +/** + * @brief Init a GPIO as RTC GPIO + * + * This function must be called when initializing a pad for an analog function. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_init(gpio_num_t gpio_num); + +/** + * @brief Init a GPIO as digital GPIO + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_deinit(gpio_num_t gpio_num); + +/** + * @brief Get the RTC IO input level + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - 1 High level + * - 0 Low level + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +uint32_t rtc_gpio_get_level(gpio_num_t gpio_num); + +/** + * @brief Set the RTC IO output level + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * @param level output level + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_set_level(gpio_num_t gpio_num, uint32_t level); + +/** + * @brief RTC GPIO set direction + * + * Configure RTC GPIO direction, such as output only, input only, + * output and input. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * @param mode GPIO direction + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_set_direction(gpio_num_t gpio_num, rtc_gpio_mode_t mode); + +/** + * @brief RTC GPIO set direction in deep sleep mode or disable sleep status (default). + * In some application scenarios, IO needs to have another states during deep sleep. + * + * NOTE: ESP32 support INPUT_ONLY mode. + * ESP32S2 support INPUT_ONLY, OUTPUT_ONLY, INPUT_OUTPUT mode. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * @param mode GPIO direction + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_set_direction_in_sleep(gpio_num_t gpio_num, rtc_gpio_mode_t mode); + +/** + * @brief RTC GPIO pullup enable + * + * This function only works for RTC IOs. In general, call gpio_pullup_en, + * which will work both for normal GPIOs and RTC IOs. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_pullup_en(gpio_num_t gpio_num); + +/** + * @brief RTC GPIO pulldown enable + * + * This function only works for RTC IOs. In general, call gpio_pulldown_en, + * which will work both for normal GPIOs and RTC IOs. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_pulldown_en(gpio_num_t gpio_num); + +/** + * @brief RTC GPIO pullup disable + * + * This function only works for RTC IOs. In general, call gpio_pullup_dis, + * which will work both for normal GPIOs and RTC IOs. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_pullup_dis(gpio_num_t gpio_num); + +/** + * @brief RTC GPIO pulldown disable + * + * This function only works for RTC IOs. In general, call gpio_pulldown_dis, + * which will work both for normal GPIOs and RTC IOs. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_pulldown_dis(gpio_num_t gpio_num); + +/** + * @brief Set RTC GPIO pad drive capability + * + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Drive capability of the pad + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t rtc_gpio_set_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t strength); + +/** + * @brief Get RTC GPIO pad drive capability + * + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Pointer to accept drive capability of the pad + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t rtc_gpio_get_drive_capability(gpio_num_t gpio_num, gpio_drive_cap_t* strength); + +#endif // SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + +#if SOC_RTCIO_HOLD_SUPPORTED + +/** + * @brief Enable hold function on an RTC IO pad + * + * Enabling HOLD function will cause the pad to latch current values of + * input enable, output enable, output value, function, drive strength values. + * This function is useful when going into light or deep sleep mode to prevent + * the pin configuration from changing. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_hold_en(gpio_num_t gpio_num); + +/** + * @brief Disable hold function on an RTC IO pad + * + * Disabling hold function will allow the pad receive the values of + * input enable, output enable, output value, function, drive strength from + * RTC_IO peripheral. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12) + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_hold_dis(gpio_num_t gpio_num); + +/** + * @brief Helper function to disconnect internal circuits from an RTC IO + * This function disables input, output, pullup, pulldown, and enables + * hold feature for an RTC IO. + * Use this function if an RTC IO needs to be disconnected from internal + * circuits in deep sleep, to minimize leakage current. + * + * In particular, for ESP32-WROVER module, call + * rtc_gpio_isolate(GPIO_NUM_12) before entering deep sleep, to reduce + * deep sleep current. + * + * @param gpio_num GPIO number (e.g. GPIO_NUM_12). + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if GPIO is not an RTC IO + */ +esp_err_t rtc_gpio_isolate(gpio_num_t gpio_num); + +/** + * @brief Enable force hold signal for all RTC IOs + * + * Each RTC pad has a "force hold" input signal from the RTC controller. + * If this signal is set, pad latches current values of input enable, + * function, output enable, and other signals which come from the RTC mux. + * Force hold signal is enabled before going into deep sleep for pins which + * are used for EXT1 wakeup. + */ +esp_err_t rtc_gpio_force_hold_all(void); + +/** + * @brief Disable force hold signal for all RTC IOs + */ +esp_err_t rtc_gpio_force_hold_dis_all(void); + +#endif // SOC_RTCIO_HOLD_SUPPORTED + +#if SOC_RTCIO_WAKE_SUPPORTED + +/** + * @brief Enable wakeup from sleep mode using specific GPIO + * @param gpio_num GPIO number + * @param intr_type Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level + * (GPIO_INTR_LOW_LEVEL) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not + * one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL. + */ +esp_err_t rtc_gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type); + +/** + * @brief Disable wakeup from sleep mode using specific GPIO + * @param gpio_num GPIO number + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO + */ +esp_err_t rtc_gpio_wakeup_disable(gpio_num_t gpio_num); + +#endif // SOC_RTCIO_WAKE_SUPPORTED + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sdio_slave.h b/tools/sdk/esp32c3/include/driver/include/driver/sdio_slave.h new file mode 100644 index 00000000..c1bc1fb7 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sdio_slave.h @@ -0,0 +1,277 @@ +// Copyright 2015-2018 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. + +#ifndef _DRIVER_SDIO_SLAVE_H_ +#define _DRIVER_SDIO_SLAVE_H_ + +#include "freertos/FreeRTOS.h" +#include "esp_err.h" +#include "sys/queue.h" + +#include "hal/sdio_slave_types.h" +#include "soc/sdio_slave_periph.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SDIO_SLAVE_RECV_MAX_BUFFER (4096-4) + +typedef void(*sdio_event_cb_t)(uint8_t event); + + +/// Configuration of SDIO slave +typedef struct { + sdio_slave_timing_t timing; ///< timing of sdio_slave. see `sdio_slave_timing_t`. + sdio_slave_sending_mode_t sending_mode; ///< mode of sdio_slave. `SDIO_SLAVE_MODE_STREAM` if the data needs to be sent as much as possible; `SDIO_SLAVE_MODE_PACKET` if the data should be sent in packets. + int send_queue_size; ///< max buffers that can be queued before sending. + size_t recv_buffer_size; + ///< If buffer_size is too small, it costs more CPU time to handle larger number of buffers. + ///< If buffer_size is too large, the space larger than the transaction length is left blank but still counts a buffer, and the buffers are easily run out. + ///< Should be set according to length of data really transferred. + ///< All data that do not fully fill a buffer is still counted as one buffer. E.g. 10 bytes data costs 2 buffers if the size is 8 bytes per buffer. + ///< Buffer size of the slave pre-defined between host and slave before communication. All receive buffer given to the driver should be larger than this. + sdio_event_cb_t event_cb; ///< when the host interrupts slave, this callback will be called with interrupt number (0-7). + uint32_t flags; ///< Features to be enabled for the slave, combinations of ``SDIO_SLAVE_FLAG_*``. +#define SDIO_SLAVE_FLAG_DAT2_DISABLED BIT(0) /**< It is required by the SD specification that all 4 data + lines should be used and pulled up even in 1-bit mode or SPI mode. However, as a feature, the user can specify + this flag to make use of DAT2 pin in 1-bit mode. Note that the host cannot read CCCR registers to know we don't + support 4-bit mode anymore, please do this at your own risk. + */ +#define SDIO_SLAVE_FLAG_HOST_INTR_DISABLED BIT(1) /**< The DAT1 line is used as the interrupt line in SDIO + protocol. However, as a feature, the user can specify this flag to make use of DAT1 pin of the slave in 1-bit + mode. Note that the host has to do polling to the interrupt registers to know whether there are interrupts from + the slave. And it cannot read CCCR registers to know we don't support 4-bit mode anymore, please do this at + your own risk. + */ +#define SDIO_SLAVE_FLAG_INTERNAL_PULLUP BIT(2) /**< Enable internal pullups for enabled pins. It is required + by the SD specification that all the 4 data lines should be pulled up even in 1-bit mode or SPI mode. Note that + the internal pull-ups are not sufficient for stable communication, please do connect external pull-ups on the + bus. This is only for example and debug use. + */ +} sdio_slave_config_t; + +/** Handle of a receive buffer, register a handle by calling ``sdio_slave_recv_register_buf``. Use the handle to load the buffer to the + * driver, or call ``sdio_slave_recv_unregister_buf`` if it is no longer used. + */ +typedef void *sdio_slave_buf_handle_t; + +/** Initialize the sdio slave driver + * + * @param config Configuration of the sdio slave driver. + * + * @return + * - ESP_ERR_NOT_FOUND if no free interrupt found. + * - ESP_ERR_INVALID_STATE if already initialized. + * - ESP_ERR_NO_MEM if fail due to memory allocation failed. + * - ESP_OK if success + */ +esp_err_t sdio_slave_initialize(sdio_slave_config_t *config); + +/** De-initialize the sdio slave driver to release the resources. + */ +void sdio_slave_deinit(void); + +/** Start hardware for sending and receiving, as well as set the IOREADY1 to 1. + * + * @note The driver will continue sending from previous data and PKT_LEN counting, keep data received as well as start receiving from current TOKEN1 counting. + * See ``sdio_slave_reset``. + * + * @return + * - ESP_ERR_INVALID_STATE if already started. + * - ESP_OK otherwise. + */ +esp_err_t sdio_slave_start(void); + +/** Stop hardware from sending and receiving, also set IOREADY1 to 0. + * + * @note this will not clear the data already in the driver, and also not reset the PKT_LEN and TOKEN1 counting. Call ``sdio_slave_reset`` to do that. + */ +void sdio_slave_stop(void); + +/** Clear the data still in the driver, as well as reset the PKT_LEN and TOKEN1 counting. + * + * @return always return ESP_OK. + */ +esp_err_t sdio_slave_reset(void); + +/*--------------------------------------------------------------------------- + * Receive + *--------------------------------------------------------------------------*/ +/** Register buffer used for receiving. All buffers should be registered before used, and then can be used (again) in the driver by the handle returned. + * + * @param start The start address of the buffer. + * + * @note The driver will use and only use the amount of space specified in the `recv_buffer_size` member set in the `sdio_slave_config_t`. + * All buffers should be larger than that. The buffer is used by the DMA, so it should be DMA capable and 32-bit aligned. + * + * @return The buffer handle if success, otherwise NULL. + */ +sdio_slave_buf_handle_t sdio_slave_recv_register_buf(uint8_t *start); + +/** Unregister buffer from driver, and free the space used by the descriptor pointing to the buffer. + * + * @param handle Handle to the buffer to release. + * + * @return ESP_OK if success, ESP_ERR_INVALID_ARG if the handle is NULL or the buffer is being used. + */ +esp_err_t sdio_slave_recv_unregister_buf(sdio_slave_buf_handle_t handle); + +/** Load buffer to the queue waiting to receive data. The driver takes ownership of the buffer until the buffer is returned by + * ``sdio_slave_send_get_finished`` after the transaction is finished. + * + * @param handle Handle to the buffer ready to receive data. + * + * @return + * - ESP_ERR_INVALID_ARG if invalid handle or the buffer is already in the queue. Only after the buffer is returened by + * ``sdio_slave_recv`` can you load it again. + * - ESP_OK if success + */ +esp_err_t sdio_slave_recv_load_buf(sdio_slave_buf_handle_t handle); + +/** Get received data if exist. The driver returns the ownership of the buffer to the app. + * + * @param handle_ret Handle to the buffer holding received data. Use this handle in ``sdio_slave_recv_load_buf`` to receive in the same buffer again. + * @param[out] out_addr Output of the start address, set to NULL if not needed. + * @param[out] out_len Actual length of the data in the buffer, set to NULL if not needed. + * @param wait Time to wait before data received. + * + * @note Call ``sdio_slave_load_buf`` with the handle to re-load the buffer onto the link list, and receive with the same buffer again. + * The address and length of the buffer got here is the same as got from `sdio_slave_get_buffer`. + * + * @return + * - ESP_ERR_INVALID_ARG if handle_ret is NULL + * - ESP_ERR_TIMEOUT if timeout before receiving new data + * - ESP_OK if success + */ +esp_err_t sdio_slave_recv(sdio_slave_buf_handle_t* handle_ret, uint8_t **out_addr, size_t *out_len, TickType_t wait); + +/** Retrieve the buffer corresponding to a handle. + * + * @param handle Handle to get the buffer. + * @param len_o Output of buffer length + * + * @return buffer address if success, otherwise NULL. + */ +uint8_t* sdio_slave_recv_get_buf(sdio_slave_buf_handle_t handle, size_t *len_o); + +/*--------------------------------------------------------------------------- + * Send + *--------------------------------------------------------------------------*/ +/** Put a new sending transfer into the send queue. The driver takes ownership of the buffer until the buffer is returned by + * ``sdio_slave_send_get_finished`` after the transaction is finished. + * + * @param addr Address for data to be sent. The buffer should be DMA capable and 32-bit aligned. + * @param len Length of the data, should not be longer than 4092 bytes (may support longer in the future). + * @param arg Argument to returned in ``sdio_slave_send_get_finished``. The argument can be used to indicate which transaction is done, + * or as a parameter for a callback. Set to NULL if not needed. + * @param wait Time to wait if the buffer is full. + * + * @return + * - ESP_ERR_INVALID_ARG if the length is not greater than 0. + * - ESP_ERR_TIMEOUT if the queue is still full until timeout. + * - ESP_OK if success. + */ +esp_err_t sdio_slave_send_queue(uint8_t* addr, size_t len, void* arg, TickType_t wait); + +/** Return the ownership of a finished transaction. + * @param out_arg Argument of the finished transaction. Set to NULL if unused. + * @param wait Time to wait if there's no finished sending transaction. + * + * @return ESP_ERR_TIMEOUT if no transaction finished, or ESP_OK if succeed. + */ +esp_err_t sdio_slave_send_get_finished(void** out_arg, TickType_t wait); + +/** Start a new sending transfer, and wait for it (blocked) to be finished. + * + * @param addr Start address of the buffer to send + * @param len Length of buffer to send. + * + * @return + * - ESP_ERR_INVALID_ARG if the length of descriptor is not greater than 0. + * - ESP_ERR_TIMEOUT if the queue is full or host do not start a transfer before timeout. + * - ESP_OK if success. + */ +esp_err_t sdio_slave_transmit(uint8_t* addr, size_t len); + +/*--------------------------------------------------------------------------- + * Host + *--------------------------------------------------------------------------*/ +/** Read the spi slave register shared with host. + * + * @param pos register address, 0-27 or 32-63. + * + * @note register 28 to 31 are reserved for interrupt vector. + * + * @return value of the register. + */ +uint8_t sdio_slave_read_reg(int pos); + +/** Write the spi slave register shared with host. + * + * @param pos register address, 0-11, 14-15, 18-19, 24-27 and 32-63, other address are reserved. + * @param reg the value to write. + * + * @note register 29 and 31 are used for interrupt vector. + * + * @return ESP_ERR_INVALID_ARG if address wrong, otherwise ESP_OK. + */ +esp_err_t sdio_slave_write_reg(int pos, uint8_t reg); + +/** Get the interrupt enable for host. + * + * @return the interrupt mask. + */ +sdio_slave_hostint_t sdio_slave_get_host_intena(void); + +/** Set the interrupt enable for host. + * + * @param mask Enable mask for host interrupt. + */ +void sdio_slave_set_host_intena(sdio_slave_hostint_t mask); + +/** Interrupt the host by general purpose interrupt. + * + * @param pos Interrupt num, 0-7. + * + * @return + * - ESP_ERR_INVALID_ARG if interrupt num error + * - ESP_OK otherwise + */ +esp_err_t sdio_slave_send_host_int(uint8_t pos); + +/** Clear general purpose interrupt to host. + * + * @param mask Interrupt bits to clear, by bit mask. + */ +void sdio_slave_clear_host_int(sdio_slave_hostint_t mask); + +/** Wait for general purpose interrupt from host. + * + * @param pos Interrupt source number to wait for. + * is set. + * @param wait Time to wait before interrupt triggered. + * + * @note this clears the interrupt at the same time. + * + * @return ESP_OK if success, ESP_ERR_TIMEOUT if timeout. + */ +esp_err_t sdio_slave_wait_int(int pos, TickType_t wait); + + +#ifdef __cplusplus +} +#endif + +#endif /*_DRIVER_SDIO_SLAVE_H */ diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_defs.h b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_defs.h new file mode 100644 index 00000000..4f1e6ddc --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_defs.h @@ -0,0 +1,484 @@ +/* + * Copyright (c) 2006 Uwe Stuehler + * Adaptations to ESP-IDF Copyright (c) 2016 Espressif Systems (Shanghai) PTE LTD + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef _SDMMC_DEFS_H_ +#define _SDMMC_DEFS_H_ + +#include +#include + +/* MMC commands */ /* response type */ +#define MMC_GO_IDLE_STATE 0 /* R0 */ +#define MMC_SEND_OP_COND 1 /* R3 */ +#define MMC_ALL_SEND_CID 2 /* R2 */ +#define MMC_SET_RELATIVE_ADDR 3 /* R1 */ +#define MMC_SWITCH 6 /* R1B */ +#define MMC_SELECT_CARD 7 /* R1 */ +#define MMC_SEND_EXT_CSD 8 /* R1 */ +#define MMC_SEND_CSD 9 /* R2 */ +#define MMC_SEND_CID 10 /* R1 */ +#define MMC_READ_DAT_UNTIL_STOP 11 /* R1 */ +#define MMC_STOP_TRANSMISSION 12 /* R1B */ +#define MMC_SEND_STATUS 13 /* R1 */ +#define MMC_SET_BLOCKLEN 16 /* R1 */ +#define MMC_READ_BLOCK_SINGLE 17 /* R1 */ +#define MMC_READ_BLOCK_MULTIPLE 18 /* R1 */ +#define MMC_WRITE_DAT_UNTIL_STOP 20 /* R1 */ +#define MMC_SET_BLOCK_COUNT 23 /* R1 */ +#define MMC_WRITE_BLOCK_SINGLE 24 /* R1 */ +#define MMC_WRITE_BLOCK_MULTIPLE 25 /* R1 */ +#define MMC_APP_CMD 55 /* R1 */ + +/* SD commands */ /* response type */ +#define SD_SEND_RELATIVE_ADDR 3 /* R6 */ +#define SD_SEND_SWITCH_FUNC 6 /* R1 */ +#define SD_SEND_IF_COND 8 /* R7 */ +#define SD_READ_OCR 58 /* R3 */ +#define SD_CRC_ON_OFF 59 /* R1 */ + +/* SD application commands */ /* response type */ +#define SD_APP_SET_BUS_WIDTH 6 /* R1 */ +#define SD_APP_SD_STATUS 13 /* R2 */ +#define SD_APP_OP_COND 41 /* R3 */ +#define SD_APP_SEND_SCR 51 /* R1 */ + +/* SD IO commands */ +#define SD_IO_SEND_OP_COND 5 /* R4 */ +#define SD_IO_RW_DIRECT 52 /* R5 */ +#define SD_IO_RW_EXTENDED 53 /* R5 */ + + +/* OCR bits */ +#define MMC_OCR_MEM_READY (1<<31) /* memory power-up status bit */ +#define MMC_OCR_ACCESS_MODE_MASK 0x60000000 /* bits 30:29 */ +#define MMC_OCR_SECTOR_MODE (1<<30) +#define MMC_OCR_BYTE_MODE (1<<29) +#define MMC_OCR_3_5V_3_6V (1<<23) +#define MMC_OCR_3_4V_3_5V (1<<22) +#define MMC_OCR_3_3V_3_4V (1<<21) +#define MMC_OCR_3_2V_3_3V (1<<20) +#define MMC_OCR_3_1V_3_2V (1<<19) +#define MMC_OCR_3_0V_3_1V (1<<18) +#define MMC_OCR_2_9V_3_0V (1<<17) +#define MMC_OCR_2_8V_2_9V (1<<16) +#define MMC_OCR_2_7V_2_8V (1<<15) +#define MMC_OCR_2_6V_2_7V (1<<14) +#define MMC_OCR_2_5V_2_6V (1<<13) +#define MMC_OCR_2_4V_2_5V (1<<12) +#define MMC_OCR_2_3V_2_4V (1<<11) +#define MMC_OCR_2_2V_2_3V (1<<10) +#define MMC_OCR_2_1V_2_2V (1<<9) +#define MMC_OCR_2_0V_2_1V (1<<8) +#define MMC_OCR_1_65V_1_95V (1<<7) + +#define SD_OCR_SDHC_CAP (1<<30) +#define SD_OCR_VOL_MASK 0xFF8000 /* bits 23:15 */ + +/* SD mode R1 response type bits */ +#define MMC_R1_READY_FOR_DATA (1<<8) /* ready for next transfer */ +#define MMC_R1_APP_CMD (1<<5) /* app. commands supported */ +#define MMC_R1_SWITCH_ERROR (1<<7) /* switch command did not succeed */ + +/* SPI mode R1 response type bits */ +#define SD_SPI_R1_IDLE_STATE (1<<0) +#define SD_SPI_R1_ERASE_RST (1<<1) +#define SD_SPI_R1_ILLEGAL_CMD (1<<2) +#define SD_SPI_R1_CMD_CRC_ERR (1<<3) +#define SD_SPI_R1_ERASE_SEQ_ERR (1<<4) +#define SD_SPI_R1_ADDR_ERR (1<<5) +#define SD_SPI_R1_PARAM_ERR (1<<6) +#define SD_SPI_R1_NO_RESPONSE (1<<7) + +#define SDIO_R1_FUNC_NUM_ERR (1<<4) + +/* 48-bit response decoding (32 bits w/o CRC) */ +#define MMC_R1(resp) ((resp)[0]) +#define MMC_R3(resp) ((resp)[0]) +#define MMC_R4(resp) ((resp)[0]) +#define MMC_R5(resp) ((resp)[0]) +#define SD_R6(resp) ((resp)[0]) +#define MMC_R1_CURRENT_STATE(resp) (((resp)[0] >> 9) & 0xf) + +/* SPI mode response decoding */ +#define SD_SPI_R1(resp) ((resp)[0] & 0xff) +#define SD_SPI_R2(resp) ((resp)[0] & 0xffff) +#define SD_SPI_R3(resp) ((resp)[0]) +#define SD_SPI_R7(resp) ((resp)[0]) + +/* SPI mode data response decoding */ +#define SD_SPI_DATA_RSP_VALID(resp_byte) (((resp_byte)&0x11)==0x1) +#define SD_SPI_DATA_RSP(resp_byte) (((resp_byte)>>1)&0x7) +#define SD_SPI_DATA_ACCEPTED 0x2 +#define SD_SPI_DATA_CRC_ERROR 0x5 +#define SD_SPI_DATA_WR_ERROR 0x6 + +/* RCA argument and response */ +#define MMC_ARG_RCA(rca) ((rca) << 16) +#define SD_R6_RCA(resp) (SD_R6((resp)) >> 16) + +/* bus width argument */ +#define SD_ARG_BUS_WIDTH_1 0 +#define SD_ARG_BUS_WIDTH_4 2 + +/* EXT_CSD fields */ +#define EXT_CSD_BUS_WIDTH 183 /* WO */ +#define EXT_CSD_HS_TIMING 185 /* R/W */ +#define EXT_CSD_REV 192 /* RO */ +#define EXT_CSD_STRUCTURE 194 /* RO */ +#define EXT_CSD_CARD_TYPE 196 /* RO */ +#define EXT_CSD_SEC_COUNT 212 /* RO */ +#define EXT_CSD_PWR_CL_26_360 203 /* RO */ +#define EXT_CSD_PWR_CL_52_360 202 /* RO */ +#define EXT_CSD_PWR_CL_26_195 201 /* RO */ +#define EXT_CSD_PWR_CL_52_195 200 /* RO */ +#define EXT_CSD_POWER_CLASS 187 /* R/W */ +#define EXT_CSD_CMD_SET 191 /* R/W */ +#define EXT_CSD_S_CMD_SET 504 /* RO */ + +/* EXT_CSD field definitions */ +#define EXT_CSD_CMD_SET_NORMAL (1U << 0) +#define EXT_CSD_CMD_SET_SECURE (1U << 1) +#define EXT_CSD_CMD_SET_CPSECURE (1U << 2) + +/* EXT_CSD_HS_TIMING */ +#define EXT_CSD_HS_TIMING_BC 0 +#define EXT_CSD_HS_TIMING_HS 1 +#define EXT_CSD_HS_TIMING_HS200 2 +#define EXT_CSD_HS_TIMING_HS400 3 + +/* EXT_CSD_BUS_WIDTH */ +#define EXT_CSD_BUS_WIDTH_1 0 +#define EXT_CSD_BUS_WIDTH_4 1 +#define EXT_CSD_BUS_WIDTH_8 2 +#define EXT_CSD_BUS_WIDTH_4_DDR 5 +#define EXT_CSD_BUS_WIDTH_8_DDR 6 + +/* EXT_CSD_CARD_TYPE */ +/* The only currently valid values for this field are 0x01, 0x03, 0x07, + * 0x0B and 0x0F. */ +#define EXT_CSD_CARD_TYPE_F_26M (1 << 0) /* SDR at "rated voltages */ +#define EXT_CSD_CARD_TYPE_F_52M (1 << 1) /* SDR at "rated voltages */ +#define EXT_CSD_CARD_TYPE_F_52M_1_8V (1 << 2) /* DDR, 1.8V or 3.3V I/O */ +#define EXT_CSD_CARD_TYPE_F_52M_1_2V (1 << 3) /* DDR, 1.2V I/O */ +#define EXT_CSD_CARD_TYPE_26M 0x01 +#define EXT_CSD_CARD_TYPE_52M 0x03 +#define EXT_CSD_CARD_TYPE_52M_V18 0x07 +#define EXT_CSD_CARD_TYPE_52M_V12 0x0b +#define EXT_CSD_CARD_TYPE_52M_V12_18 0x0f + +/* EXT_CSD MMC */ +#define EXT_CSD_MMC_SIZE 512 + +/* MMC_SWITCH access mode */ +#define MMC_SWITCH_MODE_CMD_SET 0x00 /* Change the command set */ +#define MMC_SWITCH_MODE_SET_BITS 0x01 /* Set bits in value */ +#define MMC_SWITCH_MODE_CLEAR_BITS 0x02 /* Clear bits in value */ +#define MMC_SWITCH_MODE_WRITE_BYTE 0x03 /* Set target to value */ + +/* MMC R2 response (CSD) */ +#define MMC_CSD_CSDVER(resp) MMC_RSP_BITS((resp), 126, 2) +#define MMC_CSD_CSDVER_1_0 1 +#define MMC_CSD_CSDVER_2_0 2 +#define MMC_CSD_CSDVER_EXT_CSD 3 +#define MMC_CSD_MMCVER(resp) MMC_RSP_BITS((resp), 122, 4) +#define MMC_CSD_MMCVER_1_0 0 /* MMC 1.0 - 1.2 */ +#define MMC_CSD_MMCVER_1_4 1 /* MMC 1.4 */ +#define MMC_CSD_MMCVER_2_0 2 /* MMC 2.0 - 2.2 */ +#define MMC_CSD_MMCVER_3_1 3 /* MMC 3.1 - 3.3 */ +#define MMC_CSD_MMCVER_4_0 4 /* MMC 4 */ +#define MMC_CSD_READ_BL_LEN(resp) MMC_RSP_BITS((resp), 80, 4) +#define MMC_CSD_C_SIZE(resp) MMC_RSP_BITS((resp), 62, 12) +#define MMC_CSD_CAPACITY(resp) ((MMC_CSD_C_SIZE((resp))+1) << \ + (MMC_CSD_C_SIZE_MULT((resp))+2)) +#define MMC_CSD_C_SIZE_MULT(resp) MMC_RSP_BITS((resp), 47, 3) + +/* MMC v1 R2 response (CID) */ +#define MMC_CID_MID_V1(resp) MMC_RSP_BITS((resp), 104, 24) +#define MMC_CID_PNM_V1_CPY(resp, pnm) \ + do { \ + (pnm)[0] = MMC_RSP_BITS((resp), 96, 8); \ + (pnm)[1] = MMC_RSP_BITS((resp), 88, 8); \ + (pnm)[2] = MMC_RSP_BITS((resp), 80, 8); \ + (pnm)[3] = MMC_RSP_BITS((resp), 72, 8); \ + (pnm)[4] = MMC_RSP_BITS((resp), 64, 8); \ + (pnm)[5] = MMC_RSP_BITS((resp), 56, 8); \ + (pnm)[6] = MMC_RSP_BITS((resp), 48, 8); \ + (pnm)[7] = '\0'; \ + } while (0) +#define MMC_CID_REV_V1(resp) MMC_RSP_BITS((resp), 40, 8) +#define MMC_CID_PSN_V1(resp) MMC_RSP_BITS((resp), 16, 24) +#define MMC_CID_MDT_V1(resp) MMC_RSP_BITS((resp), 8, 8) + +/* MMC v2 R2 response (CID) */ +#define MMC_CID_MID_V2(resp) MMC_RSP_BITS((resp), 120, 8) +#define MMC_CID_OID_V2(resp) MMC_RSP_BITS((resp), 104, 16) +#define MMC_CID_PNM_V2_CPY(resp, pnm) \ + do { \ + (pnm)[0] = MMC_RSP_BITS((resp), 96, 8); \ + (pnm)[1] = MMC_RSP_BITS((resp), 88, 8); \ + (pnm)[2] = MMC_RSP_BITS((resp), 80, 8); \ + (pnm)[3] = MMC_RSP_BITS((resp), 72, 8); \ + (pnm)[4] = MMC_RSP_BITS((resp), 64, 8); \ + (pnm)[5] = MMC_RSP_BITS((resp), 56, 8); \ + (pnm)[6] = '\0'; \ + } while (0) +#define MMC_CID_PSN_V2(resp) MMC_RSP_BITS((resp), 16, 32) + +/* SD R2 response (CSD) */ +#define SD_CSD_CSDVER(resp) MMC_RSP_BITS((resp), 126, 2) +#define SD_CSD_CSDVER_1_0 0 +#define SD_CSD_CSDVER_2_0 1 +#define SD_CSD_TAAC(resp) MMC_RSP_BITS((resp), 112, 8) +#define SD_CSD_TAAC_1_5_MSEC 0x26 +#define SD_CSD_NSAC(resp) MMC_RSP_BITS((resp), 104, 8) +#define SD_CSD_SPEED(resp) MMC_RSP_BITS((resp), 96, 8) +#define SD_CSD_SPEED_25_MHZ 0x32 +#define SD_CSD_SPEED_50_MHZ 0x5a +#define SD_CSD_CCC(resp) MMC_RSP_BITS((resp), 84, 12) +#define SD_CSD_CCC_BASIC (1 << 0) /* basic */ +#define SD_CSD_CCC_BR (1 << 2) /* block read */ +#define SD_CSD_CCC_BW (1 << 4) /* block write */ +#define SD_CSD_CCC_ERASE (1 << 5) /* erase */ +#define SD_CSD_CCC_WP (1 << 6) /* write protection */ +#define SD_CSD_CCC_LC (1 << 7) /* lock card */ +#define SD_CSD_CCC_AS (1 << 8) /*application specific*/ +#define SD_CSD_CCC_IOM (1 << 9) /* I/O mode */ +#define SD_CSD_CCC_SWITCH (1 << 10) /* switch */ +#define SD_CSD_READ_BL_LEN(resp) MMC_RSP_BITS((resp), 80, 4) +#define SD_CSD_READ_BL_PARTIAL(resp) MMC_RSP_BITS((resp), 79, 1) +#define SD_CSD_WRITE_BLK_MISALIGN(resp) MMC_RSP_BITS((resp), 78, 1) +#define SD_CSD_READ_BLK_MISALIGN(resp) MMC_RSP_BITS((resp), 77, 1) +#define SD_CSD_DSR_IMP(resp) MMC_RSP_BITS((resp), 76, 1) +#define SD_CSD_C_SIZE(resp) MMC_RSP_BITS((resp), 62, 12) +#define SD_CSD_CAPACITY(resp) ((SD_CSD_C_SIZE((resp))+1) << \ + (SD_CSD_C_SIZE_MULT((resp))+2)) +#define SD_CSD_V2_C_SIZE(resp) MMC_RSP_BITS((resp), 48, 22) +#define SD_CSD_V2_CAPACITY(resp) ((SD_CSD_V2_C_SIZE((resp))+1) << 10) +#define SD_CSD_V2_BL_LEN 0x9 /* 512 */ +#define SD_CSD_VDD_R_CURR_MIN(resp) MMC_RSP_BITS((resp), 59, 3) +#define SD_CSD_VDD_R_CURR_MAX(resp) MMC_RSP_BITS((resp), 56, 3) +#define SD_CSD_VDD_W_CURR_MIN(resp) MMC_RSP_BITS((resp), 53, 3) +#define SD_CSD_VDD_W_CURR_MAX(resp) MMC_RSP_BITS((resp), 50, 3) +#define SD_CSD_VDD_RW_CURR_100mA 0x7 +#define SD_CSD_VDD_RW_CURR_80mA 0x6 +#define SD_CSD_C_SIZE_MULT(resp) MMC_RSP_BITS((resp), 47, 3) +#define SD_CSD_ERASE_BLK_EN(resp) MMC_RSP_BITS((resp), 46, 1) +#define SD_CSD_SECTOR_SIZE(resp) MMC_RSP_BITS((resp), 39, 7) /* +1 */ +#define SD_CSD_WP_GRP_SIZE(resp) MMC_RSP_BITS((resp), 32, 7) /* +1 */ +#define SD_CSD_WP_GRP_ENABLE(resp) MMC_RSP_BITS((resp), 31, 1) +#define SD_CSD_R2W_FACTOR(resp) MMC_RSP_BITS((resp), 26, 3) +#define SD_CSD_WRITE_BL_LEN(resp) MMC_RSP_BITS((resp), 22, 4) +#define SD_CSD_RW_BL_LEN_2G 0xa +#define SD_CSD_RW_BL_LEN_1G 0x9 +#define SD_CSD_WRITE_BL_PARTIAL(resp) MMC_RSP_BITS((resp), 21, 1) +#define SD_CSD_FILE_FORMAT_GRP(resp) MMC_RSP_BITS((resp), 15, 1) +#define SD_CSD_COPY(resp) MMC_RSP_BITS((resp), 14, 1) +#define SD_CSD_PERM_WRITE_PROTECT(resp) MMC_RSP_BITS((resp), 13, 1) +#define SD_CSD_TMP_WRITE_PROTECT(resp) MMC_RSP_BITS((resp), 12, 1) +#define SD_CSD_FILE_FORMAT(resp) MMC_RSP_BITS((resp), 10, 2) + +/* SD R2 response (CID) */ +#define SD_CID_MID(resp) MMC_RSP_BITS((resp), 120, 8) +#define SD_CID_OID(resp) MMC_RSP_BITS((resp), 104, 16) +#define SD_CID_PNM_CPY(resp, pnm) \ + do { \ + (pnm)[0] = MMC_RSP_BITS((resp), 96, 8); \ + (pnm)[1] = MMC_RSP_BITS((resp), 88, 8); \ + (pnm)[2] = MMC_RSP_BITS((resp), 80, 8); \ + (pnm)[3] = MMC_RSP_BITS((resp), 72, 8); \ + (pnm)[4] = MMC_RSP_BITS((resp), 64, 8); \ + (pnm)[5] = '\0'; \ + } while (0) +#define SD_CID_REV(resp) MMC_RSP_BITS((resp), 56, 8) +#define SD_CID_PSN(resp) MMC_RSP_BITS((resp), 24, 32) +#define SD_CID_MDT(resp) MMC_RSP_BITS((resp), 8, 12) + +/* SCR (SD Configuration Register) */ +#define SCR_STRUCTURE(scr) MMC_RSP_BITS((scr), 60, 4) +#define SCR_STRUCTURE_VER_1_0 0 /* Version 1.0 */ +#define SCR_SD_SPEC(scr) MMC_RSP_BITS((scr), 56, 4) +#define SCR_SD_SPEC_VER_1_0 0 /* Version 1.0 and 1.01 */ +#define SCR_SD_SPEC_VER_1_10 1 /* Version 1.10 */ +#define SCR_SD_SPEC_VER_2 2 /* Version 2.00 or Version 3.0X */ +#define SCR_DATA_STAT_AFTER_ERASE(scr) MMC_RSP_BITS((scr), 55, 1) +#define SCR_SD_SECURITY(scr) MMC_RSP_BITS((scr), 52, 3) +#define SCR_SD_SECURITY_NONE 0 /* no security */ +#define SCR_SD_SECURITY_1_0 1 /* security protocol 1.0 */ +#define SCR_SD_SECURITY_1_0_2 2 /* security protocol 1.0 */ +#define SCR_SD_BUS_WIDTHS(scr) MMC_RSP_BITS((scr), 48, 4) +#define SCR_SD_BUS_WIDTHS_1BIT (1 << 0) /* 1bit (DAT0) */ +#define SCR_SD_BUS_WIDTHS_4BIT (1 << 2) /* 4bit (DAT0-3) */ +#define SCR_SD_SPEC3(scr) MMC_RSP_BITS((scr), 47, 1) +#define SCR_EX_SECURITY(scr) MMC_RSP_BITS((scr), 43, 4) +#define SCR_SD_SPEC4(scr) MMC_RSP_BITS((scr), 42, 1) +#define SCR_RESERVED(scr) MMC_RSP_BITS((scr), 34, 8) +#define SCR_CMD_SUPPORT_CMD23(scr) MMC_RSP_BITS((scr), 33, 1) +#define SCR_CMD_SUPPORT_CMD20(scr) MMC_RSP_BITS((scr), 32, 1) +#define SCR_RESERVED2(scr) MMC_RSP_BITS((scr), 0, 32) + +/* Max supply current in SWITCH_FUNC response (in mA) */ +#define SD_SFUNC_I_MAX(status) (MMC_RSP_BITS((uint32_t *)(status), 496, 16)) + +/* Supported flags in SWITCH_FUNC response */ +#define SD_SFUNC_SUPPORTED(status, group) \ + (MMC_RSP_BITS((uint32_t *)(status), 400 + (group - 1) * 16, 16)) + +/* Selected function in SWITCH_FUNC response */ +#define SD_SFUNC_SELECTED(status, group) \ + (MMC_RSP_BITS((uint32_t *)(status), 376 + (group - 1) * 4, 4)) + +/* Busy flags in SWITCH_FUNC response */ +#define SD_SFUNC_BUSY(status, group) \ + (MMC_RSP_BITS((uint32_t *)(status), 272 + (group - 1) * 16, 16)) + +/* Version of SWITCH_FUNC response */ +#define SD_SFUNC_VER(status) (MMC_RSP_BITS((uint32_t *)(status), 368, 8)) + +#define SD_SFUNC_GROUP_MAX 6 +#define SD_SFUNC_FUNC_MAX 15 + +#define SD_ACCESS_MODE 1 /* Function group 1, Access Mode */ + +#define SD_ACCESS_MODE_SDR12 0 /* 25 MHz clock */ +#define SD_ACCESS_MODE_SDR25 1 /* 50 MHz clock */ +#define SD_ACCESS_MODE_SDR50 2 /* UHS-I, 100 MHz clock */ +#define SD_ACCESS_MODE_SDR104 3 /* UHS-I, 208 MHz clock */ +#define SD_ACCESS_MODE_DDR50 4 /* UHS-I, 50 MHz clock, DDR */ + +/** + * @brief Extract up to 32 sequential bits from an array of 32-bit words + * + * Bits within the word are numbered in the increasing order from LSB to MSB. + * + * As an example, consider 2 32-bit words: + * + * 0x01234567 0x89abcdef + * + * On a little-endian system, the bytes are stored in memory as follows: + * + * 67 45 23 01 ef cd ab 89 + * + * MMC_RSP_BITS will extact bits as follows: + * + * start=0 len=4 -> result=0x00000007 + * start=0 len=12 -> result=0x00000567 + * start=28 len=8 -> result=0x000000f0 + * start=59 len=5 -> result=0x00000011 + * + * @param src array of words to extract bits from + * @param start index of the first bit to extract + * @param len number of bits to extract, 1 to 32 + * @return 32-bit word where requested bits start from LSB + */ +static inline uint32_t MMC_RSP_BITS(uint32_t *src, int start, int len) +{ + uint32_t mask = (len % 32 == 0) ? UINT_MAX : UINT_MAX >> (32 - (len % 32)); + size_t word = start / 32; + size_t shift = start % 32; + uint32_t right = src[word] >> shift; + uint32_t left = (len + shift <= 32) ? 0 : src[word + 1] << ((32 - shift) % 32); + return (left | right) & mask; +} + +/* SD R4 response (IO OCR) */ +#define SD_IO_OCR_MEM_READY (1<<31) +#define SD_IO_OCR_NUM_FUNCTIONS(ocr) (((ocr) >> 28) & 0x7) +#define SD_IO_OCR_MEM_PRESENT (1<<27) +#define SD_IO_OCR_MASK 0x00fffff0 + +/* CMD52 arguments */ +#define SD_ARG_CMD52_READ (0<<31) +#define SD_ARG_CMD52_WRITE (1<<31) +#define SD_ARG_CMD52_FUNC_SHIFT 28 +#define SD_ARG_CMD52_FUNC_MASK 0x7 +#define SD_ARG_CMD52_EXCHANGE (1<<27) +#define SD_ARG_CMD52_REG_SHIFT 9 +#define SD_ARG_CMD52_REG_MASK 0x1ffff +#define SD_ARG_CMD52_DATA_SHIFT 0 +#define SD_ARG_CMD52_DATA_MASK 0xff +#define SD_R5_DATA(resp) ((resp)[0] & 0xff) + +/* CMD53 arguments */ +#define SD_ARG_CMD53_READ (0<<31) +#define SD_ARG_CMD53_WRITE (1<<31) +#define SD_ARG_CMD53_FUNC_SHIFT 28 +#define SD_ARG_CMD53_FUNC_MASK 0x7 +#define SD_ARG_CMD53_BLOCK_MODE (1<<27) +#define SD_ARG_CMD53_INCREMENT (1<<26) +#define SD_ARG_CMD53_REG_SHIFT 9 +#define SD_ARG_CMD53_REG_MASK 0x1ffff +#define SD_ARG_CMD53_LENGTH_SHIFT 0 +#define SD_ARG_CMD53_LENGTH_MASK 0x1ff +#define SD_ARG_CMD53_LENGTH_MAX 512 + +/* Card Common Control Registers (CCCR) */ +#define SD_IO_CCCR_START 0x00000 +#define SD_IO_CCCR_SIZE 0x100 +#define SD_IO_CCCR_FN_ENABLE 0x02 +#define SD_IO_CCCR_FN_READY 0x03 +#define SD_IO_CCCR_INT_ENABLE 0x04 +#define SD_IO_CCCR_INT_PENDING 0x05 +#define SD_IO_CCCR_CTL 0x06 +#define CCCR_CTL_RES (1<<3) +#define SD_IO_CCCR_BUS_WIDTH 0x07 +#define CCCR_BUS_WIDTH_1 (0<<0) +#define CCCR_BUS_WIDTH_4 (2<<0) +#define CCCR_BUS_WIDTH_8 (3<<0) +#define CCCR_BUS_WIDTH_ECSI (1<<5) +#define SD_IO_CCCR_CARD_CAP 0x08 +#define CCCR_CARD_CAP_LSC BIT(6) +#define CCCR_CARD_CAP_4BLS BIT(7) +#define SD_IO_CCCR_CISPTR 0x09 +#define SD_IO_CCCR_BLKSIZEL 0x10 +#define SD_IO_CCCR_BLKSIZEH 0x11 +#define SD_IO_CCCR_HIGHSPEED 0x13 +#define CCCR_HIGHSPEED_SUPPORT BIT(0) +#define CCCR_HIGHSPEED_ENABLE BIT(1) + +/* Function Basic Registers (FBR) */ +#define SD_IO_FBR_START 0x00100 +#define SD_IO_FBR_SIZE 0x00700 + +/* Card Information Structure (CIS) */ +#define SD_IO_CIS_START 0x01000 +#define SD_IO_CIS_SIZE 0x17000 + +/* CIS tuple codes (based on PC Card 16) */ +#define CISTPL_CODE_NULL 0x00 +#define CISTPL_CODE_DEVICE 0x01 +#define CISTPL_CODE_CHKSUM 0x10 +#define CISTPL_CODE_VERS1 0x15 +#define CISTPL_CODE_ALTSTR 0x16 +#define CISTPL_CODE_CONFIG 0x1A +#define CISTPL_CODE_CFTABLE_ENTRY 0x1B +#define CISTPL_CODE_MANFID 0x20 +#define CISTPL_CODE_FUNCID 0x21 +#define TPLFID_FUNCTION_SDIO 0x0c +#define CISTPL_CODE_FUNCE 0x22 +#define CISTPL_CODE_VENDER_BEGIN 0x80 +#define CISTPL_CODE_VENDER_END 0x8F +#define CISTPL_CODE_SDIO_STD 0x91 +#define CISTPL_CODE_SDIO_EXT 0x92 +#define CISTPL_CODE_END 0xFF + + +/* Timing */ +#define SDMMC_TIMING_LEGACY 0 +#define SDMMC_TIMING_HIGHSPEED 1 +#define SDMMC_TIMING_MMC_DDR52 2 + +#endif //_SDMMC_DEFS_H_ diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_host.h b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_host.h new file mode 100644 index 00000000..e9da4ae1 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_host.h @@ -0,0 +1,247 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include "soc/soc_caps.h" +#if SOC_SDMMC_HOST_SUPPORTED + +#include +#include +#include "esp_err.h" +#include "sdmmc_types.h" +#include "driver/gpio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define SDMMC_HOST_SLOT_0 0 ///< SDMMC slot 0 +#define SDMMC_HOST_SLOT_1 1 ///< SDMMC slot 1 + +/** + * @brief Default sdmmc_host_t structure initializer for SDMMC peripheral + * + * Uses SDMMC peripheral, with 4-bit mode enabled, and max frequency set to 20MHz + */ +#define SDMMC_HOST_DEFAULT() {\ + .flags = SDMMC_HOST_FLAG_8BIT | \ + SDMMC_HOST_FLAG_4BIT | \ + SDMMC_HOST_FLAG_1BIT | \ + SDMMC_HOST_FLAG_DDR, \ + .slot = SDMMC_HOST_SLOT_1, \ + .max_freq_khz = SDMMC_FREQ_DEFAULT, \ + .io_voltage = 3.3f, \ + .init = &sdmmc_host_init, \ + .set_bus_width = &sdmmc_host_set_bus_width, \ + .get_bus_width = &sdmmc_host_get_slot_width, \ + .set_bus_ddr_mode = &sdmmc_host_set_bus_ddr_mode, \ + .set_card_clk = &sdmmc_host_set_card_clk, \ + .do_transaction = &sdmmc_host_do_transaction, \ + .deinit = &sdmmc_host_deinit, \ + .io_int_enable = sdmmc_host_io_int_enable, \ + .io_int_wait = sdmmc_host_io_int_wait, \ + .command_timeout_ms = 0, \ +} + +/** + * Extra configuration for SDMMC peripheral slot + */ +typedef struct { + gpio_num_t gpio_cd; ///< GPIO number of card detect signal + gpio_num_t gpio_wp; ///< GPIO number of write protect signal + uint8_t width; ///< Bus width used by the slot (might be less than the max width supported) + uint32_t flags; ///< Features used by this slot +#define SDMMC_SLOT_FLAG_INTERNAL_PULLUP BIT(0) + /**< Enable internal pullups on enabled pins. The internal pullups + are insufficient however, please make sure external pullups are + connected on the bus. This is for debug / example purpose only. + */ +} sdmmc_slot_config_t; + +#define SDMMC_SLOT_NO_CD GPIO_NUM_NC ///< indicates that card detect line is not used +#define SDMMC_SLOT_NO_WP GPIO_NUM_NC ///< indicates that write protect line is not used +#define SDMMC_SLOT_WIDTH_DEFAULT 0 ///< use the default width for the slot (8 for slot 0, 4 for slot 1) + +/** + * Macro defining default configuration of SDMMC host slot + */ +#define SDMMC_SLOT_CONFIG_DEFAULT() {\ + .gpio_cd = SDMMC_SLOT_NO_CD, \ + .gpio_wp = SDMMC_SLOT_NO_WP, \ + .width = SDMMC_SLOT_WIDTH_DEFAULT, \ + .flags = 0, \ +} + +/** + * @brief Initialize SDMMC host peripheral + * + * @note This function is not thread safe + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if sdmmc_host_init was already called + * - ESP_ERR_NO_MEM if memory can not be allocated + */ +esp_err_t sdmmc_host_init(void); + +/** + * @brief Initialize given slot of SDMMC peripheral + * + * On the ESP32, SDMMC peripheral has two slots: + * - Slot 0: 8-bit wide, maps to HS1_* signals in PIN MUX + * - Slot 1: 4-bit wide, maps to HS2_* signals in PIN MUX + * + * Card detect and write protect signals can be routed to + * arbitrary GPIOs using GPIO matrix. + * + * @note This function is not thread safe + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param slot_config additional configuration for the slot + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if host has not been initialized using sdmmc_host_init + */ +esp_err_t sdmmc_host_init_slot(int slot, const sdmmc_slot_config_t* slot_config); + +/** + * @brief Select bus width to be used for data transfer + * + * SD/MMC card must be initialized prior to this command, and a command to set + * bus width has to be sent to the card (e.g. SD_APP_SET_BUS_WIDTH) + * + * @note This function is not thread safe + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param width bus width (1, 4, or 8 for slot 0; 1 or 4 for slot 1) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if slot number or width is not valid + */ +esp_err_t sdmmc_host_set_bus_width(int slot, size_t width); + +/** + * @brief Get bus width configured in ``sdmmc_host_init_slot`` to be used for data transfer + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @return configured bus width of the specified slot. + */ +size_t sdmmc_host_get_slot_width(int slot); + +/** + * @brief Set card clock frequency + * + * Currently only integer fractions of 40MHz clock can be used. + * For High Speed cards, 40MHz can be used. + * For Default Speed cards, 20MHz can be used. + * + * @note This function is not thread safe + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param freq_khz card clock frequency, in kHz + * @return + * - ESP_OK on success + * - other error codes may be returned in the future + */ +esp_err_t sdmmc_host_set_card_clk(int slot, uint32_t freq_khz); + +/** + * @brief Enable or disable DDR mode of SD interface + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param ddr_enabled enable or disable DDR mode + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_SUPPORTED if DDR mode is not supported on this slot + */ +esp_err_t sdmmc_host_set_bus_ddr_mode(int slot, bool ddr_enabled); + +/** + * @brief Send command to the card and get response + * + * This function returns when command is sent and response is received, + * or data is transferred, or timeout occurs. + * + * @note This function is not thread safe w.r.t. init/deinit functions, + * and bus width/clock speed configuration functions. Multiple tasks + * can call sdmmc_host_do_transaction as long as other sdmmc_host_* + * functions are not called. + * + * @attention Data buffer passed in cmdinfo->data must be in DMA capable memory + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param cmdinfo pointer to structure describing command and data to transfer + * @return + * - ESP_OK on success + * - ESP_ERR_TIMEOUT if response or data transfer has timed out + * - ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed + * - ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response + * - ESP_ERR_INVALID_SIZE if the size of data transfer is not valid in SD protocol + * - ESP_ERR_INVALID_ARG if the data buffer is not in DMA capable memory + */ +esp_err_t sdmmc_host_do_transaction(int slot, sdmmc_command_t* cmdinfo); + +/** + * @brief Enable IO interrupts + * + * This function configures the host to accept SDIO interrupts. + * + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @return returns ESP_OK, other errors possible in the future + */ +esp_err_t sdmmc_host_io_int_enable(int slot); + +/** + * @brief Block until an SDIO interrupt is received, or timeout occurs + * @param slot slot number (SDMMC_HOST_SLOT_0 or SDMMC_HOST_SLOT_1) + * @param timeout_ticks number of RTOS ticks to wait for the interrupt + * @return + * - ESP_OK on success (interrupt received) + * - ESP_ERR_TIMEOUT if the interrupt did not occur within timeout_ticks + */ +esp_err_t sdmmc_host_io_int_wait(int slot, TickType_t timeout_ticks); + +/** + * @brief Disable SDMMC host and release allocated resources + * + * @note This function is not thread safe + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if sdmmc_host_init function has not been called + */ +esp_err_t sdmmc_host_deinit(void); + +/** + * @brief Enable the pull-ups of sd pins. + * + * @note You should always place actual pullups on the lines instead of using + * this function. Internal pullup resistance are high and not sufficient, may + * cause instability in products. This is for debug or examples only. + * + * @param slot Slot to use, normally set it to 1. + * @param width Bit width of your configuration, 1 or 4. + * + * @return + * - ESP_OK: if success + * - ESP_ERR_INVALID_ARG: if configured width larger than maximum the slot can + * support + */ +esp_err_t sdmmc_host_pullup_en(int slot, int width); + +#ifdef __cplusplus +} +#endif + +#endif //SOC_SDMMC_HOST_SUPPORTED diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_types.h b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_types.h new file mode 100644 index 00000000..25310830 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sdmmc_types.h @@ -0,0 +1,183 @@ +/* + * Copyright (c) 2006 Uwe Stuehler + * Adaptations to ESP-IDF Copyright (c) 2016 Espressif Systems (Shanghai) PTE LTD + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef _SDMMC_TYPES_H_ +#define _SDMMC_TYPES_H_ + +#include +#include +#include "esp_err.h" +#include "freertos/FreeRTOS.h" + +/** + * Decoded values from SD card Card Specific Data register + */ +typedef struct { + int csd_ver; /*!< CSD structure format */ + int mmc_ver; /*!< MMC version (for CID format) */ + int capacity; /*!< total number of sectors */ + int sector_size; /*!< sector size in bytes */ + int read_block_len; /*!< block length for reads */ + int card_command_class; /*!< Card Command Class for SD */ + int tr_speed; /*!< Max transfer speed */ +} sdmmc_csd_t; + +/** + * Decoded values from SD card Card IDentification register + */ +typedef struct { + int mfg_id; /*!< manufacturer identification number */ + int oem_id; /*!< OEM/product identification number */ + char name[8]; /*!< product name (MMC v1 has the longest) */ + int revision; /*!< product revision */ + int serial; /*!< product serial number */ + int date; /*!< manufacturing date */ +} sdmmc_cid_t; + +/** + * Decoded values from SD Configuration Register + */ +typedef struct { + int sd_spec; /*!< SD Physical layer specification version, reported by card */ + int bus_width; /*!< bus widths supported by card: BIT(0) — 1-bit bus, BIT(2) — 4-bit bus */ +} sdmmc_scr_t; + +/** + * Decoded values of Extended Card Specific Data + */ +typedef struct { + uint8_t power_class; /*!< Power class used by the card */ +} sdmmc_ext_csd_t; + +/** + * SD/MMC command response buffer + */ +typedef uint32_t sdmmc_response_t[4]; + +/** + * SD SWITCH_FUNC response buffer + */ +typedef struct { + uint32_t data[512 / 8 / sizeof(uint32_t)]; /*!< response data */ +} sdmmc_switch_func_rsp_t; + +/** + * SD/MMC command information + */ +typedef struct { + uint32_t opcode; /*!< SD or MMC command index */ + uint32_t arg; /*!< SD/MMC command argument */ + sdmmc_response_t response; /*!< response buffer */ + void* data; /*!< buffer to send or read into */ + size_t datalen; /*!< length of data buffer */ + size_t blklen; /*!< block length */ + int flags; /*!< see below */ +/** @cond */ +#define SCF_ITSDONE 0x0001 /*!< command is complete */ +#define SCF_CMD(flags) ((flags) & 0x00f0) +#define SCF_CMD_AC 0x0000 +#define SCF_CMD_ADTC 0x0010 +#define SCF_CMD_BC 0x0020 +#define SCF_CMD_BCR 0x0030 +#define SCF_CMD_READ 0x0040 /*!< read command (data expected) */ +#define SCF_RSP_BSY 0x0100 +#define SCF_RSP_136 0x0200 +#define SCF_RSP_CRC 0x0400 +#define SCF_RSP_IDX 0x0800 +#define SCF_RSP_PRESENT 0x1000 +/* response types */ +#define SCF_RSP_R0 0 /*!< none */ +#define SCF_RSP_R1 (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX) +#define SCF_RSP_R1B (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX|SCF_RSP_BSY) +#define SCF_RSP_R2 (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_136) +#define SCF_RSP_R3 (SCF_RSP_PRESENT) +#define SCF_RSP_R4 (SCF_RSP_PRESENT) +#define SCF_RSP_R5 (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX) +#define SCF_RSP_R5B (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX|SCF_RSP_BSY) +#define SCF_RSP_R6 (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX) +#define SCF_RSP_R7 (SCF_RSP_PRESENT|SCF_RSP_CRC|SCF_RSP_IDX) +/* special flags */ +#define SCF_WAIT_BUSY 0x2000 /*!< Wait for completion of card busy signal before returning */ +/** @endcond */ + esp_err_t error; /*!< error returned from transfer */ + int timeout_ms; /*!< response timeout, in milliseconds */ +} sdmmc_command_t; + +/** + * SD/MMC Host description + * + * This structure defines properties of SD/MMC host and functions + * of SD/MMC host which can be used by upper layers. + */ +typedef struct { + uint32_t flags; /*!< flags defining host properties */ +#define SDMMC_HOST_FLAG_1BIT BIT(0) /*!< host supports 1-line SD and MMC protocol */ +#define SDMMC_HOST_FLAG_4BIT BIT(1) /*!< host supports 4-line SD and MMC protocol */ +#define SDMMC_HOST_FLAG_8BIT BIT(2) /*!< host supports 8-line MMC protocol */ +#define SDMMC_HOST_FLAG_SPI BIT(3) /*!< host supports SPI protocol */ +#define SDMMC_HOST_FLAG_DDR BIT(4) /*!< host supports DDR mode for SD/MMC */ +#define SDMMC_HOST_FLAG_DEINIT_ARG BIT(5) /*!< host `deinit` function called with the slot argument */ + int slot; /*!< slot number, to be passed to host functions */ + int max_freq_khz; /*!< max frequency supported by the host */ +#define SDMMC_FREQ_DEFAULT 20000 /*!< SD/MMC Default speed (limited by clock divider) */ +#define SDMMC_FREQ_HIGHSPEED 40000 /*!< SD High speed (limited by clock divider) */ +#define SDMMC_FREQ_PROBING 400 /*!< SD/MMC probing speed */ +#define SDMMC_FREQ_52M 52000 /*!< MMC 52MHz speed */ +#define SDMMC_FREQ_26M 26000 /*!< MMC 26MHz speed */ + float io_voltage; /*!< I/O voltage used by the controller (voltage switching is not supported) */ + esp_err_t (*init)(void); /*!< Host function to initialize the driver */ + esp_err_t (*set_bus_width)(int slot, size_t width); /*!< host function to set bus width */ + size_t (*get_bus_width)(int slot); /*!< host function to get bus width */ + esp_err_t (*set_bus_ddr_mode)(int slot, bool ddr_enable); /*!< host function to set DDR mode */ + esp_err_t (*set_card_clk)(int slot, uint32_t freq_khz); /*!< host function to set card clock frequency */ + esp_err_t (*do_transaction)(int slot, sdmmc_command_t* cmdinfo); /*!< host function to do a transaction */ + union { + esp_err_t (*deinit)(void); /*!< host function to deinitialize the driver */ + esp_err_t (*deinit_p)(int slot); /*!< host function to deinitialize the driver, called with the `slot` */ + }; + esp_err_t (*io_int_enable)(int slot); /*!< Host function to enable SDIO interrupt line */ + esp_err_t (*io_int_wait)(int slot, TickType_t timeout_ticks); /*!< Host function to wait for SDIO interrupt line to be active */ + int command_timeout_ms; /*!< timeout, in milliseconds, of a single command. Set to 0 to use the default value. */ +} sdmmc_host_t; + +/** + * SD/MMC card information structure + */ +typedef struct { + sdmmc_host_t host; /*!< Host with which the card is associated */ + uint32_t ocr; /*!< OCR (Operation Conditions Register) value */ + union { + sdmmc_cid_t cid; /*!< decoded CID (Card IDentification) register value */ + sdmmc_response_t raw_cid; /*!< raw CID of MMC card to be decoded + after the CSD is fetched in the data transfer mode*/ + }; + sdmmc_csd_t csd; /*!< decoded CSD (Card-Specific Data) register value */ + sdmmc_scr_t scr; /*!< decoded SCR (SD card Configuration Register) value */ + sdmmc_ext_csd_t ext_csd; /*!< decoded EXT_CSD (Extended Card Specific Data) register value */ + uint16_t rca; /*!< RCA (Relative Card Address) */ + uint16_t max_freq_khz; /*!< Maximum frequency, in kHz, supported by the card */ + uint32_t is_mem : 1; /*!< Bit indicates if the card is a memory card */ + uint32_t is_sdio : 1; /*!< Bit indicates if the card is an IO card */ + uint32_t is_mmc : 1; /*!< Bit indicates if the card is MMC */ + uint32_t num_io_functions : 3; /*!< If is_sdio is 1, contains the number of IO functions on the card */ + uint32_t log_bus_width : 2; /*!< log2(bus width supported by card) */ + uint32_t is_ddr : 1; /*!< Card supports DDR mode */ + uint32_t reserved : 23; /*!< Reserved for future expansion */ +} sdmmc_card_t; + + +#endif // _SDMMC_TYPES_H_ diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sdspi_host.h b/tools/sdk/esp32c3/include/driver/include/driver/sdspi_host.h new file mode 100644 index 00000000..064c68cc --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sdspi_host.h @@ -0,0 +1,246 @@ +// Copyright 2015-2017 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. + +#pragma once + +#include +#include +#include "esp_err.h" +#include "sdmmc_types.h" +#include "driver/gpio.h" +#include "driver/spi_master.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// Handle representing an SD SPI device +typedef int sdspi_dev_handle_t; + +/** + * @brief Default sdmmc_host_t structure initializer for SD over SPI driver + * + * Uses SPI mode and max frequency set to 20MHz + * + * 'slot' should be set to an sdspi device initialized by `sdspi_host_init_device()`. + */ +#define SDSPI_HOST_DEFAULT() {\ + .flags = SDMMC_HOST_FLAG_SPI | SDMMC_HOST_FLAG_DEINIT_ARG, \ + .slot = HSPI_HOST, \ + .max_freq_khz = SDMMC_FREQ_DEFAULT, \ + .io_voltage = 3.3f, \ + .init = &sdspi_host_init, \ + .set_bus_width = NULL, \ + .get_bus_width = NULL, \ + .set_bus_ddr_mode = NULL, \ + .set_card_clk = &sdspi_host_set_card_clk, \ + .do_transaction = &sdspi_host_do_transaction, \ + .deinit_p = &sdspi_host_remove_device, \ + .io_int_enable = &sdspi_host_io_int_enable, \ + .io_int_wait = &sdspi_host_io_int_wait, \ + .command_timeout_ms = 0, \ +} + +/** + * Extra configuration for SD SPI device. + */ +typedef struct { + spi_host_device_t host_id; ///< SPI host to use, SPIx_HOST (see spi_types.h). + gpio_num_t gpio_cs; ///< GPIO number of CS signal + gpio_num_t gpio_cd; ///< GPIO number of card detect signal + gpio_num_t gpio_wp; ///< GPIO number of write protect signal + gpio_num_t gpio_int; ///< GPIO number of interrupt line (input) for SDIO card. +} sdspi_device_config_t; + +#define SDSPI_SLOT_NO_CD GPIO_NUM_NC ///< indicates that card detect line is not used +#define SDSPI_SLOT_NO_WP GPIO_NUM_NC ///< indicates that write protect line is not used +#define SDSPI_SLOT_NO_INT GPIO_NUM_NC ///< indicates that interrupt line is not used + +/** + * Macro defining default configuration of SD SPI device. + */ +#define SDSPI_DEVICE_CONFIG_DEFAULT() {\ + .host_id = HSPI_HOST, \ + .gpio_cs = GPIO_NUM_13, \ + .gpio_cd = SDSPI_SLOT_NO_CD, \ + .gpio_wp = SDSPI_SLOT_NO_WP, \ + .gpio_int = GPIO_NUM_NC, \ +} + +/** + * @brief Initialize SD SPI driver + * + * @note This function is not thread safe + * + * @return + * - ESP_OK on success + * - other error codes may be returned in future versions + */ +esp_err_t sdspi_host_init(void); + +/** +* @brief Attach and initialize an SD SPI device on the specific SPI bus +* +* @note This function is not thread safe +* +* @note Initialize the SPI bus by `spi_bus_initialize()` before calling this function. +* +* @note The SDIO over sdspi needs an extra interrupt line. Call ``gpio_install_isr_service()`` before this function. +* +* @param dev_config pointer to device configuration structure +* @param out_handle Output of the handle to the sdspi device. + +* @return +* - ESP_OK on success +* - ESP_ERR_INVALID_ARG if sdspi_host_init_device has invalid arguments +* - ESP_ERR_NO_MEM if memory can not be allocated +* - other errors from the underlying spi_master and gpio drivers +*/ +esp_err_t sdspi_host_init_device(const sdspi_device_config_t* dev_config, sdspi_dev_handle_t* out_handle); + +/** + * @brief Remove an SD SPI device + * + * @param handle Handle of the SD SPI device + * @return Always ESP_OK + */ +esp_err_t sdspi_host_remove_device(sdspi_dev_handle_t handle); + +/** + * @brief Send command to the card and get response + * + * This function returns when command is sent and response is received, + * or data is transferred, or timeout occurs. + * + * @note This function is not thread safe w.r.t. init/deinit functions, + * and bus width/clock speed configuration functions. Multiple tasks + * can call sdspi_host_do_transaction as long as other sdspi_host_* + * functions are not called. + * + * @param handle Handle of the sdspi device + * @param cmdinfo pointer to structure describing command and data to transfer + * @return + * - ESP_OK on success + * - ESP_ERR_TIMEOUT if response or data transfer has timed out + * - ESP_ERR_INVALID_CRC if response or data transfer CRC check has failed + * - ESP_ERR_INVALID_RESPONSE if the card has sent an invalid response + */ +esp_err_t sdspi_host_do_transaction(sdspi_dev_handle_t handle, sdmmc_command_t *cmdinfo); + +/** + * @brief Set card clock frequency + * + * Currently only integer fractions of 40MHz clock can be used. + * For High Speed cards, 40MHz can be used. + * For Default Speed cards, 20MHz can be used. + * + * @note This function is not thread safe + * + * @param host Handle of the sdspi device + * @param freq_khz card clock frequency, in kHz + * @return + * - ESP_OK on success + * - other error codes may be returned in the future + */ +esp_err_t sdspi_host_set_card_clk(sdspi_dev_handle_t host, uint32_t freq_khz); + +/** + * @brief Release resources allocated using sdspi_host_init + * + * @note This function is not thread safe + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if sdspi_host_init function has not been called + */ +esp_err_t sdspi_host_deinit(void); + +/** + * @brief Enable SDIO interrupt. + * + * @param handle Handle of the sdspi device + * + * @return + * - ESP_OK on success + */ +esp_err_t sdspi_host_io_int_enable(sdspi_dev_handle_t handle); + +/** + * @brief Wait for SDIO interrupt until timeout. + * + * @param handle Handle of the sdspi device + * @param timeout_ticks Ticks to wait before timeout. + * + * @return + * - ESP_OK on success + */ +esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks); + +/******************************************************************************* + * Deprecated APIs + ******************************************************************************/ + +/** + * Extra configuration for SPI host. + * + * @deprecated Use `sdspi_device_config_t` and corresponding `sdspi_host_init_device()` instead. + */ +typedef struct { + gpio_num_t gpio_cs; ///< GPIO number of CS signal + gpio_num_t gpio_cd; ///< GPIO number of card detect signal + gpio_num_t gpio_wp; ///< GPIO number of write protect signal + gpio_num_t gpio_int; ///< GPIO number of interrupt line (input) for SDIO card. + gpio_num_t gpio_miso; ///< GPIO number of MISO signal. + gpio_num_t gpio_mosi; ///< GPIO number of MOSI signal. + gpio_num_t gpio_sck; ///< GPIO number of SCK signal. + int dma_channel; ///< DMA channel to be used by SPI driver (1 or 2). +} sdspi_slot_config_t; + +/** + * Macro defining default configuration of SPI host + */ +#define SDSPI_SLOT_CONFIG_DEFAULT() {\ + .gpio_cs = GPIO_NUM_13, \ + .gpio_cd = SDSPI_SLOT_NO_CD, \ + .gpio_wp = SDSPI_SLOT_NO_WP, \ + .gpio_int = GPIO_NUM_NC, \ + .gpio_miso = GPIO_NUM_2, \ + .gpio_mosi = GPIO_NUM_15, \ + .gpio_sck = GPIO_NUM_14, \ + .dma_channel = 1, \ +} + +/** +* @brief Initialize SD SPI driver for the specific SPI controller +* +* @note This function is not thread safe +* +* @note The SDIO over sdspi needs an extra interrupt line. Call ``gpio_install_isr_service()`` before this function. +* +* @param slot SPI controller to use (HSPI_HOST or VSPI_HOST) +* @param slot_config pointer to slot configuration structure + +* @deprecated Use `sdspi_host_init_device` instead. +* +* @return +* - ESP_OK on success +* - ESP_ERR_INVALID_ARG if sdspi_init_slot has invalid arguments +* - ESP_ERR_NO_MEM if memory can not be allocated +* - other errors from the underlying spi_master and gpio drivers +*/ +esp_err_t sdspi_host_init_slot(int slot, const sdspi_slot_config_t* slot_config); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/sigmadelta.h b/tools/sdk/esp32c3/include/driver/include/driver/sigmadelta.h new file mode 100644 index 00000000..d7e7eef1 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/sigmadelta.h @@ -0,0 +1,86 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include +#include "soc/soc_caps.h" +#include "soc/sigmadelta_periph.h" +#include "driver/gpio.h" +#include "hal/sigmadelta_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Configure Sigma-delta channel + * + * @param config Pointer of Sigma-delta channel configuration struct + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE sigmadelta driver already initialized + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t sigmadelta_config(const sigmadelta_config_t *config); + +/** + * @brief Set Sigma-delta channel duty. + * + * This function is used to set Sigma-delta channel duty, + * If you add a capacitor between the output pin and ground, + * the average output voltage will be Vdc = VDDIO / 256 * duty + VDDIO/2, + * where VDDIO is the power supply voltage. + * + * @param channel Sigma-delta channel number + * @param duty Sigma-delta duty of one channel, the value ranges from -128 to 127, recommended range is -90 ~ 90. + * The waveform is more like a random one in this range. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE sigmadelta driver has not been initialized + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t sigmadelta_set_duty(sigmadelta_channel_t channel, int8_t duty); + +/** + * @brief Set Sigma-delta channel's clock pre-scale value. + * The source clock is APP_CLK, 80MHz. The clock frequency of the sigma-delta channel is APP_CLK / pre_scale + * + * @param channel Sigma-delta channel number + * @param prescale The divider of source clock, ranges from 0 to 255 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE sigmadelta driver has not been initialized + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t sigmadelta_set_prescale(sigmadelta_channel_t channel, uint8_t prescale); + +/** + * @brief Set Sigma-delta signal output pin + * + * @param channel Sigma-delta channel number + * @param gpio_num GPIO number of output pin. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE sigmadelta driver has not been initialized + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t sigmadelta_set_pin(sigmadelta_channel_t channel, gpio_num_t gpio_num); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/spi_common.h b/tools/sdk/esp32c3/include/driver/include/driver/spi_common.h new file mode 100644 index 00000000..05d7d2c7 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/spi_common.h @@ -0,0 +1,162 @@ +// Copyright 2010-2019 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. + +#pragma once + +#include +#include +#include "esp_err.h" +#include "soc/lldesc.h" +#include "soc/spi_periph.h" +#include "hal/spi_types.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +//Maximum amount of bytes that can be put in one DMA descriptor +#define SPI_MAX_DMA_LEN (4096-4) + +/** + * Transform unsigned integer of length <= 32 bits to the format which can be + * sent by the SPI driver directly. + * + * E.g. to send 9 bits of data, you can: + * + * uint16_t data = SPI_SWAP_DATA_TX(0x145, 9); + * + * Then points tx_buffer to ``&data``. + * + * @param DATA Data to be sent, can be uint8_t, uint16_t or uint32_t. + * @param LEN Length of data to be sent, since the SPI peripheral sends from + * the MSB, this helps to shift the data to the MSB. + */ +#define SPI_SWAP_DATA_TX(DATA, LEN) __builtin_bswap32((uint32_t)(DATA)<<(32-(LEN))) + +/** + * Transform received data of length <= 32 bits to the format of an unsigned integer. + * + * E.g. to transform the data of 15 bits placed in a 4-byte array to integer: + * + * uint16_t data = SPI_SWAP_DATA_RX(*(uint32_t*)t->rx_data, 15); + * + * @param DATA Data to be rearranged, can be uint8_t, uint16_t or uint32_t. + * @param LEN Length of data received, since the SPI peripheral writes from + * the MSB, this helps to shift the data to the LSB. + */ +#define SPI_SWAP_DATA_RX(DATA, LEN) (__builtin_bswap32(DATA)>>(32-(LEN))) + +#define SPICOMMON_BUSFLAG_SLAVE 0 ///< Initialize I/O in slave mode +#define SPICOMMON_BUSFLAG_MASTER (1<<0) ///< Initialize I/O in master mode +#define SPICOMMON_BUSFLAG_IOMUX_PINS (1<<1) ///< Check using iomux pins. Or indicates the pins are configured through the IO mux rather than GPIO matrix. +#define SPICOMMON_BUSFLAG_GPIO_PINS (1<<2) ///< Force the signals to be routed through GPIO matrix. Or indicates the pins are routed through the GPIO matrix. +#define SPICOMMON_BUSFLAG_SCLK (1<<3) ///< Check existing of SCLK pin. Or indicates CLK line initialized. +#define SPICOMMON_BUSFLAG_MISO (1<<4) ///< Check existing of MISO pin. Or indicates MISO line initialized. +#define SPICOMMON_BUSFLAG_MOSI (1<<5) ///< Check existing of MOSI pin. Or indicates MOSI line initialized. +#define SPICOMMON_BUSFLAG_DUAL (1<<6) ///< Check MOSI and MISO pins can output. Or indicates bus able to work under DIO mode. +#define SPICOMMON_BUSFLAG_WPHD (1<<7) ///< Check existing of WP and HD pins. Or indicates WP & HD pins initialized. +#define SPICOMMON_BUSFLAG_QUAD (SPICOMMON_BUSFLAG_DUAL|SPICOMMON_BUSFLAG_WPHD) ///< Check existing of MOSI/MISO/WP/HD pins as output. Or indicates bus able to work under QIO mode. + +#define SPICOMMON_BUSFLAG_NATIVE_PINS SPICOMMON_BUSFLAG_IOMUX_PINS + +/** + * @brief SPI DMA channels + */ +typedef enum { + SPI_DMA_DISABLED = 0, ///< Do not enable DMA for SPI +#if CONFIG_IDF_TARGET_ESP32 + SPI_DMA_CH1 = 1, ///< Enable DMA, select DMA Channel 1 + SPI_DMA_CH2 = 2, ///< Enable DMA, select DMA Channel 2 +#endif + SPI_DMA_CH_AUTO = 3, ///< Enable DMA, channel is automatically selected by driver +} spi_common_dma_t; + +#if __cplusplus +/* Needed for C++ backwards compatibility with earlier ESP-IDF where this argument is a bare 'int'. Can be removed in ESP-IDF 5 */ +typedef int spi_dma_chan_t; +#else +typedef spi_common_dma_t spi_dma_chan_t; +#endif + +/** + * @brief This is a configuration structure for a SPI bus. + * + * You can use this structure to specify the GPIO pins of the bus. Normally, the driver will use the + * GPIO matrix to route the signals. An exception is made when all signals either can be routed through + * the IO_MUX or are -1. In that case, the IO_MUX is used, allowing for >40MHz speeds. + * + * @note Be advised that the slave driver does not use the quadwp/quadhd lines and fields in spi_bus_config_t refering to these lines will be ignored and can thus safely be left uninitialized. + */ +typedef struct { + int mosi_io_num; ///< GPIO pin for Master Out Slave In (=spi_d) signal, or -1 if not used. + int miso_io_num; ///< GPIO pin for Master In Slave Out (=spi_q) signal, or -1 if not used. + int sclk_io_num; ///< GPIO pin for Spi CLocK signal, or -1 if not used. + int quadwp_io_num; ///< GPIO pin for WP (Write Protect) signal which is used as D2 in 4-bit communication modes, or -1 if not used. + int quadhd_io_num; ///< GPIO pin for HD (HolD) signal which is used as D3 in 4-bit communication modes, or -1 if not used. + int max_transfer_sz; ///< Maximum transfer size, in bytes. Defaults to 4094 if 0. + uint32_t flags; ///< Abilities of bus to be checked by the driver. Or-ed value of ``SPICOMMON_BUSFLAG_*`` flags. + int intr_flags; /**< Interrupt flag for the bus to set the priority, and IRAM attribute, see + * ``esp_intr_alloc.h``. Note that the EDGE, INTRDISABLED attribute are ignored + * by the driver. Note that if ESP_INTR_FLAG_IRAM is set, ALL the callbacks of + * the driver, and their callee functions, should be put in the IRAM. + */ +} spi_bus_config_t; + + +/** + * @brief Initialize a SPI bus + * + * @warning For now, only supports HSPI and VSPI. + * + * @param host_id SPI peripheral that controls this bus + * @param bus_config Pointer to a spi_bus_config_t struct specifying how the host should be initialized + * @param dma_chan - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. + * - Selecting SPI_DMA_DISABLED limits the size of transactions. + * - Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. + * - Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. + * + * @warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in + * DMA-capable memory. + * + * @warning The ISR of SPI is always executed on the core which calls this + * function. Never starve the ISR on this core or the SPI transactions will not + * be handled. + * + * @return + * - ESP_ERR_INVALID_ARG if configuration is invalid + * - ESP_ERR_INVALID_STATE if host already is in use + * - ESP_ERR_NOT_FOUND if there is no available DMA channel + * - ESP_ERR_NO_MEM if out of memory + * - ESP_OK on success + */ +esp_err_t spi_bus_initialize(spi_host_device_t host_id, const spi_bus_config_t *bus_config, spi_dma_chan_t dma_chan); + +/** + * @brief Free a SPI bus + * + * @warning In order for this to succeed, all devices have to be removed first. + * + * @param host_id SPI peripheral to free + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_INVALID_STATE if not all devices on the bus are freed + * - ESP_OK on success + */ +esp_err_t spi_bus_free(spi_host_device_t host_id); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/spi_common_internal.h b/tools/sdk/esp32c3/include/driver/include/driver/spi_common_internal.h new file mode 100644 index 00000000..b490efeb --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/spi_common_internal.h @@ -0,0 +1,786 @@ +// Copyright 2010-2019 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. + +// Internal header, don't use it in the user code + +#pragma once + +#include +#include "driver/spi_common.h" +#include "freertos/FreeRTOS.h" +#include "hal/spi_types.h" +#include "esp_pm.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +#ifdef CONFIG_SPI_MASTER_ISR_IN_IRAM +#define SPI_MASTER_ISR_ATTR IRAM_ATTR +#else +#define SPI_MASTER_ISR_ATTR +#endif + +#ifdef CONFIG_SPI_MASTER_IN_IRAM +#define SPI_MASTER_ATTR IRAM_ATTR +#else +#define SPI_MASTER_ATTR +#endif + + +#define BUS_LOCK_DEBUG 0 + +#if BUS_LOCK_DEBUG +#define BUS_LOCK_DEBUG_EXECUTE_CHECK(x) assert(x) +#else +#define BUS_LOCK_DEBUG_EXECUTE_CHECK(x) +#endif + + +struct spi_bus_lock_t; +struct spi_bus_lock_dev_t; +/// Handle to the lock of an SPI bus +typedef struct spi_bus_lock_t* spi_bus_lock_handle_t; +/// Handle to lock of one of the device on an SPI bus +typedef struct spi_bus_lock_dev_t* spi_bus_lock_dev_handle_t; + +/// Background operation control function +typedef void (*bg_ctrl_func_t)(void*); + +/// Attributes of an SPI bus +typedef struct { + spi_bus_config_t bus_cfg; ///< Config used to initialize the bus + uint32_t flags; ///< Flags (attributes) of the bus + int max_transfer_sz; ///< Maximum length of bytes available to send + bool dma_enabled; ///< To enable DMA or not + int tx_dma_chan; ///< TX DMA channel, on ESP32 and ESP32S2, tx_dma_chan and rx_dma_chan are same + int rx_dma_chan; ///< RX DMA channel, on ESP32 and ESP32S2, tx_dma_chan and rx_dma_chan are same + int dma_desc_num; ///< DMA descriptor number of dmadesc_tx or dmadesc_rx. + lldesc_t *dmadesc_tx; ///< DMA descriptor array for TX + lldesc_t *dmadesc_rx; ///< DMA descriptor array for RX + spi_bus_lock_handle_t lock; +#ifdef CONFIG_PM_ENABLE + esp_pm_lock_handle_t pm_lock; ///< Power management lock +#endif +} spi_bus_attr_t; + +/// Destructor called when a bus is deinitialized. +typedef esp_err_t (*spi_destroy_func_t)(void*); + + +/** + * @brief Try to claim a SPI peripheral + * + * Call this if your driver wants to manage a SPI peripheral. + * + * @param host Peripheral to claim + * @param source The caller indentification string. + * + * @note This public API is deprecated. + * + * @return True if peripheral is claimed successfully; false if peripheral already is claimed. + */ +bool spicommon_periph_claim(spi_host_device_t host, const char* source); + +/** + * @brief Check whether the spi periph is in use. + * + * @param host Peripheral to check. + * + * @note This public API is deprecated. + * + * @return True if in use, otherwise false. + */ +bool spicommon_periph_in_use(spi_host_device_t host); + +/** + * @brief Return the SPI peripheral so another driver can claim it. + * + * @param host Peripheral to return + * + * @note This public API is deprecated. + * + * @return True if peripheral is returned successfully; false if peripheral was free to claim already. + */ +bool spicommon_periph_free(spi_host_device_t host); + +/** + * @brief Alloc DMA for SPI Slave + * + * @param host_id SPI host ID + * @param dma_chan DMA channel to be used + * @param[out] out_actual_tx_dma_chan Actual TX DMA channel (if you choose to assign a specific DMA channel, this will be the channel you assigned before) + * @param[out] out_actual_rx_dma_chan Actual RX DMA channel (if you choose to assign a specific DMA channel, this will be the channel you assigned before) + * + * @return + * - ESP_OK: On success + * - ESP_ERR_NO_MEM: No enough memory + * - ESP_ERR_NOT_FOUND: There is no available DMA channel + */ +esp_err_t spicommon_slave_dma_chan_alloc(spi_host_device_t host_id, spi_dma_chan_t dma_chan, uint32_t *out_actual_tx_dma_chan, uint32_t *out_actual_rx_dma_chan); + +/** + * @brief Free DMA for SPI Slave + * + * @param host_id SPI host ID + * + * @return + * - ESP_OK: On success + */ +esp_err_t spicommon_slave_free_dma(spi_host_device_t host_id); + +/** + * @brief Connect a SPI peripheral to GPIO pins + * + * This routine is used to connect a SPI peripheral to the IO-pads and DMA channel given in + * the arguments. Depending on the IO-pads requested, the routing is done either using the + * IO_mux or using the GPIO matrix. + * + * @note This public API is deprecated. Please call ``spi_bus_initialize`` for master + * bus initialization and ``spi_slave_initialize`` for slave initialization. + * + * @param host SPI peripheral to be routed + * @param bus_config Pointer to a spi_bus_config struct detailing the GPIO pins + * @param flags Combination of SPICOMMON_BUSFLAG_* flags, set to ensure the pins set are capable with some functions: + * - ``SPICOMMON_BUSFLAG_MASTER``: Initialize I/O in master mode + * - ``SPICOMMON_BUSFLAG_SLAVE``: Initialize I/O in slave mode + * - ``SPICOMMON_BUSFLAG_IOMUX_PINS``: Pins set should match the iomux pins of the controller. + * - ``SPICOMMON_BUSFLAG_SCLK``, ``SPICOMMON_BUSFLAG_MISO``, ``SPICOMMON_BUSFLAG_MOSI``: + * Make sure SCLK/MISO/MOSI is/are set to a valid GPIO. Also check output capability according to the mode. + * - ``SPICOMMON_BUSFLAG_DUAL``: Make sure both MISO and MOSI are output capable so that DIO mode is capable. + * - ``SPICOMMON_BUSFLAG_WPHD`` Make sure WP and HD are set to valid output GPIOs. + * - ``SPICOMMON_BUSFLAG_QUAD``: Combination of ``SPICOMMON_BUSFLAG_DUAL`` and ``SPICOMMON_BUSFLAG_WPHD``. + * @param[out] flags_o A SPICOMMON_BUSFLAG_* flag combination of bus abilities will be written to this address. + * Leave to NULL if not needed. + * - ``SPICOMMON_BUSFLAG_IOMUX_PINS``: The bus is connected to iomux pins. + * - ``SPICOMMON_BUSFLAG_SCLK``, ``SPICOMMON_BUSFLAG_MISO``, ``SPICOMMON_BUSFLAG_MOSI``: The bus has + * CLK/MISO/MOSI connected. + * - ``SPICOMMON_BUSFLAG_DUAL``: The bus is capable with DIO mode. + * - ``SPICOMMON_BUSFLAG_WPHD`` The bus has WP and HD connected. + * - ``SPICOMMON_BUSFLAG_QUAD``: Combination of ``SPICOMMON_BUSFLAG_DUAL`` and ``SPICOMMON_BUSFLAG_WPHD``. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spicommon_bus_initialize_io(spi_host_device_t host, const spi_bus_config_t *bus_config, uint32_t flags, uint32_t *flags_o); + +/** + * @brief Free the IO used by a SPI peripheral + * + * @note This public API is deprecated. Please call ``spi_bus_free`` for master + * bus deinitialization and ``spi_slave_free`` for slave deinitialization. + * + * @param bus_cfg Bus config struct which defines which pins to be used. + * + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spicommon_bus_free_io_cfg(const spi_bus_config_t *bus_cfg); + +/** + * @brief Initialize a Chip Select pin for a specific SPI peripheral + * + * @note This public API is deprecated. Please call corresponding device initialization + * functions. + * + * @param host SPI peripheral + * @param cs_io_num GPIO pin to route + * @param cs_num CS id to route + * @param force_gpio_matrix If true, CS will always be routed through the GPIO matrix. If false, + * if the GPIO number allows it, the routing will happen through the IO_mux. + */ +void spicommon_cs_initialize(spi_host_device_t host, int cs_io_num, int cs_num, int force_gpio_matrix); + +/** + * @brief Free a chip select line + * + * @param cs_gpio_num CS gpio num to free + * + * @note This public API is deprecated. + */ +void spicommon_cs_free_io(int cs_gpio_num); + +/** + * @brief Check whether all pins used by a host are through IOMUX. + * + * @param host SPI peripheral + * + * @note This public API is deprecated. + * + * @return false if any pins are through the GPIO matrix, otherwise true. + */ +bool spicommon_bus_using_iomux(spi_host_device_t host); + +/** + * @brief Get the IRQ source for a specific SPI host + * + * @param host The SPI host + * + * @note This public API is deprecated. + * + * @return The hosts IRQ source + */ +int spicommon_irqsource_for_host(spi_host_device_t host); + +/** + * @brief Get the IRQ source for a specific SPI DMA + * + * @param host The SPI host + * + * @note This public API is deprecated. + * + * @return The hosts IRQ source + */ +int spicommon_irqdma_source_for_host(spi_host_device_t host); + +/** + * Callback, to be called when a DMA engine reset is completed +*/ +typedef void(*dmaworkaround_cb_t)(void *arg); + + +/** + * @brief Request a reset for a certain DMA channel + * + * @note In some (well-defined) cases in the ESP32 (at least rev v.0 and v.1), a SPI DMA channel will get confused. This can be remedied + * by resetting the SPI DMA hardware in case this happens. Unfortunately, the reset knob used for thsi will reset _both_ DMA channels, and + * as such can only done safely when both DMA channels are idle. These functions coordinate this. + * + * Essentially, when a reset is needed, a driver can request this using spicommon_dmaworkaround_req_reset. This is supposed to be called + * with an user-supplied function as an argument. If both DMA channels are idle, this call will reset the DMA subsystem and return true. + * If the other DMA channel is still busy, it will return false; as soon as the other DMA channel is done, however, it will reset the + * DMA subsystem and call the callback. The callback is then supposed to be used to continue the SPI drivers activity. + * + * @param dmachan DMA channel associated with the SPI host that needs a reset + * @param cb Callback to call in case DMA channel cannot be reset immediately + * @param arg Argument to the callback + * + * @note This public API is deprecated. + * + * @return True when a DMA reset could be executed immediately. False when it could not; in this + * case the callback will be called with the specified argument when the logic can execute + * a reset, after that reset. + */ +bool spicommon_dmaworkaround_req_reset(int dmachan, dmaworkaround_cb_t cb, void *arg); + + +/** + * @brief Check if a DMA reset is requested but has not completed yet + * + * @note This public API is deprecated. + * + * @return True when a DMA reset is requested but hasn't completed yet. False otherwise. + */ +bool spicommon_dmaworkaround_reset_in_progress(void); + + +/** + * @brief Mark a DMA channel as idle. + * + * A call to this function tells the workaround logic that this channel will + * not be affected by a global SPI DMA reset. + * + * @note This public API is deprecated. + */ +void spicommon_dmaworkaround_idle(int dmachan); + +/** + * @brief Mark a DMA channel as active. + * + * A call to this function tells the workaround logic that this channel will + * be affected by a global SPI DMA reset, and a reset like that should not be attempted. + * + * @note This public API is deprecated. + */ +void spicommon_dmaworkaround_transfer_active(int dmachan); + +/******************************************************************************* + * Bus attributes + ******************************************************************************/ +/** + * @brief Set bus lock for the main bus, called by startup code. + * + * @param lock The lock to be used by the main SPI bus. + */ +void spi_bus_main_set_lock(spi_bus_lock_handle_t lock); + +/** + * @brief Get the attributes of a specified SPI bus. + * + * @param host_id The specified host to get attribute + * @return (Const) Pointer to the attributes + */ +const spi_bus_attr_t* spi_bus_get_attr(spi_host_device_t host_id); + +/** + * @brief Register a function to a initialized bus to make it called when deinitializing the bus. + * + * @param host_id The SPI bus to register the destructor. + * @param f Destructor to register + * @param arg The argument to call the destructor + * @return Always ESP_OK. + */ +esp_err_t spi_bus_register_destroy_func(spi_host_device_t host_id, + spi_destroy_func_t f, void *arg); + +/******************************************************************************* + * SPI Bus Lock for arbitration among SPI master (intr, polling) trans, SPI flash operations and + * flash/psram cache access. + * + * NON-PUBLIC API. Don't use it directly in applications. + * + * There is the main lock corresponding to an SPI bus, of which several devices (holding child + * locks) attaching to it. Each of the device is STRONGLY RECOMMENDED to be used in only one task + * to avoid concurrency issues. + * + * Terms: + * - BG operations (BackGround operations) means some transaction that will not immediately / + * explicitly be sent in the task. It can be some cache access, or interrupt transactions. + * + * - Operation: usage of the bus, for example, do SPI transactions. + * + * - Acquiring processor: the task or the ISR that is allowed to use the bus. No operations will be + * performed if there is no acquiring processor. A processor becomes the acquiring processor if + * it ask for that when no acquiring processor exist, otherwise it has to wait for the acquiring + * processor to handle over the role to it. The acquiring processor will and will only assign one + * acquiring processor in the waiting list (if not empty) when it finishes its operation. + * + * - Acquiring device: the only device allowed to use the bus. Operations can be performed in + * either the BG or the task. When there's no acquiring device, only the ISR is allowed to be the + * acquiring processor and perform operations on the bus. + * + * When a device wants to perform operations, it either: + * 1. Acquire the bus, and operate in the task (e.g. polling transactions of SPI master, and SPI flash + * operations) + * + * 2. Request a BG operation. And the ISR will be enabled at proper time. + * + * For example if a task wants to send an interrupt transaction, it prepares the data in the task, + * call `spi_bus_lock_bg_request`, and handle sending in the ISR. + * + * 3. When a device has already acquired the bus, BG operations are also allowed. After the + * `spi_bus_lock_bg_request` is called, call `spi_bus_lock_wait_bg_done` before operations in task + * again to wait until BG operations are done. + * + * Any device may try to invoke the ISR (by `spi_bus_lock_bg_request`). The ISR will be invoked and + * become the acquiring processor immediately when the bus is not acquired by other processors. Any + * device may also try to acquire the bus (by `spi_bus_lock_acquire_start`). The device will become + * the acquiring processor immediately when the bus is not acquired and there is no request active. + * + * The acquiring processor must be aware of its acquiring role, and properly transfer the acquiring + * processor to other tasks or ISR when they have nothing else to do. Before picking a new + * acquiring processor, a new acquiring device must be picked first, if there are other devices, + * asking to be acquiring device. After that, the new acquiring processor is picked by the sequence + * below: + * + * 1. If there is an acquiring device: + * 1.1 The ISR, if acquiring device has active BG requests + * 1.2 The task of the device, if no active BG request for the device + * 2. The ISR, if there's no acquiring device, but any BG request is active + * 3. No one becomes the acquiring processor + * + * The API also helps on the arbitration of SPI cs lines. The bus is initialized with a cs_num + * argument. When attaching devices onto the bus with `spi_bus_lock_register_dev`, it will allocate + * devices with different device ID according to the flags given. If the ID is smaller than the + * cs_num given when bus is initialized, error will be returned. + * + * Usage: + * * Initialization: + * 1. Call `spi_bus_init_lock` to register a lock for a bus. + * 2. Call `spi_bus_lock_set_bg_control` to prepare BG enable/disable functions for + * the lock. + * 3. Call `spi_bus_lock_register_dev` for each devices that may make use of the + * bus, properly store the returned handle, representing those devices. + * + * * Acquiring: + * 1. Call `spi_bus_lock_acquire_start` when a device wants to use the bus + * 2. Call `spi_bus_lock_touch` to mark the bus as touched by this device. Also check if the bus + * has been touched by other devices. + * 3. (optional) Do something on the bus... + * 4. (optional) Call `spi_bus_lock_bg_request` to inform and invoke the BG. See ISR below about + * ISR operations. + * 5. (optional) If `spi_bus_lock_bg_request` is done, you have to call `spi_bus_lock_wait_bg_done` + * before touching the bus again, or do the following steps. + * 6. Call `spi_bus_lock_acquire_end` to release the bus to other devices. + * + * * ISR: + * 1. Call `spi_bus_lock_bg_entry` when entering the ISR, run or skip the closure for the previous + * operation according to the return value. + * 2. Call `spi_bus_lock_get_acquiring_dev` to get the acquiring device. If there is no acquiring + * device, call `spi_bus_lock_bg_check_dev_acq` to check and update a new acquiring device. + * 3. Call `spi_bus_lock_bg_check_dev_req` to check for request of the desired device. If the + * desired device is not requested, go to step 5. + * 4. Check, start operation for the desired device and go to step 6; otherwise if no operations + * can be performed, call `spi_bus_lock_bg_clear_req` to clear the request for this device. If + * `spi_bus_lock_bg_clear_req` is called and there is no BG requests active, goto step 6. + * 5. (optional) If the device is the acquiring device, go to step 6, otherwise + * find another desired device, and go back to step 3. + * 6. Call `spi_bus_lock_bg_exit` to try quitting the ISR. If failed, go back to step 2 to look for + * a new request again. Otherwise, quit the ISR. + * + * * Deinitialization (optional): + * 1. Call `spi_bus_lock_unregister_dev` for each device when they are no longer needed. + * 2. Call `spi_bus_deinit_lock` to release the resources occupied by the lock. + * + * Some technical details: + * + * The child-lock of each device will have its own Binary Semaphore, which allows the task serving + * this device (task A) being blocked when it fail to become the acquiring processor while it's + * calling `spi_bus_lock_acquire_start` or `spi_bus_lock_wait_bg_done`. If it is blocked, there + * must be an acquiring processor (either the ISR or another task (task B)), is doing transaction + * on the bus. After that, task A will get unblocked and become the acquiring processor when the + * ISR call `spi_bus_lock_bg_resume_acquired_dev`, or task B call `spi_bus_lock_acquire_end`. + * + * When the device wants to send ISR transaction, it should call `spi_bus_lock_bg_request` after + * the data is prepared. This function sets a request bit in the critical resource. The ISR will be + * invoked and become the new acquiring processor, when: + * + * 1. A task calls `spi_bus_lock_bg_request` while there is no acquiring processor; + * 2. A tasks calls `spi_bus_lock_bg_request` while the task is the acquiring processor. Then the + * acquiring processor is handled over to the ISR; + * 3. A tasks who is the acquiring processor release the bus by calling `spi_bus_lock_acquire_end`, + * and the ISR happens to be the next acquiring processor. + * + * The ISR will check (by `spi_bus_lock_bg_check_dev_req`) and clear a request bit (by + * `spi_bus_lock_bg_clear_req`) after it confirm that all the requests of the corresponding device + * are served. The request bit supports being written to recursively, which means, the task don't + * need to wait for `spi_bus_lock_bg_clear_req` before call another `spi_bus_lock_bg_request`. The + * API will handle the concurrency conflicts properly. + * + * The `spi_bus_lock_bg_exit` (together with `spi_bus_lock_bg_entry` called before)` is responsible + * to ensure ONE and ONLY ONE of the following will happen when the ISR try to give up its + * acquiring processor rule: + * + * 1. ISR quit, no any task unblocked while the interrupt disabled, and none of the BG bits is + * active. + * 2. ISR quit, there is an acquiring device, and the acquiring processor is passed to the task + * serving the acquiring device by unblocking the task. + * 3. The ISR failed to quit and have to try again. + ******************************************************************************/ + +#define DEV_NUM_MAX 6 ///< Number of devices supported by this lock + +/// Lock configuration struct +typedef struct { + int host_id; ///< SPI host id + int cs_num; ///< Physical cs numbers of the host +} spi_bus_lock_config_t; + +/// Child-lock configuration struct +typedef struct { + uint32_t flags; ///< flags for the lock, OR-ed of `SPI_BUS_LOCK_DEV_*` flags. +#define SPI_BUS_LOCK_DEV_FLAG_CS_REQUIRED BIT(0) ///< The device needs a physical CS pin. +} spi_bus_lock_dev_config_t; + +/************* Common *********************/ +/** + * Initialize a lock for an SPI bus. + * + * @param out_lock Output of the handle to the lock + * @return + * - ESP_ERR_NO_MEM: if memory exhausted + * - ESP_OK: if success + */ +esp_err_t spi_bus_init_lock(spi_bus_lock_handle_t *out_lock, const spi_bus_lock_config_t *config); + +/** + * Free the resources used by an SPI bus lock. + * + * @note All attached devices should have been unregistered before calling this + * funciton. + * + * @param lock Handle to the lock to free. + */ +void spi_bus_deinit_lock(spi_bus_lock_handle_t lock); + +/** + * @brief Get the corresponding lock according to bus id. + * + * @param host_id The bus id to get the lock + * @return The lock handle + */ +spi_bus_lock_handle_t spi_bus_lock_get_by_id(spi_host_device_t host_id); + +/** + * @brief Configure how the SPI bus lock enable the background operation. + * + * @note The lock will not try to stop the background operations, but wait for + * The background operations finished indicated by `spi_bus_lock_bg_resume_acquired_dev`. + * + * @param lock Handle to the lock to set + * @param bg_enable The enabling function + * @param bg_disable The disabling function, set to NULL if not required + * @param arg Argument to pass to the enabling/disabling function. + */ +void spi_bus_lock_set_bg_control(spi_bus_lock_handle_t lock, bg_ctrl_func_t bg_enable, + bg_ctrl_func_t bg_disable, void *arg); + +/** + * Attach a device onto an SPI bus lock. The returning handle is used to perform + * following requests for the attached device. + * + * @param lock SPI bus lock to attach + * @param out_dev_handle Output handle corresponding to the device + * @param flags requirement of the device, bitwise OR of SPI_BUS_LOCK_FLAG_* flags + * + * @return + * - ESP_ERR_NOT_SUPPORTED: if there's no hardware resources for new devices. + * - ESP_ERR_NO_MEM: if memory exhausted + * - ESP_OK: if success + */ +esp_err_t spi_bus_lock_register_dev(spi_bus_lock_handle_t lock, + spi_bus_lock_dev_config_t *config, + spi_bus_lock_dev_handle_t *out_dev_handle); + +/** + * Detach a device from its bus and free the resources used + * + * @param dev_handle Handle to the device. + */ +void spi_bus_lock_unregister_dev(spi_bus_lock_dev_handle_t dev_handle); + +/** + * @brief Get the parent bus lock of the device + * + * @param dev_handle Handle to the device to get bus lock + * @return The bus lock handle + */ +spi_bus_lock_handle_t spi_bus_lock_get_parent(spi_bus_lock_dev_handle_t dev_handle); + +/** + * @brief Get the device ID of a lock. + * + * The callers should allocate CS pins according to this ID. + * + * @param dev_handle Handle to the device to get ID + * @return ID of the device + */ +int spi_bus_lock_get_dev_id(spi_bus_lock_dev_handle_t dev_handle); + +/** + * @brief The device request to touch bus registers. Can only be called by the acquiring processor. + * + * Also check if the registers has been touched by other devices. + * + * @param dev_handle Handle to the device to operate the registers + * @return true if there has been other devices touching SPI registers. + * The caller may need to do a full-configuration. Otherwise return + * false. + */ +bool spi_bus_lock_touch(spi_bus_lock_dev_handle_t dev_handle); + +/************* Acquiring service *********************/ +/** + * Acquiring the SPI bus for exclusive use. Will also wait for the BG to finish all requests of + * this device before it returns. + * + * After successfully return, the caller becomes the acquiring processor. + * + * @note For the main flash bus, `bg_disable` will be called to disable the cache. + * + * @param dev_handle Handle to the device request for acquiring. + * @param wait Time to wait until timeout or succeed, must be `portMAX_DELAY` for now. + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: timeout is not portMAX_DELAY + */ +esp_err_t spi_bus_lock_acquire_start(spi_bus_lock_dev_handle_t dev_handle, TickType_t wait); + +/** + * Release the bus acquired. Will pass the acquiring processor to other blocked + * processors (tasks or ISR), and cause them to be unblocked or invoked. + * + * The acquiring device may also become NULL if no device is asking for acquiring. + * In this case, the BG may be invoked if there is any BG requests. + * + * If the new acquiring device has BG requests, the BG will be invoked before the + * task is resumed later after the BG finishes all requests of the new acquiring + * device. Otherwise the task of the new acquiring device will be resumed immediately. + * + * @param dev_handle Handle to the device releasing the bus. + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_STATE: the device hasn't acquired the lock yet + */ +esp_err_t spi_bus_lock_acquire_end(spi_bus_lock_dev_handle_t dev_handle); + +/** + * Get the device acquiring the bus. + * + * @note Return value is not stable as the acquiring processor may change + * when this function is called. + * + * @param lock Lock of SPI bus to get the acquiring device. + * @return The argument corresponding to the acquiring device, see + * `spi_bus_lock_register_dev`. + */ +spi_bus_lock_dev_handle_t spi_bus_lock_get_acquiring_dev(spi_bus_lock_handle_t lock); + +/************* BG (Background, for ISR or cache) service *********************/ +/** + * Call by a device to request a BG operation. + * + * Depending on the bus lock state, the BG operations may be resumed by this + * call, or pending until BG operations allowed. + * + * Cleared by `spi_bus_lock_bg_clear_req` in the BG. + * + * @param dev_handle The device requesting BG operations. + * @return always ESP_OK + */ +esp_err_t spi_bus_lock_bg_request(spi_bus_lock_dev_handle_t dev_handle); + +/** + * Wait until the ISR has finished all the BG operations for the acquiring device. + * If any `spi_bus_lock_bg_request` for this device has been called after + * `spi_bus_lock_acquire_start`, this function must be called before any operation + * in the task. + * + * @note Can only be called when bus acquired by this device. + * + * @param dev_handle Handle to the device acquiring the bus. + * @param wait Time to wait until timeout or succeed, must be `portMAX_DELAY` for now. + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_STATE: The device is not the acquiring bus. + * - ESP_ERR_INVALID_ARG: Timeout is not portMAX_DELAY. + */ +esp_err_t spi_bus_lock_wait_bg_done(spi_bus_lock_dev_handle_t dev_handle, TickType_t wait); + +/** + * Handle interrupt and closure of last operation. Should be called at the beginning of the ISR, + * when the ISR is acting as the acquiring processor. + * + * @param lock The SPI bus lock + * + * @return false if the ISR has already touched the HW, should run closure of the + * last operation first; otherwise true if the ISR just start operating + * on the HW, closure should be skipped. + */ +bool spi_bus_lock_bg_entry(spi_bus_lock_handle_t lock); + +/** + * Handle the scheduling of other acquiring devices, and control of HW operation + * status. + * + * If no BG request is found, call with `wip=false`. This function will return false, + * indicating there is incoming BG requests for the current acquiring device (or + * for all devices if there is no acquiring device) and the ISR needs retry. + * Otherwise may schedule a new acquiring processor (unblock the task) if there + * is, and return true. + * + * Otherwise if a BG request is started in this ISR, call with `wip=true` and the + * function will enable the interrupt to make the ISR be called again when the + * request is done. + * + * This function is safe and should still be called when the ISR just lost its acquiring processor + * role, but hasn't quit. + * + * @note This function will not change acquiring device. The ISR call + * `spi_bus_lock_bg_update_acquiring` to check for new acquiring device, + * when acquiring devices need to be served before other devices. + * + * @param lock The SPI bus lock. + * @param wip Whether an operation is being executed when quitting the ISR. + * @param do_yield[out] Not touched when no yielding required, otherwise set + * to pdTRUE. + * @return false if retry is required, indicating that there is pending BG request. + * otherwise true and quit ISR is allowed. + */ +bool spi_bus_lock_bg_exit(spi_bus_lock_handle_t lock, bool wip, BaseType_t* do_yield); + +/** + * Check whether there is device asking for the acquiring device, and the desired + * device for the next operation is also recommended. + * + * @note Must be called when the ISR is acting as the acquiring processor, and + * there is no acquiring device. + * + * @param lock The SPI bus lock. + * @param out_dev_lock The recommended device for hte next operation. It's the new + * acquiring device when found, otherwise a device that has active BG request. + * + * @return true if the ISR need to quit (new acquiring device has no active BG + * request, or no active BG requests for all devices when there is no + * acquiring device), otherwise false. + */ +bool spi_bus_lock_bg_check_dev_acq(spi_bus_lock_handle_t lock, spi_bus_lock_dev_handle_t *out_dev_lock); + +/** + * Check if the device has BG requests. Must be called when the ISR is acting as + * the acquiring processor. + * + * @note This is not stable, may become true again when a task request for BG + * operation (by `spi_bus_lock_bg_request`). + * + * @param dev_lock The device to check. + * @return true if the device has BG requests, otherwise false. + */ +bool spi_bus_lock_bg_check_dev_req(spi_bus_lock_dev_handle_t dev_lock); + +/** + * Clear the pending BG operation request of a device after served. Must be + * called when the ISR is acting as the acquiring processor. + * + * @note When the return value is true, the ISR will lost the acquiring processor role. Then + * `spi_bus_lock_bg_exit` must be called and checked before calling all other functions that + * require to be called when the ISR is the acquiring processor again. + * + * @param dev_handle The device whose request is served. + * @return True if no pending requests for the acquiring device, or for all devices + * if there is no acquiring device. Otherwise false. When the return value is + * true, the ISR is no longer the acquiring processor. + */ +bool spi_bus_lock_bg_clear_req(spi_bus_lock_dev_handle_t dev_lock); + +/** + * Check if there is any active BG requests. + * + * @param lock The SPI bus lock. + * @return true if any device has active BG requst, otherwise false. + */ +bool spi_bus_lock_bg_req_exist(spi_bus_lock_handle_t lock); + +/******************************************************************************* + * Variable and APIs for the OS to initialize the locks for the main chip + ******************************************************************************/ +/// The lock for the main bus +extern const spi_bus_lock_handle_t g_main_spi_bus_lock; + +/** + * @brief Initialize the main SPI bus, called during chip startup. + * + * @return always ESP_OK + */ +esp_err_t spi_bus_lock_init_main_bus(void); + +/// The lock for the main flash device +extern const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev; + +/** + * @brief Initialize the main flash device, called during chip startup. + * + * @return + * - ESP_OK: if success + * - ESP_ERR_NO_MEM: memory exhausted + */ +esp_err_t spi_bus_lock_init_main_dev(void); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/spi_master.h b/tools/sdk/esp32c3/include/driver/include/driver/spi_master.h new file mode 100644 index 00000000..e6ed8c5a --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/spi_master.h @@ -0,0 +1,392 @@ +// Copyright 2010-2019 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. + +#pragma once + +#include "esp_err.h" +#include "freertos/FreeRTOS.h" +//for spi_bus_initialization funcions. to be back-compatible +#include "driver/spi_common.h" + +/** SPI master clock is divided by 80MHz apb clock. Below defines are example frequencies, and are accurate. Be free to specify a random frequency, it will be rounded to closest frequency (to macros below if above 8MHz). + * 8MHz + */ +#define SPI_MASTER_FREQ_8M (APB_CLK_FREQ/10) +#define SPI_MASTER_FREQ_9M (APB_CLK_FREQ/9) ///< 8.89MHz +#define SPI_MASTER_FREQ_10M (APB_CLK_FREQ/8) ///< 10MHz +#define SPI_MASTER_FREQ_11M (APB_CLK_FREQ/7) ///< 11.43MHz +#define SPI_MASTER_FREQ_13M (APB_CLK_FREQ/6) ///< 13.33MHz +#define SPI_MASTER_FREQ_16M (APB_CLK_FREQ/5) ///< 16MHz +#define SPI_MASTER_FREQ_20M (APB_CLK_FREQ/4) ///< 20MHz +#define SPI_MASTER_FREQ_26M (APB_CLK_FREQ/3) ///< 26.67MHz +#define SPI_MASTER_FREQ_40M (APB_CLK_FREQ/2) ///< 40MHz +#define SPI_MASTER_FREQ_80M (APB_CLK_FREQ/1) ///< 80MHz +#ifdef __cplusplus +extern "C" +{ +#endif + +#define SPI_DEVICE_TXBIT_LSBFIRST (1<<0) ///< Transmit command/address/data LSB first instead of the default MSB first +#define SPI_DEVICE_RXBIT_LSBFIRST (1<<1) ///< Receive data LSB first instead of the default MSB first +#define SPI_DEVICE_BIT_LSBFIRST (SPI_DEVICE_TXBIT_LSBFIRST|SPI_DEVICE_RXBIT_LSBFIRST) ///< Transmit and receive LSB first +#define SPI_DEVICE_3WIRE (1<<2) ///< Use MOSI (=spid) for both sending and receiving data +#define SPI_DEVICE_POSITIVE_CS (1<<3) ///< Make CS positive during a transaction instead of negative +#define SPI_DEVICE_HALFDUPLEX (1<<4) ///< Transmit data before receiving it, instead of simultaneously +#define SPI_DEVICE_CLK_AS_CS (1<<5) ///< Output clock on CS line if CS is active +/** There are timing issue when reading at high frequency (the frequency is related to whether iomux pins are used, valid time after slave sees the clock). + * - In half-duplex mode, the driver automatically inserts dummy bits before reading phase to fix the timing issue. Set this flag to disable this feature. + * - In full-duplex mode, however, the hardware cannot use dummy bits, so there is no way to prevent data being read from getting corrupted. + * Set this flag to confirm that you're going to work with output only, or read without dummy bits at your own risk. + */ +#define SPI_DEVICE_NO_DUMMY (1<<6) +#define SPI_DEVICE_DDRCLK (1<<7) + + +typedef struct spi_transaction_t spi_transaction_t; +typedef void(*transaction_cb_t)(spi_transaction_t *trans); + +/** + * @brief This is a configuration for a SPI slave device that is connected to one of the SPI buses. + */ +typedef struct { + uint8_t command_bits; ///< Default amount of bits in command phase (0-16), used when ``SPI_TRANS_VARIABLE_CMD`` is not used, otherwise ignored. + uint8_t address_bits; ///< Default amount of bits in address phase (0-64), used when ``SPI_TRANS_VARIABLE_ADDR`` is not used, otherwise ignored. + uint8_t dummy_bits; ///< Amount of dummy bits to insert between address and data phase + uint8_t mode; /**< SPI mode, representing a pair of (CPOL, CPHA) configuration: + - 0: (0, 0) + - 1: (0, 1) + - 2: (1, 0) + - 3: (1, 1) + */ + uint16_t duty_cycle_pos; ///< Duty cycle of positive clock, in 1/256th increments (128 = 50%/50% duty). Setting this to 0 (=not setting it) is equivalent to setting this to 128. + uint16_t cs_ena_pretrans; ///< Amount of SPI bit-cycles the cs should be activated before the transmission (0-16). This only works on half-duplex transactions. + uint8_t cs_ena_posttrans; ///< Amount of SPI bit-cycles the cs should stay active after the transmission (0-16) + int clock_speed_hz; ///< Clock speed, divisors of 80MHz, in Hz. See ``SPI_MASTER_FREQ_*``. + int input_delay_ns; /**< Maximum data valid time of slave. The time required between SCLK and MISO + valid, including the possible clock delay from slave to master. The driver uses this value to give an extra + delay before the MISO is ready on the line. Leave at 0 unless you know you need a delay. For better timing + performance at high frequency (over 8MHz), it's suggest to have the right value. + */ + int spics_io_num; ///< CS GPIO pin for this device, or -1 if not used + uint32_t flags; ///< Bitwise OR of SPI_DEVICE_* flags + int queue_size; ///< Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_device_queue_trans but not yet finished using spi_device_get_trans_result) at the same time + transaction_cb_t pre_cb; /**< Callback to be called before a transmission is started. + * + * This callback is called within interrupt + * context should be in IRAM for best + * performance, see "Transferring Speed" + * section in the SPI Master documentation for + * full details. If not, the callback may crash + * during flash operation when the driver is + * initialized with ESP_INTR_FLAG_IRAM. + */ + transaction_cb_t post_cb; /**< Callback to be called after a transmission has completed. + * + * This callback is called within interrupt + * context should be in IRAM for best + * performance, see "Transferring Speed" + * section in the SPI Master documentation for + * full details. If not, the callback may crash + * during flash operation when the driver is + * initialized with ESP_INTR_FLAG_IRAM. + */ +} spi_device_interface_config_t; + + +#define SPI_TRANS_MODE_DIO (1<<0) ///< Transmit/receive data in 2-bit mode +#define SPI_TRANS_MODE_QIO (1<<1) ///< Transmit/receive data in 4-bit mode +#define SPI_TRANS_USE_RXDATA (1<<2) ///< Receive into rx_data member of spi_transaction_t instead into memory at rx_buffer. +#define SPI_TRANS_USE_TXDATA (1<<3) ///< Transmit tx_data member of spi_transaction_t instead of data at tx_buffer. Do not set tx_buffer when using this. +#define SPI_TRANS_MODE_DIOQIO_ADDR (1<<4) ///< Also transmit address in mode selected by SPI_MODE_DIO/SPI_MODE_QIO +#define SPI_TRANS_VARIABLE_CMD (1<<5) ///< Use the ``command_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``. +#define SPI_TRANS_VARIABLE_ADDR (1<<6) ///< Use the ``address_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``. +#define SPI_TRANS_VARIABLE_DUMMY (1<<7) ///< Use the ``dummy_bits`` in ``spi_transaction_ext_t`` rather than default value in ``spi_device_interface_config_t``. +#define SPI_TRANS_SET_CD (1<<7) ///< Set the CD pin + +/** + * This structure describes one SPI transaction. The descriptor should not be modified until the transaction finishes. + */ +struct spi_transaction_t { + uint32_t flags; ///< Bitwise OR of SPI_TRANS_* flags + uint16_t cmd; /**< Command data, of which the length is set in the ``command_bits`` of spi_device_interface_config_t. + * + * NOTE: this field, used to be "command" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF 3.0. + * + * Example: write 0x0123 and command_bits=12 to send command 0x12, 0x3_ (in previous version, you may have to write 0x3_12). + */ + uint64_t addr; /**< Address data, of which the length is set in the ``address_bits`` of spi_device_interface_config_t. + * + * NOTE: this field, used to be "address" in ESP-IDF 2.1 and before, is re-written to be used in a new way in ESP-IDF3.0. + * + * Example: write 0x123400 and address_bits=24 to send address of 0x12, 0x34, 0x00 (in previous version, you may have to write 0x12340000). + */ + size_t length; ///< Total data length, in bits + size_t rxlength; ///< Total data length received, should be not greater than ``length`` in full-duplex mode (0 defaults this to the value of ``length``). + void *user; ///< User-defined variable. Can be used to store eg transaction ID. + union { + const void *tx_buffer; ///< Pointer to transmit buffer, or NULL for no MOSI phase + uint8_t tx_data[4]; ///< If SPI_TRANS_USE_TXDATA is set, data set here is sent directly from this variable. + }; + union { + void *rx_buffer; ///< Pointer to receive buffer, or NULL for no MISO phase. Written by 4 bytes-unit if DMA is used. + uint8_t rx_data[4]; ///< If SPI_TRANS_USE_RXDATA is set, data is received directly to this variable + }; +} ; //the rx data should start from a 32-bit aligned address to get around dma issue. + +/** + * This struct is for SPI transactions which may change their address and command length. + * Please do set the flags in base to ``SPI_TRANS_VARIABLE_CMD_ADR`` to use the bit length here. + */ +typedef struct { + struct spi_transaction_t base; ///< Transaction data, so that pointer to spi_transaction_t can be converted into spi_transaction_ext_t + uint8_t command_bits; ///< The command length in this transaction, in bits. + uint8_t address_bits; ///< The address length in this transaction, in bits. + uint8_t dummy_bits; ///< The dummy length in this transaction, in bits. +} spi_transaction_ext_t ; + + +typedef struct spi_device_t* spi_device_handle_t; ///< Handle for a device on a SPI bus +/** + * @brief Allocate a device on a SPI bus + * + * This initializes the internal structures for a device, plus allocates a CS pin on the indicated SPI master + * peripheral and routes it to the indicated GPIO. All SPI master devices have three CS pins and can thus control + * up to three devices. + * + * @note While in general, speeds up to 80MHz on the dedicated SPI pins and 40MHz on GPIO-matrix-routed pins are + * supported, full-duplex transfers routed over the GPIO matrix only support speeds up to 26MHz. + * + * @param host_id SPI peripheral to allocate device on + * @param dev_config SPI interface protocol config for the device + * @param handle Pointer to variable to hold the device handle + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_NOT_FOUND if host doesn't have any free CS slots + * - ESP_ERR_NO_MEM if out of memory + * - ESP_OK on success + */ +esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle); + + +/** + * @brief Remove a device from the SPI bus + * + * @param handle Device handle to free + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_INVALID_STATE if device already is freed + * - ESP_OK on success + */ +esp_err_t spi_bus_remove_device(spi_device_handle_t handle); + + +/** + * @brief Queue a SPI transaction for interrupt transaction execution. Get the result by ``spi_device_get_trans_result``. + * + * @note Normally a device cannot start (queue) polling and interrupt + * transactions simultaneously. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param trans_desc Description of transaction to execute + * @param ticks_to_wait Ticks to wait until there's room in the queue; use portMAX_DELAY to + * never time out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_TIMEOUT if there was no room in the queue before ticks_to_wait expired + * - ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed + * - ESP_ERR_INVALID_STATE if previous transactions are not finished + * - ESP_OK on success + */ +esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait); + + +/** + * @brief Get the result of a SPI transaction queued earlier by ``spi_device_queue_trans``. + * + * This routine will wait until a transaction to the given device + * succesfully completed. It will then return the description of the + * completed transaction so software can inspect the result and e.g. free the memory or + * re-use the buffers. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param trans_desc Pointer to variable able to contain a pointer to the description of the transaction + that is executed. The descriptor should not be modified until the descriptor is returned by + spi_device_get_trans_result. + * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time + out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_TIMEOUT if there was no completed transaction before ticks_to_wait expired + * - ESP_OK on success + */ +esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait); + + +/** + * @brief Send a SPI transaction, wait for it to complete, and return the result + * + * This function is the equivalent of calling spi_device_queue_trans() followed by spi_device_get_trans_result(). + * Do not use this when there is still a transaction separately queued (started) from spi_device_queue_trans() or polling_start/transmit that hasn't been finalized. + * + * @note This function is not thread safe when multiple tasks access the same SPI device. + * Normally a device cannot start (queue) polling and interrupt + * transactions simutanuously. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param trans_desc Description of transaction to execute + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc); + + +/** + * @brief Immediately start a polling transaction. + * + * @note Normally a device cannot start (queue) polling and interrupt + * transactions simutanuously. Moreover, a device cannot start a new polling + * transaction if another polling transaction is not finished. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param trans_desc Description of transaction to execute + * @param ticks_to_wait Ticks to wait until there's room in the queue; + * currently only portMAX_DELAY is supported. + * + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_TIMEOUT if the device cannot get control of the bus before ``ticks_to_wait`` expired + * - ESP_ERR_NO_MEM if allocating DMA-capable temporary buffer failed + * - ESP_ERR_INVALID_STATE if previous transactions are not finished + * - ESP_OK on success + */ +esp_err_t spi_device_polling_start(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait); + + +/** + * @brief Poll until the polling transaction ends. + * + * This routine will not return until the transaction to the given device has + * succesfully completed. The task is not blocked, but actively busy-spins for + * the transaction to be completed. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time + out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_TIMEOUT if the transaction cannot finish before ticks_to_wait expired + * - ESP_OK on success + */ +esp_err_t spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait); + + +/** + * @brief Send a polling transaction, wait for it to complete, and return the result + * + * This function is the equivalent of calling spi_device_polling_start() followed by spi_device_polling_end(). + * Do not use this when there is still a transaction that hasn't been finalized. + * + * @note This function is not thread safe when multiple tasks access the same SPI device. + * Normally a device cannot start (queue) polling and interrupt + * transactions simutanuously. + * + * @param handle Device handle obtained using spi_host_add_dev + * @param trans_desc Description of transaction to execute + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc); + + +/** + * @brief Occupy the SPI bus for a device to do continuous transactions. + * + * Transactions to all other devices will be put off until ``spi_device_release_bus`` is called. + * + * @note The function will wait until all the existing transactions have been sent. + * + * @param device The device to occupy the bus. + * @param wait Time to wait before the the bus is occupied by the device. Currently MUST set to portMAX_DELAY. + * + * @return + * - ESP_ERR_INVALID_ARG : ``wait`` is not set to portMAX_DELAY. + * - ESP_OK : Success. + */ +esp_err_t spi_device_acquire_bus(spi_device_handle_t device, TickType_t wait); + +/** + * @brief Release the SPI bus occupied by the device. All other devices can start sending transactions. + * + * @param dev The device to release the bus. + */ +void spi_device_release_bus(spi_device_handle_t dev); + + +/** + * @brief Calculate the working frequency that is most close to desired frequency, and also the register value. + * + * @param fapb The frequency of apb clock, should be ``APB_CLK_FREQ``. + * @param hz Desired working frequency + * @param duty_cycle Duty cycle of the spi clock + * @param reg_o Output of value to be set in clock register, or NULL if not needed. + * + * @deprecated The app shouldn't care about the register. Call ``spi_get_actual_clock`` instead. + * + * @return Actual working frequency that most fit. + */ +int spi_cal_clock(int fapb, int hz, int duty_cycle, uint32_t* reg_o) __attribute__((deprecated)); + +/** + * @brief Calculate the working frequency that is most close to desired frequency. + * + * @param fapb The frequency of apb clock, should be ``APB_CLK_FREQ``. + * @param hz Desired working frequency + * @param duty_cycle Duty cycle of the spi clock + * + * @return Actual working frequency that most fit. + */ +int spi_get_actual_clock(int fapb, int hz, int duty_cycle); + +/** + * @brief Calculate the timing settings of specified frequency and settings. + * + * @param gpio_is_used True if using GPIO matrix, or False if iomux pins are used. + * @param input_delay_ns Input delay from SCLK launch edge to MISO data valid. + * @param eff_clk Effective clock frequency (in Hz) from spi_cal_clock. + * @param dummy_o Address of dummy bits used output. Set to NULL if not needed. + * @param cycles_remain_o Address of cycles remaining (after dummy bits are used) output. + * - -1 If too many cycles remaining, suggest to compensate half a clock. + * - 0 If no remaining cycles or dummy bits are not used. + * - positive value: cycles suggest to compensate. + * + * @note If **dummy_o* is not zero, it means dummy bits should be applied in half duplex mode, and full duplex mode may not work. + */ +void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int* dummy_o, int* cycles_remain_o); + +/** + * @brief Get the frequency limit of current configurations. + * SPI master working at this limit is OK, while above the limit, full duplex mode and DMA will not work, + * and dummy bits will be aplied in the half duplex mode. + * + * @param gpio_is_used True if using GPIO matrix, or False if native pins are used. + * @param input_delay_ns Input delay from SCLK launch edge to MISO data valid. + * @return Frequency limit of current configurations. + */ +int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/spi_slave.h b/tools/sdk/esp32c3/include/driver/include/driver/spi_slave.h new file mode 100644 index 00000000..a970159f --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/spi_slave.h @@ -0,0 +1,198 @@ +// Copyright 2010-2018 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. + + +#ifndef _DRIVER_SPI_SLAVE_H_ +#define _DRIVER_SPI_SLAVE_H_ + +#include "esp_err.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "driver/spi_common.h" + + +#ifdef __cplusplus +extern "C" +{ +#endif + + +#define SPI_SLAVE_TXBIT_LSBFIRST (1<<0) ///< Transmit command/address/data LSB first instead of the default MSB first +#define SPI_SLAVE_RXBIT_LSBFIRST (1<<1) ///< Receive data LSB first instead of the default MSB first +#define SPI_SLAVE_BIT_LSBFIRST (SPI_SLAVE_TXBIT_LSBFIRST|SPI_SLAVE_RXBIT_LSBFIRST) ///< Transmit and receive LSB first + + +typedef struct spi_slave_transaction_t spi_slave_transaction_t; +typedef void(*slave_transaction_cb_t)(spi_slave_transaction_t *trans); + +/** + * @brief This is a configuration for a SPI host acting as a slave device. + */ +typedef struct { + int spics_io_num; ///< CS GPIO pin for this device + uint32_t flags; ///< Bitwise OR of SPI_SLAVE_* flags + int queue_size; ///< Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_slave_queue_trans but not yet finished using spi_slave_get_trans_result) at the same time + uint8_t mode; /**< SPI mode, representing a pair of (CPOL, CPHA) configuration: + - 0: (0, 0) + - 1: (0, 1) + - 2: (1, 0) + - 3: (1, 1) + */ + slave_transaction_cb_t post_setup_cb; /**< Callback called after the SPI registers are loaded with new data. + * + * This callback is called within interrupt + * context should be in IRAM for best + * performance, see "Transferring Speed" + * section in the SPI Master documentation for + * full details. If not, the callback may crash + * during flash operation when the driver is + * initialized with ESP_INTR_FLAG_IRAM. + */ + slave_transaction_cb_t post_trans_cb; /**< Callback called after a transaction is done. + * + * This callback is called within interrupt + * context should be in IRAM for best + * performance, see "Transferring Speed" + * section in the SPI Master documentation for + * full details. If not, the callback may crash + * during flash operation when the driver is + * initialized with ESP_INTR_FLAG_IRAM. + */ +} spi_slave_interface_config_t; + +/** + * This structure describes one SPI transaction + */ +struct spi_slave_transaction_t { + size_t length; ///< Total data length, in bits + size_t trans_len; ///< Transaction data length, in bits + const void *tx_buffer; ///< Pointer to transmit buffer, or NULL for no MOSI phase + void *rx_buffer; /**< Pointer to receive buffer, or NULL for no MISO phase. + * When the DMA is anabled, must start at WORD boundary (``rx_buffer%4==0``), + * and has length of a multiple of 4 bytes. + */ + void *user; ///< User-defined variable. Can be used to store eg transaction ID. +}; + +/** + * @brief Initialize a SPI bus as a slave interface + * + * @warning For now, only supports HSPI and VSPI. + * + * @param host SPI peripheral to use as a SPI slave interface + * @param bus_config Pointer to a spi_bus_config_t struct specifying how the host should be initialized + * @param slave_config Pointer to a spi_slave_interface_config_t struct specifying the details for the slave interface + * @param dma_chan - Selecting a DMA channel for an SPI bus allows transactions on the bus with size only limited by the amount of internal memory. + * - Selecting SPI_DMA_DISABLED limits the size of transactions. + * - Set to SPI_DMA_DISABLED if only the SPI flash uses this bus. + * - Set to SPI_DMA_CH_AUTO to let the driver to allocate the DMA channel. + * + * @warning If a DMA channel is selected, any transmit and receive buffer used should be allocated in + * DMA-capable memory. + * + * @warning The ISR of SPI is always executed on the core which calls this + * function. Never starve the ISR on this core or the SPI transactions will not + * be handled. + * + * @return + * - ESP_ERR_INVALID_ARG if configuration is invalid + * - ESP_ERR_INVALID_STATE if host already is in use + * - ESP_ERR_NOT_FOUND if there is no available DMA channel + * - ESP_ERR_NO_MEM if out of memory + * - ESP_OK on success + */ +esp_err_t spi_slave_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, const spi_slave_interface_config_t *slave_config, spi_dma_chan_t dma_chan); + +/** + * @brief Free a SPI bus claimed as a SPI slave interface + * + * @param host SPI peripheral to free + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_ERR_INVALID_STATE if not all devices on the bus are freed + * - ESP_OK on success + */ +esp_err_t spi_slave_free(spi_host_device_t host); + + +/** + * @brief Queue a SPI transaction for execution + * + * Queues a SPI transaction to be executed by this slave device. (The transaction queue size was specified when the slave + * device was initialised via spi_slave_initialize.) This function may block if the queue is full (depending on the + * ticks_to_wait parameter). No SPI operation is directly initiated by this function, the next queued transaction + * will happen when the master initiates a SPI transaction by pulling down CS and sending out clock signals. + * + * This function hands over ownership of the buffers in ``trans_desc`` to the SPI slave driver; the application is + * not to access this memory until ``spi_slave_queue_trans`` is called to hand ownership back to the application. + * + * @param host SPI peripheral that is acting as a slave + * @param trans_desc Description of transaction to execute. Not const because we may want to write status back + * into the transaction description. + * @param ticks_to_wait Ticks to wait until there's room in the queue; use portMAX_DELAY to + * never time out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spi_slave_queue_trans(spi_host_device_t host, const spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait); + + +/** + * @brief Get the result of a SPI transaction queued earlier + * + * This routine will wait until a transaction to the given device (queued earlier with + * spi_slave_queue_trans) has succesfully completed. It will then return the description of the + * completed transaction so software can inspect the result and e.g. free the memory or + * re-use the buffers. + * + * It is mandatory to eventually use this function for any transaction queued by ``spi_slave_queue_trans``. + * + * @param host SPI peripheral to that is acting as a slave + * @param[out] trans_desc Pointer to variable able to contain a pointer to the description of the + * transaction that is executed + * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time + * out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spi_slave_get_trans_result(spi_host_device_t host, spi_slave_transaction_t **trans_desc, TickType_t ticks_to_wait); + + +/** + * @brief Do a SPI transaction + * + * Essentially does the same as spi_slave_queue_trans followed by spi_slave_get_trans_result. Do + * not use this when there is still a transaction queued that hasn't been finalized + * using spi_slave_get_trans_result. + * + * @param host SPI peripheral to that is acting as a slave + * @param trans_desc Pointer to variable able to contain a pointer to the description of the + * transaction that is executed. Not const because we may want to write status back + * into the transaction description. + * @param ticks_to_wait Ticks to wait until there's a returned item; use portMAX_DELAY to never time + * out. + * @return + * - ESP_ERR_INVALID_ARG if parameter is invalid + * - ESP_OK on success + */ +esp_err_t spi_slave_transmit(spi_host_device_t host, spi_slave_transaction_t *trans_desc, TickType_t ticks_to_wait); + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/spi_slave_hd.h b/tools/sdk/esp32c3/include/driver/include/driver/spi_slave_hd.h new file mode 100644 index 00000000..7e9289fb --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/spi_slave_hd.h @@ -0,0 +1,214 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include "esp_types.h" +#include "soc/soc_caps.h" +#include "freertos/FreeRTOS.h" + +#include "hal/spi_types.h" +#include "driver/spi_common.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !SOC_SPI_SUPPORT_SLAVE_HD_VER2 && !CI_HEADER_CHECK +#error The SPI peripheral does not support this feature +#endif + +/// Descriptor of data to send/receive +typedef struct { + uint8_t* data; ///< Buffer to send, must be DMA capable + size_t len; ///< Len of data to send/receive. For receiving the buffer length should be multiples of 4 bytes, otherwise the extra part will be truncated. + size_t trans_len; ///< For RX direction, it indicates the data actually received. For TX direction, it is meaningless. + void* arg; ///< Extra argument indiciating this data +} spi_slave_hd_data_t; + +/// Information of SPI Slave HD event +typedef struct { + spi_event_t event; ///< Event type + spi_slave_hd_data_t* trans; ///< Corresponding transaction for SPI_EV_SEND and SPI_EV_RECV events +} spi_slave_hd_event_t; + +/// Callback for SPI Slave HD +typedef bool (*slave_cb_t)(void* arg, spi_slave_hd_event_t* event, BaseType_t* awoken); + +/// Channel of SPI Slave HD to do data transaction +typedef enum { + SPI_SLAVE_CHAN_TX = 0, ///< The output channel (RDDMA) + SPI_SLAVE_CHAN_RX = 1, ///< The input channel (WRDMA) +} spi_slave_chan_t; + +/// Callback configuration structure for SPI Slave HD +typedef struct { + slave_cb_t cb_buffer_tx; ///< Callback when master reads from shared buffer + slave_cb_t cb_buffer_rx; ///< Callback when master writes to shared buffer + slave_cb_t cb_sent; ///< Callback when data are sent + slave_cb_t cb_recv; ///< Callback when data are received + slave_cb_t cb_cmd9; ///< Callback when CMD9 received + slave_cb_t cb_cmdA; ///< Callback when CMDA received + void* arg; ///< Argument indicating this SPI Slave HD peripheral instance +} spi_slave_hd_callback_config_t; + + +//flags for ``spi_slave_hd_slot_config_t`` to use +#define SPI_SLAVE_HD_TXBIT_LSBFIRST (1<<0) ///< Transmit command/address/data LSB first instead of the default MSB first +#define SPI_SLAVE_HD_RXBIT_LSBFIRST (1<<1) ///< Receive data LSB first instead of the default MSB first +#define SPI_SLAVE_HD_BIT_LSBFIRST (SPI_SLAVE_HD_TXBIT_LSBFIRST|SPI_SLAVE_HD_RXBIT_LSBFIRST) ///< Transmit and receive LSB first +#define SPI_SLAVE_HD_APPEND_MODE (1<<2) ///< Adopt DMA append mode for transactions. In this mode, users can load(append) DMA descriptors without stopping the DMA + +/// Configuration structure for the SPI Slave HD driver +typedef struct { + uint8_t mode; /**< SPI mode, representing a pair of (CPOL, CPHA) configuration: + - 0: (0, 0) + - 1: (0, 1) + - 2: (1, 0) + - 3: (1, 1) + */ + uint32_t spics_io_num; ///< CS GPIO pin for this device + uint32_t flags; ///< Bitwise OR of SPI_SLAVE_HD_* flags + uint32_t command_bits; ///< command field bits, multiples of 8 and at least 8. + uint32_t address_bits; ///< address field bits, multiples of 8 and at least 8. + uint32_t dummy_bits; ///< dummy field bits, multiples of 8 and at least 8. + uint32_t queue_size; ///< Transaction queue size. This sets how many transactions can be 'in the air' (queued using spi_slave_hd_queue_trans but not yet finished using spi_slave_hd_get_trans_result) at the same time + spi_dma_chan_t dma_chan; ///< DMA channel to used. + spi_slave_hd_callback_config_t cb_config; ///< Callback configuration +} spi_slave_hd_slot_config_t; + +/** + * @brief Initialize the SPI Slave HD driver. + * + * @param host_id The host to use + * @param bus_config Bus configuration for the bus used + * @param config Configuration for the SPI Slave HD driver + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: invalid argument given + * - ESP_ERR_INVALID_STATE: function called in invalid state, may be some resources are already in use + * - ESP_ERR_NOT_FOUND if there is no available DMA channel + * - ESP_ERR_NO_MEM: memory allocation failed + * - or other return value from `esp_intr_alloc` + */ +esp_err_t spi_slave_hd_init(spi_host_device_t host_id, const spi_bus_config_t *bus_config, + const spi_slave_hd_slot_config_t *config); + +/** + * @brief Deinitialize the SPI Slave HD driver + * + * @param host_id The host to deinitialize the driver + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: if the host_id is not correct + */ +esp_err_t spi_slave_hd_deinit(spi_host_device_t host_id); + +/** + * @brief Queue transactions (segment mode) + * + * @param host_id Host to queue the transaction + * @param chan SPI_SLAVE_CHAN_TX or SPI_SLAVE_CHAN_RX + * @param trans Transaction descriptors + * @param timeout Timeout before the data is queued + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: The input argument is invalid. Can be the following reason: + * - The buffer given is not DMA capable + * - The length of data is invalid (not larger than 0, or exceed the max transfer length) + * - The transaction direction is invalid + * - ESP_ERR_TIMEOUT: Cannot queue the data before timeout. Master is still processing previous transaction. + * - ESP_ERR_INVALID_STATE: Function called in invalid state. This API should be called under segment mode. + */ +esp_err_t spi_slave_hd_queue_trans(spi_host_device_t host_id, spi_slave_chan_t chan, spi_slave_hd_data_t* trans, TickType_t timeout); + +/** + * @brief Get the result of a data transaction (segment mode) + * + * @note This API should be called successfully the same times as the ``spi_slave_hd_queue_trans``. + * + * @param host_id Host to queue the transaction + * @param chan Channel to get the result, SPI_SLAVE_CHAN_TX or SPI_SLAVE_CHAN_RX + * @param[out] out_trans Pointer to the transaction descriptor (``spi_slave_hd_data_t``) passed to the driver before. Hardware has finished this transaction. Member ``trans_len`` indicates the actual number of bytes of received data, it's meaningless for TX. + * @param timeout Timeout before the result is got + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: Function is not valid + * - ESP_ERR_TIMEOUT: There's no transaction done before timeout + * - ESP_ERR_INVALID_STATE: Function called in invalid state. This API should be called under segment mode. + */ +esp_err_t spi_slave_hd_get_trans_res(spi_host_device_t host_id, spi_slave_chan_t chan, spi_slave_hd_data_t **out_trans, TickType_t timeout); + +/** + * @brief Read the shared registers + * + * @param host_id Host to read the shared registers + * @param addr Address of register to read, 0 to ``SOC_SPI_MAXIMUM_BUFFER_SIZE-1`` + * @param[out] out_data Output buffer to store the read data + * @param len Length to read, not larger than ``SOC_SPI_MAXIMUM_BUFFER_SIZE-addr`` + */ +void spi_slave_hd_read_buffer(spi_host_device_t host_id, int addr, uint8_t *out_data, size_t len); + +/** + * @brief Write the shared registers + * + * @param host_id Host to write the shared registers + * @param addr Address of register to write, 0 to ``SOC_SPI_MAXIMUM_BUFFER_SIZE-1`` + * @param data Buffer holding the data to write + * @param len Length to write, ``SOC_SPI_MAXIMUM_BUFFER_SIZE-addr`` + */ +void spi_slave_hd_write_buffer(spi_host_device_t host_id, int addr, uint8_t *data, size_t len); + +/** + * @brief Load transactions (append mode) + * + * @note In this mode, user transaction descriptors will be appended to the DMA and the DMA will keep processing the data without stopping + * + * @param host_id Host to load transactions + * @param chan SPI_SLAVE_CHAN_TX or SPI_SLAVE_CHAN_RX + * @param trans Transaction descriptor + * @param timeout Timeout before the transaction is loaded + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: The input argument is invalid. Can be the following reason: + * - The buffer given is not DMA capable + * - The length of data is invalid (not larger than 0, or exceed the max transfer length) + * - The transaction direction is invalid + * - ESP_ERR_TIMEOUT: Master is still processing previous transaction. There is no available transaction for slave to load + * - ESP_ERR_INVALID_STATE: Function called in invalid state. This API should be called under append mode. + */ +esp_err_t spi_slave_hd_append_trans(spi_host_device_t host_id, spi_slave_chan_t chan, spi_slave_hd_data_t *trans, TickType_t timeout); + +/** + * @brief Get the result of a data transaction (append mode) + * + * @note This API should be called the same times as the ``spi_slave_hd_append_trans`` + * + * @param host_id Host to load the transaction + * @param chan SPI_SLAVE_CHAN_TX or SPI_SLAVE_CHAN_RX + * @param[out] out_trans Pointer to the transaction descriptor (``spi_slave_hd_data_t``) passed to the driver before. Hardware has finished this transaction. Member ``trans_len`` indicates the actual number of bytes of received data, it's meaningless for TX. + * @param timeout Timeout before the result is got + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: Function is not valid + * - ESP_ERR_TIMEOUT: There's no transaction done before timeout + * - ESP_ERR_INVALID_STATE: Function called in invalid state. This API should be called under append mode. + */ +esp_err_t spi_slave_hd_get_append_trans_res(spi_host_device_t host_id, spi_slave_chan_t chan, spi_slave_hd_data_t **out_trans, TickType_t timeout); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/timer.h b/tools/sdk/esp32c3/include/driver/include/driver/timer.h new file mode 100644 index 00000000..1a4c074a --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/timer.h @@ -0,0 +1,456 @@ +// Copyright 2010-2019 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. + +#pragma once + +#include "esp_err.h" +#include "esp_attr.h" +#include "soc/soc.h" +#include "soc/timer_periph.h" +#include "esp_intr_alloc.h" +#include "hal/timer_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define TIMER_BASE_CLK (APB_CLK_FREQ) /*!< Frequency of the clock on the input of the timer groups */ + +/** + * @brief Interrupt handle callback function. User need to retrun a bool value + * in callback. + * + * @return + * - True Do task yield at the end of ISR + * - False Not do task yield at the end of ISR + * + * @note If you called FreeRTOS functions in callback, you need to return true or false based on + * the retrun value of argument `pxHigherPriorityTaskWoken`. + * For example, `xQueueSendFromISR` is called in callback, if the return value `pxHigherPriorityTaskWoken` + * of any FreeRTOS calls is pdTRUE, return true; otherwise return false. + */ +typedef bool (*timer_isr_t)(void *); + +/** + * @brief Interrupt handle, used in order to free the isr after use. + * Aliases to an int handle for now. + */ +typedef intr_handle_t timer_isr_handle_t; + +/** + * @brief Read the counter value of hardware timer. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param timer_val Pointer to accept timer counter value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_get_counter_value(timer_group_t group_num, timer_idx_t timer_num, uint64_t *timer_val); + +/** + * @brief Read the counter value of hardware timer, in unit of a given scale. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param time Pointer, type of double*, to accept timer counter value, in seconds. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_get_counter_time_sec(timer_group_t group_num, timer_idx_t timer_num, double *time); + +/** + * @brief Set counter value to hardware timer. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param load_val Counter value to write to the hardware timer. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_counter_value(timer_group_t group_num, timer_idx_t timer_num, uint64_t load_val); + +/** + * @brief Start the counter of hardware timer. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_start(timer_group_t group_num, timer_idx_t timer_num); + +/** + * @brief Pause the counter of hardware timer. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_pause(timer_group_t group_num, timer_idx_t timer_num); + +/** + * @brief Set counting mode for hardware timer. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param counter_dir Counting direction of timer, count-up or count-down + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_counter_mode(timer_group_t group_num, timer_idx_t timer_num, timer_count_dir_t counter_dir); + +/** + * @brief Enable or disable counter reload function when alarm event occurs. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param reload Counter reload mode. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_auto_reload(timer_group_t group_num, timer_idx_t timer_num, timer_autoreload_t reload); + +/** + * @brief Set hardware timer source clock divider. Timer groups clock are divider from APB clock. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param divider Timer clock divider value. The divider's range is from from 2 to 65536. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_divider(timer_group_t group_num, timer_idx_t timer_num, uint32_t divider); + +/** + * @brief Set timer alarm value. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param alarm_value A 64-bit value to set the alarm value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_alarm_value(timer_group_t group_num, timer_idx_t timer_num, uint64_t alarm_value); + +/** + * @brief Get timer alarm value. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param alarm_value Pointer of A 64-bit value to accept the alarm value. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_get_alarm_value(timer_group_t group_num, timer_idx_t timer_num, uint64_t *alarm_value); + +/** + * @brief Enable or disable generation of timer alarm events. + * + * @param group_num Timer group, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param alarm_en To enable or disable timer alarm function. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_set_alarm(timer_group_t group_num, timer_idx_t timer_num, timer_alarm_t alarm_en); + +/** + * @brief Add ISR handle callback for the corresponding timer. + * + * @param group_num Timer group number + * @param timer_num Timer index of timer group + * @param isr_handler Interrupt handler function, it is a callback function. + * @param arg Parameter for handler function + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * + * @note This ISR handler will be called from an ISR. + * This ISR handler do not need to handle interrupt status, and should be kept short. + * If you want to realize some specific applications or write the whole ISR, you can + * call timer_isr_register(...) to register ISR. + * + * The callback should return a bool value to determine whether need to do YIELD at + * the end of the ISR. + * + * If the intr_alloc_flags value ESP_INTR_FLAG_IRAM is set, + * the handler function must be declared with IRAM_ATTR attribute + * and can only call functions in IRAM or ROM. It cannot call other timer APIs. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_isr_callback_add(timer_group_t group_num, timer_idx_t timer_num, timer_isr_t isr_handler, void *arg, int intr_alloc_flags); + +/** + * @brief Remove ISR handle callback for the corresponding timer. + * + * @param group_num Timer group number + * @param timer_num Timer index of timer group + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_isr_callback_remove(timer_group_t group_num, timer_idx_t timer_num); + +/** + * @brief Register Timer interrupt handler, the handler is an ISR. + * The handler will be attached to the same CPU core that this function is running on. + * + * @param group_num Timer group number + * @param timer_num Timer index of timer group + * @param fn Interrupt handler function. + * @param arg Parameter for handler function + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @param handle Pointer to return handle. If non-NULL, a handle for the interrupt will + * be returned here. + * + * @note If use this function to reigster ISR, you need to write the whole ISR. + * In the interrupt handler, you need to call timer_spinlock_take(..) before + * your handling, and call timer_spinlock_give(...) after your handling. + * + * If the intr_alloc_flags value ESP_INTR_FLAG_IRAM is set, + * the handler function must be declared with IRAM_ATTR attribute + * and can only call functions in IRAM or ROM. It cannot call other timer APIs. + * Use direct register access to configure timers from inside the ISR in this case. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_isr_register(timer_group_t group_num, timer_idx_t timer_num, void (*fn)(void *), void *arg, int intr_alloc_flags, timer_isr_handle_t *handle); + +/** @brief Initializes and configure the timer. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param config Pointer to timer initialization parameters. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_init(timer_group_t group_num, timer_idx_t timer_num, const timer_config_t *config); + +/** @brief Deinitializes the timer. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_deinit(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Get timer configure value. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index, 0 for hw_timer[0] & 1 for hw_timer[1] + * @param config Pointer of struct to accept timer parameters. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_get_config(timer_group_t group_num, timer_idx_t timer_num, timer_config_t *config); + +/** @brief Enable timer group interrupt, by enable mask + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param intr_mask Timer interrupt enable mask. + * - TIMER_INTR_T0: t0 interrupt + * - TIMER_INTR_T1: t1 interrupt + * - TIMER_INTR_WDT: watchdog interrupt + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_group_intr_enable(timer_group_t group_num, timer_intr_t intr_mask); + +/** @brief Disable timer group interrupt, by disable mask + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param intr_mask Timer interrupt disable mask. + * - TIMER_INTR_T0: t0 interrupt + * - TIMER_INTR_T1: t1 interrupt + * - TIMER_INTR_WDT: watchdog interrupt + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_group_intr_disable(timer_group_t group_num, timer_intr_t intr_mask); + +/** @brief Enable timer interrupt + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_enable_intr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Disable timer interrupt + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_disable_intr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Clear timer interrupt status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + */ +void timer_group_intr_clr_in_isr(timer_group_t group_num, timer_idx_t timer_num) __attribute__((deprecated)); + +/** @brief Clear timer interrupt status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + */ +void timer_group_clr_intr_status_in_isr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Enable alarm interrupt, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + */ +void timer_group_enable_alarm_in_isr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Get the current counter value, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * + * @return + * - Counter value + */ +uint64_t timer_group_get_counter_value_in_isr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Set the alarm threshold for the timer, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * @param alarm_val Alarm threshold. + * + */ +void timer_group_set_alarm_value_in_isr(timer_group_t group_num, timer_idx_t timer_num, uint64_t alarm_val); + +/** @brief Enable/disable a counter, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index. + * @param counter_en Enable/disable. + * + */ +void timer_group_set_counter_enable_in_isr(timer_group_t group_num, timer_idx_t timer_num, timer_start_t counter_en); + +/** @brief Get the masked interrupt status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * + * @return + * - Interrupt status + */ +timer_intr_t timer_group_intr_get_in_isr(timer_group_t group_num) __attribute__((deprecated)); + +/** @brief Get interrupt status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * + * @return + * - Interrupt status + */ +uint32_t timer_group_get_intr_status_in_isr(timer_group_t group_num); + +/** @brief Clear the masked interrupt status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param intr_mask Masked interrupt. + * + */ +void timer_group_clr_intr_sta_in_isr(timer_group_t group_num, timer_intr_t intr_mask) __attribute__((deprecated)); + +/** @brief Get auto reload enable status, just used in ISR + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param timer_num Timer index + * + * @return + * - True Auto reload enabled + * - False Auto reload disabled + */ +bool timer_group_get_auto_reload_in_isr(timer_group_t group_num, timer_idx_t timer_num); + +/** @brief Take timer spinlock to enter critical protect + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_spinlock_take(timer_group_t group_num); + +/** @brief Give timer spinlock to exit critical protect + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t timer_spinlock_give(timer_group_t group_num); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/touch_pad.h b/tools/sdk/esp32c3/include/driver/include/driver/touch_pad.h new file mode 100644 index 00000000..4b7a021f --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/touch_pad.h @@ -0,0 +1,17 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include "driver/touch_sensor.h" diff --git a/tools/sdk/esp32c3/include/driver/include/driver/touch_sensor_common.h b/tools/sdk/esp32c3/include/driver/include/driver/touch_sensor_common.h new file mode 100644 index 00000000..f9855bc9 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/touch_sensor_common.h @@ -0,0 +1,171 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include "esp_err.h" +#include "esp_intr_alloc.h" +#include "hal/touch_sensor_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize touch module. + * @note If default parameter don't match the usage scenario, it can be changed after this function. + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Touch pad init error + * - ESP_ERR_NOT_SUPPORTED Touch pad is providing current to external XTAL + */ +esp_err_t touch_pad_init(void); + +/** + * @brief Un-install touch pad driver. + * @note After this function is called, other touch functions are prohibited from being called. + * @return + * - ESP_OK Success + * - ESP_FAIL Touch pad driver not initialized + */ +esp_err_t touch_pad_deinit(void); + +/** + * @brief Initialize touch pad GPIO + * @param touch_num touch pad index + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if argument is wrong + */ +esp_err_t touch_pad_io_init(touch_pad_t touch_num); + +/** + * @brief Set touch sensor high voltage threshold of chanrge. + * The touch sensor measures the channel capacitance value by charging and discharging the channel. + * So the high threshold should be less than the supply voltage. + * @param refh the value of DREFH + * @param refl the value of DREFL + * @param atten the attenuation on DREFH + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if argument is wrong + */ +esp_err_t touch_pad_set_voltage(touch_high_volt_t refh, touch_low_volt_t refl, touch_volt_atten_t atten); + +/** + * @brief Get touch sensor reference voltage, + * @param refh pointer to accept DREFH value + * @param refl pointer to accept DREFL value + * @param atten pointer to accept the attenuation on DREFH + * @return + * - ESP_OK on success + */ +esp_err_t touch_pad_get_voltage(touch_high_volt_t *refh, touch_low_volt_t *refl, touch_volt_atten_t *atten); + +/** + * @brief Set touch sensor charge/discharge speed for each pad. + * If the slope is 0, the counter would always be zero. + * If the slope is 1, the charging and discharging would be slow, accordingly. + * If the slope is set 7, which is the maximum value, the charging and discharging would be fast. + * @note The higher the charge and discharge current, the greater the immunity of the touch channel, + * but it will increase the system power consumption. + * @param touch_num touch pad index + * @param slope touch pad charge/discharge speed + * @param opt the initial voltage + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if argument is wrong + */ +esp_err_t touch_pad_set_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t slope, touch_tie_opt_t opt); + +/** + * @brief Get touch sensor charge/discharge speed for each pad + * @param touch_num touch pad index + * @param slope pointer to accept touch pad charge/discharge slope + * @param opt pointer to accept the initial voltage + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if argument is wrong + */ +esp_err_t touch_pad_get_cnt_mode(touch_pad_t touch_num, touch_cnt_slope_t *slope, touch_tie_opt_t *opt); + +/** + * @brief Deregister the handler previously registered using touch_pad_isr_handler_register + * @param fn handler function to call (as passed to touch_pad_isr_handler_register) + * @param arg argument of the handler (as passed to touch_pad_isr_handler_register) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if a handler matching both fn and + * arg isn't registered + */ +esp_err_t touch_pad_isr_deregister(void(*fn)(void *), void *arg); + +/** + * @brief Get the touch pad which caused wakeup from deep sleep. + * @param pad_num pointer to touch pad which caused wakeup + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG parameter is NULL + */ +esp_err_t touch_pad_get_wakeup_status(touch_pad_t *pad_num); + +/** + * @brief Set touch sensor FSM mode, the test action can be triggered by the timer, + * as well as by the software. + * @param mode FSM mode + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if argument is wrong + */ +esp_err_t touch_pad_set_fsm_mode(touch_fsm_mode_t mode); + +/** + * @brief Get touch sensor FSM mode + * @param mode pointer to accept FSM mode + * @return + * - ESP_OK on success + */ +esp_err_t touch_pad_get_fsm_mode(touch_fsm_mode_t *mode); + + +/** + * @brief To clear the touch sensor channel active status. + * + * @note The FSM automatically updates the touch sensor status. It is generally not necessary to call this API to clear the status. + * @return + * - ESP_OK on success + */ +esp_err_t touch_pad_clear_status(void); + +/** + * @brief Get the touch sensor channel active status mask. + * The bit position represents the channel number. The 0/1 status of the bit represents the trigger status. + * + * @return + * - The touch sensor status. e.g. Touch1 trigger status is `status_mask & (BIT1)`. + */ +uint32_t touch_pad_get_status(void); + +/** + * @brief Check touch sensor measurement status. + * + * @return + * - True measurement is under way + * - False measurement done + */ +bool touch_pad_meas_is_done(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/twai.h b/tools/sdk/esp32c3/include/driver/include/driver/twai.h new file mode 100644 index 00000000..0cb74400 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/twai.h @@ -0,0 +1,352 @@ +// Copyright 2015-2018 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/soc_caps.h" +#if SOC_TWAI_SUPPORTED + +#include "freertos/FreeRTOS.h" +#include "esp_types.h" +#include "esp_intr_alloc.h" +#include "esp_err.h" +#include "gpio.h" +#include "hal/twai_types.h" + +/* -------------------- Default initializers and flags ---------------------- */ +/** @cond */ //Doxy command to hide preprocessor definitions from docs +/** + * @brief Initializer macro for general configuration structure. + * + * This initializer macros allows the TX GPIO, RX GPIO, and operating mode to be + * configured. The other members of the general configuration structure are + * assigned default values. + */ +#define TWAI_GENERAL_CONFIG_DEFAULT(tx_io_num, rx_io_num, op_mode) {.mode = op_mode, .tx_io = tx_io_num, .rx_io = rx_io_num, \ + .clkout_io = TWAI_IO_UNUSED, .bus_off_io = TWAI_IO_UNUSED, \ + .tx_queue_len = 5, .rx_queue_len = 5, \ + .alerts_enabled = TWAI_ALERT_NONE, .clkout_divider = 0, \ + .intr_flags = ESP_INTR_FLAG_LEVEL1} + +/** + * @brief Alert flags + * + * The following flags represents the various kind of alerts available in + * the TWAI driver. These flags can be used when configuring/reconfiguring + * alerts, or when calling twai_read_alerts(). + * + * @note The TWAI_ALERT_AND_LOG flag is not an actual alert, but will configure + * the TWAI driver to log to UART when an enabled alert occurs. + */ +#define TWAI_ALERT_TX_IDLE 0x00000001 /**< Alert(1): No more messages to transmit */ +#define TWAI_ALERT_TX_SUCCESS 0x00000002 /**< Alert(2): The previous transmission was successful */ +#define TWAI_ALERT_BELOW_ERR_WARN 0x00000004 /**< Alert(4): Both error counters have dropped below error warning limit */ +#define TWAI_ALERT_ERR_ACTIVE 0x00000008 /**< Alert(8): TWAI controller has become error active */ +#define TWAI_ALERT_RECOVERY_IN_PROGRESS 0x00000010 /**< Alert(16): TWAI controller is undergoing bus recovery */ +#define TWAI_ALERT_BUS_RECOVERED 0x00000020 /**< Alert(32): TWAI controller has successfully completed bus recovery */ +#define TWAI_ALERT_ARB_LOST 0x00000040 /**< Alert(64): The previous transmission lost arbitration */ +#define TWAI_ALERT_ABOVE_ERR_WARN 0x00000080 /**< Alert(128): One of the error counters have exceeded the error warning limit */ +#define TWAI_ALERT_BUS_ERROR 0x00000100 /**< Alert(256): A (Bit, Stuff, CRC, Form, ACK) error has occurred on the bus */ +#define TWAI_ALERT_TX_FAILED 0x00000200 /**< Alert(512): The previous transmission has failed (for single shot transmission) */ +#define TWAI_ALERT_RX_QUEUE_FULL 0x00000400 /**< Alert(1024): The RX queue is full causing a frame to be lost */ +#define TWAI_ALERT_ERR_PASS 0x00000800 /**< Alert(2048): TWAI controller has become error passive */ +#define TWAI_ALERT_BUS_OFF 0x00001000 /**< Alert(4096): Bus-off condition occurred. TWAI controller can no longer influence bus */ +#define TWAI_ALERT_RX_FIFO_OVERRUN 0x00002000 /**< Alert(8192): An RX FIFO overrun has occurred */ +#define TWAI_ALERT_TX_RETRIED 0x00004000 /**< Alert(16384): An message transmission was cancelled and retried due to an errata workaround */ +#define TWAI_ALERT_PERIPH_RESET 0x00008000 /**< Alert(32768): The TWAI controller was reset */ +#define TWAI_ALERT_ALL 0x0000FFFF /**< Bit mask to enable all alerts during configuration */ +#define TWAI_ALERT_NONE 0x00000000 /**< Bit mask to disable all alerts during configuration */ +#define TWAI_ALERT_AND_LOG 0x00010000 /**< Bit mask to enable alerts to also be logged when they occur. Note that logging from the ISR is disabled if CONFIG_TWAI_ISR_IN_IRAM is enabled (see docs). */ + +/** @endcond */ + +#define TWAI_IO_UNUSED ((gpio_num_t) -1) /**< Marks GPIO as unused in TWAI configuration */ + +/* ----------------------- Enum and Struct Definitions ---------------------- */ + +/** + * @brief TWAI driver states + */ +typedef enum { + TWAI_STATE_STOPPED, /**< Stopped state. The TWAI controller will not participate in any TWAI bus activities */ + TWAI_STATE_RUNNING, /**< Running state. The TWAI controller can transmit and receive messages */ + TWAI_STATE_BUS_OFF, /**< Bus-off state. The TWAI controller cannot participate in bus activities until it has recovered */ + TWAI_STATE_RECOVERING, /**< Recovering state. The TWAI controller is undergoing bus recovery */ +} twai_state_t; + +/** + * @brief Structure for general configuration of the TWAI driver + * + * @note Macro initializers are available for this structure + */ +typedef struct { + twai_mode_t mode; /**< Mode of TWAI controller */ + gpio_num_t tx_io; /**< Transmit GPIO number */ + gpio_num_t rx_io; /**< Receive GPIO number */ + gpio_num_t clkout_io; /**< CLKOUT GPIO number (optional, set to -1 if unused) */ + gpio_num_t bus_off_io; /**< Bus off indicator GPIO number (optional, set to -1 if unused) */ + uint32_t tx_queue_len; /**< Number of messages TX queue can hold (set to 0 to disable TX Queue) */ + uint32_t rx_queue_len; /**< Number of messages RX queue can hold */ + uint32_t alerts_enabled; /**< Bit field of alerts to enable (see documentation) */ + uint32_t clkout_divider; /**< CLKOUT divider. Can be 1 or any even number from 2 to 14 (optional, set to 0 if unused) */ + int intr_flags; /**< Interrupt flags to set the priority of the driver's ISR. Note that to use the ESP_INTR_FLAG_IRAM, the CONFIG_TWAI_ISR_IN_IRAM option should be enabled first. */ +} twai_general_config_t; + +/** + * @brief Structure to store status information of TWAI driver + */ +typedef struct { + twai_state_t state; /**< Current state of TWAI controller (Stopped/Running/Bus-Off/Recovery) */ + uint32_t msgs_to_tx; /**< Number of messages queued for transmission or awaiting transmission completion */ + uint32_t msgs_to_rx; /**< Number of messages in RX queue waiting to be read */ + uint32_t tx_error_counter; /**< Current value of Transmit Error Counter */ + uint32_t rx_error_counter; /**< Current value of Receive Error Counter */ + uint32_t tx_failed_count; /**< Number of messages that failed transmissions */ + uint32_t rx_missed_count; /**< Number of messages that were lost due to a full RX queue (or errata workaround if enabled) */ + uint32_t rx_overrun_count; /**< Number of messages that were lost due to a RX FIFO overrun */ + uint32_t arb_lost_count; /**< Number of instances arbitration was lost */ + uint32_t bus_error_count; /**< Number of instances a bus error has occurred */ +} twai_status_info_t; + +/* ------------------------------ Public API -------------------------------- */ + +/** + * @brief Install TWAI driver + * + * This function installs the TWAI driver using three configuration structures. + * The required memory is allocated and the TWAI driver is placed in the stopped + * state after running this function. + * + * @param[in] g_config General configuration structure + * @param[in] t_config Timing configuration structure + * @param[in] f_config Filter configuration structure + * + * @note Macro initializers are available for the configuration structures (see documentation) + * + * @note To reinstall the TWAI driver, call twai_driver_uninstall() first + * + * @return + * - ESP_OK: Successfully installed TWAI driver + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_NO_MEM: Insufficient memory + * - ESP_ERR_INVALID_STATE: Driver is already installed + */ +esp_err_t twai_driver_install(const twai_general_config_t *g_config, const twai_timing_config_t *t_config, const twai_filter_config_t *f_config); + +/** + * @brief Uninstall the TWAI driver + * + * This function uninstalls the TWAI driver, freeing the memory utilized by the + * driver. This function can only be called when the driver is in the stopped + * state or the bus-off state. + * + * @warning The application must ensure that no tasks are blocked on TX/RX + * queues or alerts when this function is called. + * + * @return + * - ESP_OK: Successfully uninstalled TWAI driver + * - ESP_ERR_INVALID_STATE: Driver is not in stopped/bus-off state, or is not installed + */ +esp_err_t twai_driver_uninstall(void); + +/** + * @brief Start the TWAI driver + * + * This function starts the TWAI driver, putting the TWAI driver into the running + * state. This allows the TWAI driver to participate in TWAI bus activities such + * as transmitting/receiving messages. The TX and RX queue are reset in this function, + * clearing any messages that are unread or pending transmission. This function + * can only be called when the TWAI driver is in the stopped state. + * + * @return + * - ESP_OK: TWAI driver is now running + * - ESP_ERR_INVALID_STATE: Driver is not in stopped state, or is not installed + */ +esp_err_t twai_start(void); + +/** + * @brief Stop the TWAI driver + * + * This function stops the TWAI driver, preventing any further message from being + * transmitted or received until twai_start() is called. Any messages in the TX + * queue are cleared. Any messages in the RX queue should be read by the + * application after this function is called. This function can only be called + * when the TWAI driver is in the running state. + * + * @warning A message currently being transmitted/received on the TWAI bus will + * be ceased immediately. This may lead to other TWAI nodes interpreting + * the unfinished message as an error. + * + * @return + * - ESP_OK: TWAI driver is now Stopped + * - ESP_ERR_INVALID_STATE: Driver is not in running state, or is not installed + */ +esp_err_t twai_stop(void); + +/** + * @brief Transmit a TWAI message + * + * This function queues a TWAI message for transmission. Transmission will start + * immediately if no other messages are queued for transmission. If the TX queue + * is full, this function will block until more space becomes available or until + * it times out. If the TX queue is disabled (TX queue length = 0 in configuration), + * this function will return immediately if another message is undergoing + * transmission. This function can only be called when the TWAI driver is in the + * running state and cannot be called under Listen Only Mode. + * + * @param[in] message Message to transmit + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block on the TX queue + * + * @note This function does not guarantee that the transmission is successful. + * The TX_SUCCESS/TX_FAILED alert can be enabled to alert the application + * upon the success/failure of a transmission. + * + * @note The TX_IDLE alert can be used to alert the application when no other + * messages are awaiting transmission. + * + * @return + * - ESP_OK: Transmission successfully queued/initiated + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_TIMEOUT: Timed out waiting for space on TX queue + * - ESP_FAIL: TX queue is disabled and another message is currently transmitting + * - ESP_ERR_INVALID_STATE: TWAI driver is not in running state, or is not installed + * - ESP_ERR_NOT_SUPPORTED: Listen Only Mode does not support transmissions + */ +esp_err_t twai_transmit(const twai_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Receive a TWAI message + * + * This function receives a message from the RX queue. The flags field of the + * message structure will indicate the type of message received. This function + * will block if there are no messages in the RX queue + * + * @param[out] message Received message + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block on RX queue + * + * @warning The flags field of the received message should be checked to determine + * if the received message contains any data bytes. + * + * @return + * - ESP_OK: Message successfully received from RX queue + * - ESP_ERR_TIMEOUT: Timed out waiting for message + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed + */ +esp_err_t twai_receive(twai_message_t *message, TickType_t ticks_to_wait); + +/** + * @brief Read TWAI driver alerts + * + * This function will read the alerts raised by the TWAI driver. If no alert has + * been issued when this function is called, this function will block until an alert + * occurs or until it timeouts. + * + * @param[out] alerts Bit field of raised alerts (see documentation for alert flags) + * @param[in] ticks_to_wait Number of FreeRTOS ticks to block for alert + * + * @note Multiple alerts can be raised simultaneously. The application should + * check for all alerts that have been enabled. + * + * @return + * - ESP_OK: Alerts read + * - ESP_ERR_TIMEOUT: Timed out waiting for alerts + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed + */ +esp_err_t twai_read_alerts(uint32_t *alerts, TickType_t ticks_to_wait); + +/** + * @brief Reconfigure which alerts are enabled + * + * This function reconfigures which alerts are enabled. If there are alerts + * which have not been read whilst reconfiguring, this function can read those + * alerts. + * + * @param[in] alerts_enabled Bit field of alerts to enable (see documentation for alert flags) + * @param[out] current_alerts Bit field of currently raised alerts. Set to NULL if unused + * + * @return + * - ESP_OK: Alerts reconfigured + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed + */ +esp_err_t twai_reconfigure_alerts(uint32_t alerts_enabled, uint32_t *current_alerts); + +/** + * @brief Start the bus recovery process + * + * This function initiates the bus recovery process when the TWAI driver is in + * the bus-off state. Once initiated, the TWAI driver will enter the recovering + * state and wait for 128 occurrences of the bus-free signal on the TWAI bus + * before returning to the stopped state. This function will reset the TX queue, + * clearing any messages pending transmission. + * + * @note The BUS_RECOVERED alert can be enabled to alert the application when + * the bus recovery process completes. + * + * @return + * - ESP_OK: Bus recovery started + * - ESP_ERR_INVALID_STATE: TWAI driver is not in the bus-off state, or is not installed + */ +esp_err_t twai_initiate_recovery(void); + +/** + * @brief Get current status information of the TWAI driver + * + * @param[out] status_info Status information + * + * @return + * - ESP_OK: Status information retrieved + * - ESP_ERR_INVALID_ARG: Arguments are invalid + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed + */ +esp_err_t twai_get_status_info(twai_status_info_t *status_info); + +/** + * @brief Clear the transmit queue + * + * This function will clear the transmit queue of all messages. + * + * @note The transmit queue is automatically cleared when twai_stop() or + * twai_initiate_recovery() is called. + * + * @return + * - ESP_OK: Transmit queue cleared + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed or TX queue is disabled + */ +esp_err_t twai_clear_transmit_queue(void); + +/** + * @brief Clear the receive queue + * + * This function will clear the receive queue of all messages. + * + * @note The receive queue is automatically cleared when twai_start() is + * called. + * + * @return + * - ESP_OK: Transmit queue cleared + * - ESP_ERR_INVALID_STATE: TWAI driver is not installed + */ +esp_err_t twai_clear_receive_queue(void); + +#ifdef __cplusplus +} +#endif + +#endif //SOC_TWAI_SUPPORTED diff --git a/tools/sdk/esp32c3/include/driver/include/driver/uart.h b/tools/sdk/esp32c3/include/driver/include/driver/uart.h new file mode 100644 index 00000000..7269b3fa --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/uart.h @@ -0,0 +1,868 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_err.h" +#include "esp_intr_alloc.h" +#include "soc/soc_caps.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/ringbuf.h" +#include "hal/uart_types.h" + +// Valid UART port number +#define UART_NUM_0 (0) /*!< UART port 0 */ +#define UART_NUM_1 (1) /*!< UART port 1 */ +#if SOC_UART_NUM > 2 +#define UART_NUM_2 (2) /*!< UART port 2 */ +#endif +#define UART_NUM_MAX (SOC_UART_NUM) /*!< UART port max */ + +#define UART_PIN_NO_CHANGE (-1) /*!< Constant for uart_set_pin function which indicates that UART pin should not be changed */ + +#define UART_FIFO_LEN SOC_UART_FIFO_LEN ///< Length of the UART HW FIFO +#define UART_BITRATE_MAX SOC_UART_BITRATE_MAX ///< Maximum configurable bitrate + +/** + * @brief UART interrupt configuration parameters for uart_intr_config function + */ +typedef struct { + uint32_t intr_enable_mask; /*!< UART interrupt enable mask, choose from UART_XXXX_INT_ENA_M under UART_INT_ENA_REG(i), connect with bit-or operator*/ + uint8_t rx_timeout_thresh; /*!< UART timeout interrupt threshold (unit: time of sending one byte)*/ + uint8_t txfifo_empty_intr_thresh; /*!< UART TX empty interrupt threshold.*/ + uint8_t rxfifo_full_thresh; /*!< UART RX full interrupt threshold.*/ +} uart_intr_config_t; + +/** + * @brief UART event types used in the ring buffer + */ +typedef enum { + UART_DATA, /*!< UART data event*/ + UART_BREAK, /*!< UART break event*/ + UART_BUFFER_FULL, /*!< UART RX buffer full event*/ + UART_FIFO_OVF, /*!< UART FIFO overflow event*/ + UART_FRAME_ERR, /*!< UART RX frame error event*/ + UART_PARITY_ERR, /*!< UART RX parity event*/ + UART_DATA_BREAK, /*!< UART TX data and break event*/ + UART_PATTERN_DET, /*!< UART pattern detected */ + UART_EVENT_MAX, /*!< UART event max index*/ +} uart_event_type_t; + +/** + * @brief Event structure used in UART event queue + */ +typedef struct { + uart_event_type_t type; /*!< UART event type */ + size_t size; /*!< UART data size for UART_DATA event*/ + bool timeout_flag; /*!< UART data read timeout flag for UART_DATA event (no new data received during configured RX TOUT)*/ + /*!< If the event is caused by FIFO-full interrupt, then there will be no event with the timeout flag before the next byte coming.*/ +} uart_event_t; + +typedef intr_handle_t uart_isr_handle_t; + +/** + * @brief Install UART driver and set the UART to the default configuration. + * + * UART ISR handler will be attached to the same CPU core that this function is running on. + * + * @note Rx_buffer_size should be greater than UART_FIFO_LEN. Tx_buffer_size should be either zero or greater than UART_FIFO_LEN. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param rx_buffer_size UART RX ring buffer size. + * @param tx_buffer_size UART TX ring buffer size. + * If set to zero, driver will not use TX buffer, TX function will block task until all data have been sent out. + * @param queue_size UART event queue size/depth. + * @param uart_queue UART event queue handle (out param). On success, a new queue handle is written here to provide + * access to UART events. If set to NULL, driver will not use an event queue. + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. Do not set ESP_INTR_FLAG_IRAM here + * (the driver's ISR handler is not located in IRAM) + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_driver_install(uart_port_t uart_num, int rx_buffer_size, int tx_buffer_size, int queue_size, QueueHandle_t* uart_queue, int intr_alloc_flags); + +/** + * @brief Uninstall UART driver. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_driver_delete(uart_port_t uart_num); + +/** + * @brief Checks whether the driver is installed or not + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - true driver is installed + * - false driver is not installed + */ +bool uart_is_driver_installed(uart_port_t uart_num); + +/** + * @brief Set UART data bits. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param data_bit UART data bits + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_word_length(uart_port_t uart_num, uart_word_length_t data_bit); + +/** + * @brief Get the UART data bit configuration. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param data_bit Pointer to accept value of UART data bits. + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success, result will be put in (*data_bit) + */ +esp_err_t uart_get_word_length(uart_port_t uart_num, uart_word_length_t* data_bit); + +/** + * @brief Set UART stop bits. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param stop_bits UART stop bits + * + * @return + * - ESP_OK Success + * - ESP_FAIL Fail + */ +esp_err_t uart_set_stop_bits(uart_port_t uart_num, uart_stop_bits_t stop_bits); + +/** + * @brief Get the UART stop bit configuration. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param stop_bits Pointer to accept value of UART stop bits. + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success, result will be put in (*stop_bit) + */ +esp_err_t uart_get_stop_bits(uart_port_t uart_num, uart_stop_bits_t* stop_bits); + +/** + * @brief Set UART parity mode. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param parity_mode the enum of uart parity configuration + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success + */ +esp_err_t uart_set_parity(uart_port_t uart_num, uart_parity_t parity_mode); + +/** + * @brief Get the UART parity mode configuration. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param parity_mode Pointer to accept value of UART parity mode. + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success, result will be put in (*parity_mode) + * + */ +esp_err_t uart_get_parity(uart_port_t uart_num, uart_parity_t* parity_mode); + +/** + * @brief Set UART baud rate. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param baudrate UART baud rate. + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success + */ +esp_err_t uart_set_baudrate(uart_port_t uart_num, uint32_t baudrate); + +/** + * @brief Get the UART baud rate configuration. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param baudrate Pointer to accept value of UART baud rate + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success, result will be put in (*baudrate) + * + */ +esp_err_t uart_get_baudrate(uart_port_t uart_num, uint32_t* baudrate); + +/** + * @brief Set UART line inverse mode + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param inverse_mask Choose the wires that need to be inverted. Using the ORred mask of `uart_signal_inv_t` + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_line_inverse(uart_port_t uart_num, uint32_t inverse_mask); + +/** + * @brief Set hardware flow control. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param flow_ctrl Hardware flow control mode + * @param rx_thresh Threshold of Hardware RX flow control (0 ~ UART_FIFO_LEN). + * Only when UART_HW_FLOWCTRL_RTS is set, will the rx_thresh value be set. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t flow_ctrl, uint8_t rx_thresh); + +/** + * @brief Set software flow control. + * + * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 + * @param enable switch on or off + * @param rx_thresh_xon low water mark + * @param rx_thresh_xoff high water mark + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ + esp_err_t uart_set_sw_flow_ctrl(uart_port_t uart_num, bool enable, uint8_t rx_thresh_xon, uint8_t rx_thresh_xoff); + +/** + * @brief Get the UART hardware flow control configuration. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param flow_ctrl Option for different flow control mode. + * + * @return + * - ESP_FAIL Parameter error + * - ESP_OK Success, result will be put in (*flow_ctrl) + */ +esp_err_t uart_get_hw_flow_ctrl(uart_port_t uart_num, uart_hw_flowcontrol_t* flow_ctrl); + +/** + * @brief Clear UART interrupt status + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param clr_mask Bit mask of the interrupt status to be cleared. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_clear_intr_status(uart_port_t uart_num, uint32_t clr_mask); + +/** + * @brief Set UART interrupt enable + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param enable_mask Bit mask of the enable bits. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_enable_intr_mask(uart_port_t uart_num, uint32_t enable_mask); + +/** + * @brief Clear UART interrupt enable bits + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param disable_mask Bit mask of the disable bits. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_disable_intr_mask(uart_port_t uart_num, uint32_t disable_mask); + +/** + * @brief Enable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_enable_rx_intr(uart_port_t uart_num); + +/** + * @brief Disable UART RX interrupt (RX_FULL & RX_TIMEOUT INTERRUPT) + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_disable_rx_intr(uart_port_t uart_num); + +/** + * @brief Disable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) + * + * @param uart_num UART port number + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_disable_tx_intr(uart_port_t uart_num); + +/** + * @brief Enable UART TX interrupt (TX_FULL & TX_TIMEOUT INTERRUPT) + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param enable 1: enable; 0: disable + * @param thresh Threshold of TX interrupt, 0 ~ UART_FIFO_LEN + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_enable_tx_intr(uart_port_t uart_num, int enable, int thresh); + +/** + * @brief Register UART interrupt handler (ISR). + * + * @note UART ISR handler will be attached to the same CPU core that this function is running on. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param fn Interrupt handler function. + * @param arg parameter for handler function + * @param intr_alloc_flags Flags used to allocate the interrupt. One or multiple (ORred) + * ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info. + * @param handle Pointer to return handle. If non-NULL, a handle for the interrupt will + * be returned here. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_isr_register(uart_port_t uart_num, void (*fn)(void*), void * arg, int intr_alloc_flags, uart_isr_handle_t *handle); + +/** + * @brief Free UART interrupt handler registered by uart_isr_register. Must be called on the same core as + * uart_isr_register was called. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_isr_free(uart_port_t uart_num); + +/** + * @brief Set UART pin number + * + * @note Internal signal can be output to multiple GPIO pads. + * Only one GPIO pad can connect with input signal. + * + * @note Instead of GPIO number a macro 'UART_PIN_NO_CHANGE' may be provided + to keep the currently allocated pin. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param tx_io_num UART TX pin GPIO number. + * @param rx_io_num UART RX pin GPIO number. + * @param rts_io_num UART RTS pin GPIO number. + * @param cts_io_num UART CTS pin GPIO number. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_pin(uart_port_t uart_num, int tx_io_num, int rx_io_num, int rts_io_num, int cts_io_num); + +/** + * @brief Manually set the UART RTS pin level. + * @note UART must be configured with hardware flow control disabled. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param level 1: RTS output low (active); 0: RTS output high (block) + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_rts(uart_port_t uart_num, int level); + +/** + * @brief Manually set the UART DTR pin level. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param level 1: DTR output low; 0: DTR output high + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_dtr(uart_port_t uart_num, int level); + +/** + * @brief Set UART idle interval after tx FIFO is empty + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param idle_num idle interval after tx FIFO is empty(unit: the time it takes to send one bit + * under current baudrate) + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_set_tx_idle_num(uart_port_t uart_num, uint16_t idle_num); + +/** + * @brief Set UART configuration parameters. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param uart_config UART parameter settings + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_param_config(uart_port_t uart_num, const uart_config_t *uart_config); + +/** + * @brief Configure UART interrupts. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param intr_conf UART interrupt settings + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_intr_config(uart_port_t uart_num, const uart_intr_config_t *intr_conf); + +/** + * @brief Wait until UART TX FIFO is empty. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param ticks_to_wait Timeout, count in RTOS ticks + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + * - ESP_ERR_TIMEOUT Timeout + */ +esp_err_t uart_wait_tx_done(uart_port_t uart_num, TickType_t ticks_to_wait); + +/** + * @brief Send data to the UART port from a given buffer and length. + * + * This function will not wait for enough space in TX FIFO. It will just fill the available TX FIFO and return when the FIFO is full. + * @note This function should only be used when UART TX buffer is not enabled. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param buffer data buffer address + * @param len data length to send + * + * @return + * - (-1) Parameter error + * - OTHERS (>=0) The number of bytes pushed to the TX FIFO + */ +int uart_tx_chars(uart_port_t uart_num, const char* buffer, uint32_t len); + +/** + * @brief Send data to the UART port from a given buffer and length, + * + * If the UART driver's parameter 'tx_buffer_size' is set to zero: + * This function will not return until all the data have been sent out, or at least pushed into TX FIFO. + * + * Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, + * UART ISR will then move data from the ring buffer to TX FIFO gradually. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param src data buffer address + * @param size data length to send + * + * @return + * - (-1) Parameter error + * - OTHERS (>=0) The number of bytes pushed to the TX FIFO + */ +int uart_write_bytes(uart_port_t uart_num, const void* src, size_t size); + +/** + * @brief Send data to the UART port from a given buffer and length, + * + * If the UART driver's parameter 'tx_buffer_size' is set to zero: + * This function will not return until all the data and the break signal have been sent out. + * After all data is sent out, send a break signal. + * + * Otherwise, if the 'tx_buffer_size' > 0, this function will return after copying all the data to tx ring buffer, + * UART ISR will then move data from the ring buffer to TX FIFO gradually. + * After all data sent out, send a break signal. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param src data buffer address + * @param size data length to send + * @param brk_len break signal duration(unit: the time it takes to send one bit at current baudrate) + * + * @return + * - (-1) Parameter error + * - OTHERS (>=0) The number of bytes pushed to the TX FIFO + */ +int uart_write_bytes_with_break(uart_port_t uart_num, const void* src, size_t size, int brk_len); + +/** + * @brief UART read bytes from UART buffer + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param buf pointer to the buffer. + * @param length data length + * @param ticks_to_wait sTimeout, count in RTOS ticks + * + * @return + * - (-1) Error + * - OTHERS (>=0) The number of bytes read from UART FIFO + */ +int uart_read_bytes(uart_port_t uart_num, void* buf, uint32_t length, TickType_t ticks_to_wait); + +/** + * @brief Alias of uart_flush_input. + * UART ring buffer flush. This will discard all data in the UART RX buffer. + * @note Instead of waiting the data sent out, this function will clear UART rx buffer. + * In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_flush(uart_port_t uart_num); + +/** + * @brief Clear input buffer, discard all the data is in the ring-buffer. + * @note In order to send all the data in tx FIFO, we can use uart_wait_tx_done function. + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_flush_input(uart_port_t uart_num); + +/** + * @brief UART get RX ring buffer cached data length + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param size Pointer of size_t to accept cached data length + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_get_buffered_data_len(uart_port_t uart_num, size_t* size); + +/** + * @brief UART disable pattern detect function. + * Designed for applications like 'AT commands'. + * When the hardware detects a series of one same character, the interrupt will be triggered. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_disable_pattern_det_intr(uart_port_t uart_num); + +#if CONFIG_IDF_TARGET_ESP32 +/** + * @brief UART enable pattern detect function. + * Designed for applications like 'AT commands'. + * When the hardware detect a series of one same character, the interrupt will be triggered. + * @note This function only works for esp32. And this function is deprecated, please use + * uart_enable_pattern_det_baud_intr instead. + * + * @param uart_num UART port number. + * @param pattern_chr character of the pattern. + * @param chr_num number of the character, 8bit value. + * @param chr_tout timeout of the interval between each pattern characters, 24bit value, unit is APB (80Mhz) clock cycle. + * When the duration is less than this value, it will not take this data as at_cmd char. + * @param post_idle idle time after the last pattern character, 24bit value, unit is APB (80Mhz) clock cycle. + * When the duration is less than this value, it will not take the previous data as the last at_cmd char + * @param pre_idle idle time before the first pattern character, 24bit value, unit is APB (80Mhz) clock cycle. + * When the duration is less than this value, it will not take this data as the first at_cmd char. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_enable_pattern_det_intr(uart_port_t uart_num, char pattern_chr, uint8_t chr_num, int chr_tout, int post_idle, int pre_idle) __attribute__((deprecated)); +#endif + +/** + * @brief UART enable pattern detect function. + * Designed for applications like 'AT commands'. + * When the hardware detect a series of one same character, the interrupt will be triggered. + * + * @param uart_num UART port number. + * @param pattern_chr character of the pattern. + * @param chr_num number of the character, 8bit value. + * @param chr_tout timeout of the interval between each pattern characters, 16bit value, unit is the baud-rate cycle you configured. + * When the duration is more than this value, it will not take this data as at_cmd char. + * @param post_idle idle time after the last pattern character, 16bit value, unit is the baud-rate cycle you configured. + * When the duration is less than this value, it will not take the previous data as the last at_cmd char + * @param pre_idle idle time before the first pattern character, 16bit value, unit is the baud-rate cycle you configured. + * When the duration is less than this value, it will not take this data as the first at_cmd char. + * + * @return + * - ESP_OK Success + * - ESP_FAIL Parameter error + */ +esp_err_t uart_enable_pattern_det_baud_intr(uart_port_t uart_num, char pattern_chr, uint8_t chr_num, int chr_tout, int post_idle, int pre_idle); + +/** + * @brief Return the nearest detected pattern position in buffer. + * The positions of the detected pattern are saved in a queue, + * this function will dequeue the first pattern position and move the pointer to next pattern position. + * @note If the RX buffer is full and flow control is not enabled, + * the detected pattern may not be found in the rx buffer due to overflow. + * + * The following APIs will modify the pattern position info: + * uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos + * It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer + * when using pattern detect feature. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @return + * - (-1) No pattern found for current index or parameter error + * - others the pattern position in rx buffer. + */ +int uart_pattern_pop_pos(uart_port_t uart_num); + +/** + * @brief Return the nearest detected pattern position in buffer. + * The positions of the detected pattern are saved in a queue, + * This function do nothing to the queue. + * @note If the RX buffer is full and flow control is not enabled, + * the detected pattern may not be found in the rx buffer due to overflow. + * + * The following APIs will modify the pattern position info: + * uart_flush_input, uart_read_bytes, uart_driver_delete, uart_pop_pattern_pos + * It is the application's responsibility to ensure atomic access to the pattern queue and the rx data buffer + * when using pattern detect feature. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @return + * - (-1) No pattern found for current index or parameter error + * - others the pattern position in rx buffer. + */ +int uart_pattern_get_pos(uart_port_t uart_num); + +/** + * @brief Allocate a new memory with the given length to save record the detected pattern position in rx buffer. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * @param queue_length Max queue length for the detected pattern. + * If the queue length is not large enough, some pattern positions might be lost. + * Set this value to the maximum number of patterns that could be saved in data buffer at the same time. + * @return + * - ESP_ERR_NO_MEM No enough memory + * - ESP_ERR_INVALID_STATE Driver not installed + * - ESP_FAIL Parameter error + * - ESP_OK Success + */ +esp_err_t uart_pattern_queue_reset(uart_port_t uart_num, int queue_length); + +/** + * @brief UART set communication mode + * + * @note This function must be executed after uart_driver_install(), when the driver object is initialized. + * @param uart_num Uart number to configure, the max port number is (UART_NUM_MAX -1). + * @param mode UART UART mode to set + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t uart_set_mode(uart_port_t uart_num, uart_mode_t mode); + +/** + * @brief Set uart threshold value for RX fifo full + * @note If application is using higher baudrate and it is observed that bytes + * in hardware RX fifo are overwritten then this threshold can be reduced + * + * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 + * @param threshold Threshold value above which RX fifo full interrupt is generated + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver is not installed + */ +esp_err_t uart_set_rx_full_threshold(uart_port_t uart_num, int threshold); + +/** + * @brief Set uart threshold values for TX fifo empty + * + * @param uart_num UART_NUM_0, UART_NUM_1 or UART_NUM_2 + * @param threshold Threshold value below which TX fifo empty interrupt is generated + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver is not installed + */ +esp_err_t uart_set_tx_empty_threshold(uart_port_t uart_num, int threshold); + +/** + * @brief UART set threshold timeout for TOUT feature + * + * @param uart_num Uart number to configure, the max port number is (UART_NUM_MAX -1). + * @param tout_thresh This parameter defines timeout threshold in uart symbol periods. The maximum value of threshold is 126. + * tout_thresh = 1, defines TOUT interrupt timeout equal to transmission time of one symbol (~11 bit) on current baudrate. + * If the time is expired the UART_RXFIFO_TOUT_INT interrupt is triggered. If tout_thresh == 0, + * the TOUT feature is disabled. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_ERR_INVALID_STATE Driver is not installed + */ +esp_err_t uart_set_rx_timeout(uart_port_t uart_num, const uint8_t tout_thresh); + +/** + * @brief Returns collision detection flag for RS485 mode + * Function returns the collision detection flag into variable pointed by collision_flag. + * *collision_flag = true, if collision detected else it is equal to false. + * This function should be executed when actual transmission is completed (after uart_write_bytes()). + * + * @param uart_num Uart number to configure the max port number is (UART_NUM_MAX -1). + * @param collision_flag Pointer to variable of type bool to return collision flag. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Parameter error + */ +esp_err_t uart_get_collision_flag(uart_port_t uart_num, bool* collision_flag); + +/** + * @brief Set the number of RX pin signal edges for light sleep wakeup + * + * UART can be used to wake up the system from light sleep. This feature works + * by counting the number of positive edges on RX pin and comparing the count to + * the threshold. When the count exceeds the threshold, system is woken up from + * light sleep. This function allows setting the threshold value. + * + * Stop bit and parity bits (if enabled) also contribute to the number of edges. + * For example, letter 'a' with ASCII code 97 is encoded as 0100001101 on the wire + * (with 8n1 configuration), start and stop bits included. This sequence has 3 + * positive edges (transitions from 0 to 1). Therefore, to wake up the system + * when 'a' is sent, set wakeup_threshold=3. + * + * The character that triggers wakeup is not received by UART (i.e. it can not + * be obtained from UART FIFO). Depending on the baud rate, a few characters + * after that will also not be received. Note that when the chip enters and exits + * light sleep mode, APB frequency will be changing. To make sure that UART has + * correct baud rate all the time, select REF_TICK as UART clock source, + * by setting use_ref_tick field in uart_config_t to true. + * + * @note in ESP32, the wakeup signal can only be input via IO_MUX (i.e. + * GPIO3 should be configured as function_1 to wake up UART0, + * GPIO9 should be configured as function_5 to wake up UART1), UART2 + * does not support light sleep wakeup feature. + * + * @param uart_num UART number, the max port number is (UART_NUM_MAX -1). + * @param wakeup_threshold number of RX edges for light sleep wakeup, value is 3 .. 0x3ff. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if uart_num is incorrect or wakeup_threshold is + * outside of [3, 0x3ff] range. + */ +esp_err_t uart_set_wakeup_threshold(uart_port_t uart_num, int wakeup_threshold); + +/** + * @brief Get the number of RX pin signal edges for light sleep wakeup. + * + * See description of uart_set_wakeup_threshold for the explanation of UART + * wakeup feature. + * + * @param uart_num UART number, the max port number is (UART_NUM_MAX -1). + * @param[out] out_wakeup_threshold output, set to the current value of wakeup + * threshold for the given UART. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if out_wakeup_threshold is NULL + */ +esp_err_t uart_get_wakeup_threshold(uart_port_t uart_num, int* out_wakeup_threshold); + +/** + * @brief Wait until UART tx memory empty and the last char send ok (polling mode). + * + * @param uart_num UART number + * + * * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Driver not installed + */ +esp_err_t uart_wait_tx_idle_polling(uart_port_t uart_num); + +/** + * @brief Configure TX signal loop back to RX module, just for the test usage. + * + * @param uart_num UART number + * @param loop_back_en Set ture to enable the loop back function, else set it false. + * + * * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG Parameter error + * - ESP_FAIL Driver not installed + */ +esp_err_t uart_set_loop_back(uart_port_t uart_num, bool loop_back_en); + +/** + * @brief Configure behavior of UART RX timeout interrupt. + * + * When always_rx_timeout is true, timeout interrupt is triggered even if FIFO is full. + * This function can cause extra timeout interrupts triggered only to send the timeout event. + * Call this function only if you want to ensure timeout interrupt will always happen after a byte stream. + * + * @param uart_num UART number + * @param always_rx_timeout_en Set to false enable the default behavior of timeout interrupt, + * set it to true to always trigger timeout interrupt. + * + */ +void uart_set_always_rx_timeout(uart_port_t uart_num, bool always_rx_timeout_en); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/driver/uart_select.h b/tools/sdk/esp32c3/include/driver/include/driver/uart_select.h new file mode 100644 index 00000000..f7a21a31 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/driver/uart_select.h @@ -0,0 +1,49 @@ + +// Copyright 2018 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. + +#ifndef _UART_SELECT_H_ +#define _UART_SELECT_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "driver/uart.h" + +typedef enum { + UART_SELECT_READ_NOTIF, + UART_SELECT_WRITE_NOTIF, + UART_SELECT_ERROR_NOTIF, +} uart_select_notif_t; + +typedef void (*uart_select_notif_callback_t)(uart_port_t uart_num, uart_select_notif_t uart_select_notif, BaseType_t *task_woken); + +/** + * @brief Set notification callback function for select() events + * @param uart_num UART port number + * @param uart_select_notif_callback callback function + */ +void uart_set_select_notif_callback(uart_port_t uart_num, uart_select_notif_callback_t uart_select_notif_callback); + +/** + * @brief Get mutex guarding select() notifications + */ +portMUX_TYPE *uart_get_selectlock(void); + +#ifdef __cplusplus +} +#endif + +#endif //_UART_SELECT_H_ diff --git a/tools/sdk/esp32c3/include/driver/include/esp_private/adc_cali.h b/tools/sdk/esp32c3/include/driver/include/esp_private/adc_cali.h new file mode 100644 index 00000000..ab577a31 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/esp_private/adc_cali.h @@ -0,0 +1,41 @@ +// Copyright 2020 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. + +// Internal header for calibration, don't use in app + +#include "sdkconfig.h" +#include "esp_err.h" +#include "hal/adc_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if !CONFIG_IDF_TARGET_ESP32 + +/** + * @brief Calibrate the offset of ADC. (Based on the pre-stored efuse or actual calibration) + * + * @param adc_n ADC unit to calibrate + * @param channel Target channel if really do calibration + * @param atten Attenuation to use + * @return Always ESP_OK + */ +extern esp_err_t adc_cal_offset(adc_ll_num_t adc_n, adc_channel_t channel, adc_atten_t atten); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/driver/include/esp_private/gdma.h b/tools/sdk/esp32c3/include/driver/include/esp_private/gdma.h new file mode 100644 index 00000000..dc27f582 --- /dev/null +++ b/tools/sdk/esp32c3/include/driver/include/esp_private/gdma.h @@ -0,0 +1,284 @@ +// Copyright 2020 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. + +// DO NOT USE THESE APIS IN ANY APPLICATIONS +// GDMA driver is not public for end users, but for ESP-IDF developpers. + +#pragma once + +#include +#include "soc/gdma_channel.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Type of GDMA channel handle + * + */ +typedef struct gdma_channel_t *gdma_channel_handle_t; + +/** + * @brief Enumeration of peripherals which have the DMA capability + * @note Some peripheral might not be available on certain chip, please refer to `soc_caps.h` for detail. + * + */ +typedef enum { + GDMA_TRIG_PERIPH_M2M, /*!< GDMA trigger peripheral: M2M */ + GDMA_TRIG_PERIPH_UART, /*!< GDMA trigger peripheral: UART */ + GDMA_TRIG_PERIPH_SPI, /*!< GDMA trigger peripheral: SPI */ + GDMA_TRIG_PERIPH_I2S, /*!< GDMA trigger peripheral: I2S */ + GDMA_TRIG_PERIPH_AES, /*!< GDMA trigger peripheral: AES */ + GDMA_TRIG_PERIPH_SHA, /*!< GDMA trigger peripheral: SHA */ + GDMA_TRIG_PERIPH_ADC, /*!< GDMA trigger peripheral: ADC */ + GDMA_TRIG_PERIPH_DAC, /*!< GDMA trigger peripheral: DAC */ + GDMA_TRIG_PERIPH_LCD, /*!< GDMA trigger peripheral: LCD */ + GDMA_TRIG_PERIPH_CAM /*!< GDMA trigger peripheral: CAM */ +} gdma_trigger_peripheral_t; + +/** + * @brief Enumeration of GDMA channel direction + * + */ +typedef enum { + GDMA_CHANNEL_DIRECTION_TX, /*!< GDMA channel direction: TX */ + GDMA_CHANNEL_DIRECTION_RX, /*!< GDMA channel direction: RX */ +} gdma_channel_direction_t; + +/** + * @brief Collection of configuration items that used for allocating GDMA channel + * + */ +typedef struct { + gdma_channel_handle_t sibling_chan; /*!< DMA sibling channel handle (NULL means having sibling is not necessary) */ + gdma_channel_direction_t direction; /*!< DMA channel direction */ + struct { + int reserve_sibling: 1; /*!< If set, DMA channel allocator would prefer to allocate new channel in a new pair, and reserve sibling channel for future use */ + } flags; +} gdma_channel_alloc_config_t; + +/** + * @brief Type of GDMA event data + * + */ +typedef struct { + union { + intptr_t rx_eof_desc_addr; /*!< EOF descriptor address of RX channel */ + intptr_t tx_eof_desc_addr; /*!< EOF descriptor address of TX channel */ + }; +} gdma_event_data_t; + +/** + * @brief Type of GDMA event callback + * @param dma_chan GDMA channel handle, created from `gdma_new_channel` + * @param event_data GDMA event data + * @param user_data User registered data from `gdma_register_tx_event_callbacks` or `gdma_register_rx_event_callbacks` + * + */ +typedef bool (*gdma_event_callback_t)(gdma_channel_handle_t dma_chan, gdma_event_data_t *event_data, void *user_data); + +/** + * @brief Group of supported GDMA TX callbacks + * @note The callbacks are all running under ISR environment + * + */ +typedef struct { + gdma_event_callback_t on_trans_eof; /*!< Invoked when TX engine meets EOF descriptor */ +} gdma_tx_event_callbacks_t; + +/** + * @brief Group of supported GDMA RX callbacks + * @note The callbacks are all running under ISR environment + * + */ +typedef struct { + gdma_event_callback_t on_recv_eof; /*!< Invoked when RX engine meets EOF descriptor */ +} gdma_rx_event_callbacks_t; + +/** + * @brief Type of GDMA engine trigger + * @note It's recommended to initialize this structure with `GDMA_MAKE_TRIGGER`. + * + */ +typedef struct { + gdma_trigger_peripheral_t periph; /*!< Target peripheral which will trigger DMA operations */ + int instance_id; /*!< Peripheral instance ID. Supported IDs are listed in `soc/gdma_channel.h`, e.g. SOC_GDMA_TRIG_PERIPH_UART0 */ +} gdma_trigger_t; + +/** + * @brief Helper macro to initialize GDMA trigger + * @note value of `peri` must be selected from `gdma_trigger_peripheral_t` enum. + * e.g. GDMA_MAKE_TRIGGER(GDMA_TRIG_PERIPH_UART,0) + * + */ +#define GDMA_MAKE_TRIGGER(peri, id) \ + (gdma_trigger_t) { .periph = peri, .instance_id = SOC_##peri##id } + +/** + * @brief A collection of strategy item that each GDMA channel could apply + * + */ +typedef struct { + bool owner_check; /*!< If set / clear, DMA channel enables / disables checking owner validity */ + bool auto_update_desc; /*!< If set / clear, DMA channel enables / disables hardware to update descriptor automatically (TX channel only) */ +} gdma_strategy_config_t; + +/** + * @brief Create GDMA channel + * @note This API won't install interrupt service for the allocated channel. + * If interrupt service is needed, user has to register GDMA event callback by `gdma_register_tx_event_callbacks` or `gdma_register_rx_event_callbacks`. + * + * @param[in] config Pointer to a collection of configurations for allocating GDMA channel + * @param[out] ret_chan Returnned channel handle + * @return + * - ESP_OK: Create DMA channel successfully + * - ESP_ERR_INVALID_ARG: Create DMA channel failed because of invalid argument + * - ESP_ERR_NO_MEM: Create DMA channel failed because out of memory + * - ESP_FAIL: Create DMA channel failed because of other error + */ +esp_err_t gdma_new_channel(const gdma_channel_alloc_config_t *config, gdma_channel_handle_t *ret_chan); + +/** + * @brief Connect GDMA channel to trigger peripheral + * + * @note Suggest to use helper macro `GDMA_MAKE_TRIGGER` to construct parameter `trig_periph`. e.g. GDMA_MAKE_TRIGGER(GDMA_TRIG_PERIPH_SHA,0) + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param[in] trig_periph GDMA trigger peripheral + * @return + * - ESP_OK: Connect GDMA channel successfully + * - ESP_ERR_INVALID_ARG: Connect GDMA channel failed because of invalid argument + * - ESP_ERR_INVALID_STATE: Connect GDMA channel failed because DMA channel is working with another peripheral + * - ESP_FAIL: Connect GDMA channel failed because of other error + */ +esp_err_t gdma_connect(gdma_channel_handle_t dma_chan, gdma_trigger_t trig_periph); + +/** + * @brief Disconnect GMA channel from peripheral + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @return + * - ESP_OK: Disconnect GDMA channel successfully + * - ESP_ERR_INVALID_ARG: Disconnect GDMA channel failed because of invalid argument + * - ESP_ERR_INVALID_STATE: Disconnect GDMA channel failed because DMA channel is not connected to any peripheral + * - ESP_FAIL: Disconnect DMA channel failed because of other error + */ +esp_err_t gdma_disconnect(gdma_channel_handle_t dma_chan); + +/** + * @brief Apply channel strategy for GDMA channel + * + * @param dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param config Configuration of GDMA channel strategy + * - ESP_OK: Apply channel strategy successfully + * - ESP_ERR_INVALID_ARG: Apply channel strategy failed because of invalid argument + * - ESP_FAIL: Apply channel strategy failed because of other error + */ +esp_err_t gdma_apply_strategy(gdma_channel_handle_t dma_chan, const gdma_strategy_config_t *config); + +/** + * @brief Delete GDMA channel + * @note If you call `gdma_new_channel` several times for a same peripheral, make sure you call this API the same times. + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @return + * - ESP_OK: Delete GDMA channel successfully + * - ESP_ERR_INVALID_ARG: Delete GDMA channel failed because of invalid argument + * - ESP_FAIL: Delete GDMA channel failed because of other error + */ +esp_err_t gdma_del_channel(gdma_channel_handle_t dma_chan); + +/** + * @brief Get the channel ID + * + * @note This API breaks the encapsulation of GDMA Channel Object. + * With the returned channel ID, you can even bypass all other GDMA driver API and access Low Level API directly. + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param[out] channel_id Returned channel ID + * @return + * - ESP_OK: Get GDMA channel ID successfully + * - ESP_ERR_INVALID_ARG: Get GDMA channel ID failed because of invalid argument + * - ESP_FAIL: Get GDMA channel ID failed because of other error + */ +esp_err_t gdma_get_channel_id(gdma_channel_handle_t dma_chan, int *channel_id); + +/** + * @brief Set GDMA event callbacks for TX channel + * @note This API will install GDMA interrupt service for the channel internally + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param[in] cbs Group of callback functions + * @param[in] user_data User data, which will be passed to callback functions directly + * @return + * - ESP_OK: Set event callbacks successfully + * - ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument + * - ESP_FAIL: Set event callbacks failed because of other error + */ +esp_err_t gdma_register_tx_event_callbacks(gdma_channel_handle_t dma_chan, gdma_tx_event_callbacks_t *cbs, void *user_data); + +/** + * @brief Set GDMA event callbacks for RX channel + * @note This API will install GDMA interrupt service for the channel internally + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param[in] cbs Group of callback functions + * @param[in] user_data User data, which will be passed to callback functions directly + * @return + * - ESP_OK: Set event callbacks successfully + * - ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument + * - ESP_FAIL: Set event callbacks failed because of other error + */ +esp_err_t gdma_register_rx_event_callbacks(gdma_channel_handle_t dma_chan, gdma_rx_event_callbacks_t *cbs, void *user_data); + +/** + * @brief Set DMA descriptor address and start engine + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @param[in] desc_base_addr Base address of descriptors (usually the descriptors are chained into a link or ring) + * @return + * - ESP_OK: Start DMA engine successfully + * - ESP_ERR_INVALID_ARG: Start DMA engine failed because of invalid argument + * - ESP_FAIL: Start DMA engine failed because of other error + */ +esp_err_t gdma_start(gdma_channel_handle_t dma_chan, intptr_t desc_base_addr); + +/** + * @brief Stop DMA engine + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @return + * - ESP_OK: Stop DMA engine successfully + * - ESP_ERR_INVALID_ARG: Stop DMA engine failed because of invalid argument + * - ESP_FAIL: Stop DMA engine failed because of other error + */ +esp_err_t gdma_stop(gdma_channel_handle_t dma_chan); + +/** + * @brief Make the appended descriptors be aware to the DMA engine + * @note This API could also resume a paused DMA engine, make sure new descriptors have been appended to the descriptor chain before calling it. + * + * @param[in] dma_chan GDMA channel handle, allocated by `gdma_new_channel` + * @return + * - ESP_OK: Send append command to DMA engine successfully + * - ESP_ERR_INVALID_ARG: Send append command to DMA engine failed because of invalid argument + * - ESP_FAIL: Send append command to DMA engine failed because of other error + */ +esp_err_t gdma_append(gdma_channel_handle_t dma_chan); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse.h b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse.h new file mode 100644 index 00000000..9ae3ab08 --- /dev/null +++ b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse.h @@ -0,0 +1,70 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Type of eFuse blocks ESP32C3 + */ +typedef enum { + EFUSE_BLK0 = 0, /**< Number of eFuse BLOCK0. REPEAT_DATA */ + + EFUSE_BLK1 = 1, /**< Number of eFuse BLOCK1. MAC_SPI_8M_SYS */ + + EFUSE_BLK2 = 2, /**< Number of eFuse BLOCK2. SYS_DATA_PART1 */ + EFUSE_BLK_SYS_DATA_PART1 = 2, /**< Number of eFuse BLOCK2. SYS_DATA_PART1 */ + + EFUSE_BLK3 = 3, /**< Number of eFuse BLOCK3. USER_DATA*/ + EFUSE_BLK_USER_DATA = 3, /**< Number of eFuse BLOCK3. USER_DATA*/ + + EFUSE_BLK4 = 4, /**< Number of eFuse BLOCK4. KEY0 */ + EFUSE_BLK_KEY0 = 4, /**< Number of eFuse BLOCK4. KEY0 */ + + EFUSE_BLK5 = 5, /**< Number of eFuse BLOCK5. KEY1 */ + EFUSE_BLK_KEY1 = 5, /**< Number of eFuse BLOCK5. KEY1 */ + + EFUSE_BLK6 = 6, /**< Number of eFuse BLOCK6. KEY2 */ + EFUSE_BLK_KEY2 = 6, /**< Number of eFuse BLOCK6. KEY2 */ + + EFUSE_BLK7 = 7, /**< Number of eFuse BLOCK7. KEY3 */ + EFUSE_BLK_KEY3 = 7, /**< Number of eFuse BLOCK7. KEY3 */ + + EFUSE_BLK8 = 8, /**< Number of eFuse BLOCK8. KEY4 */ + EFUSE_BLK_KEY4 = 8, /**< Number of eFuse BLOCK8. KEY4 */ + + EFUSE_BLK9 = 9, /**< Number of eFuse BLOCK9. KEY5 */ + EFUSE_BLK_KEY5 = 9, /**< Number of eFuse BLOCK9. KEY5 */ + EFUSE_BLK_KEY_MAX = 10, + + EFUSE_BLK10 = 10, /**< Number of eFuse BLOCK10. SYS_DATA_PART2 */ + EFUSE_BLK_SYS_DATA_PART2 = 10, /**< Number of eFuse BLOCK10. SYS_DATA_PART2 */ + + EFUSE_BLK_MAX +} esp_efuse_block_t; + +/** + * @brief Type of coding scheme + */ +typedef enum { + EFUSE_CODING_SCHEME_NONE = 0, /**< None */ + EFUSE_CODING_SCHEME_RS = 3, /**< Reed-Solomon coding */ +} esp_efuse_coding_scheme_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_rtc_calib.h b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_rtc_calib.h new file mode 100644 index 00000000..5dc007f8 --- /dev/null +++ b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_rtc_calib.h @@ -0,0 +1,62 @@ +// Copyright 2020 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 +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Get the RTC calibration efuse version + * + * @return Version of the stored efuse + */ +int esp_efuse_rtc_calib_get_ver(void); + +/** + * @brief Get the init code in the efuse, for the corresponding attenuation. + * + * @param version Version of the stored efuse + * @param atten Attenuation of the init code + * @return The init code stored in efuse + */ +uint16_t esp_efuse_rtc_calib_get_init_code(int version, int atten); + +/** + * @brief Get the calibration digits stored in the efuse, and the corresponding voltage. + * + * @param version Version of the stored efuse + * @param atten Attenuation to use + * @param out_digi Output buffer of the digits + * @param out_vol_mv Output of the voltage, in mV + * @return + * - ESP_ERR_INVALID_ARG: If efuse version or attenuation is invalid + * - ESP_OK: if success + */ +esp_err_t esp_efuse_rtc_calib_get_cal_voltage(int version, int atten, uint32_t* out_digi, uint32_t* out_vol_mv); + +/** + * @brief Get the temperature sensor calibration number delta_T stored in the efuse. + * + * @param version Version of the stored efuse + * + * @return The specification of temperature sensor calibration number in efuse. + */ +float esp_efuse_rtc_calib_get_cal_temp(int version); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_table.h b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_table.h new file mode 100644 index 00000000..13f3f183 --- /dev/null +++ b/tools/sdk/esp32c3/include/efuse/esp32c3/include/esp_efuse_table.h @@ -0,0 +1,144 @@ +// Copyright 2017-2020 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 + +#ifdef __cplusplus +extern "C" { +#endif + + +// md5_digest_table f9a84eb22f94a7bc083b4c6817a33a59 +// This file was generated from the file esp_efuse_table.csv. DO NOT CHANGE THIS FILE MANUALLY. +// If you want to change some fields, you need to change esp_efuse_table.csv file +// then run `efuse_common_table` or `efuse_custom_table` command it will generate this file. +// To show efuse_table run the command 'show_efuse_table'. + + +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_RD_DIS[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_GROUP_1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_GROUP_2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SECURE_BOOT_KEY_REVOKE0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SECURE_BOOT_KEY_REVOKE1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SECURE_BOOT_KEY_REVOKE2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY0_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY1_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY2_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY3_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY4_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY5_PURPOSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SECURE_BOOT_EN[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SECURE_BOOT_AGGRESSIVE_REVOKE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_GROUP_3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_BLK1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SYS_DATA_PART1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_USER_DATA[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY4[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_KEY5[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WR_DIS_SYS_DATA_PART2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY4[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_KEY5[]; +extern const esp_efuse_desc_t* ESP_EFUSE_RD_DIS_SYS_DATA_PART2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_RTC_RAM_BOOT[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_ICACHE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_USB_JTAG[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_DOWNLOAD_ICACHE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_USB_DEVICE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_FORCE_DOWNLOAD[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_USB[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_CAN[]; +extern const esp_efuse_desc_t* ESP_EFUSE_JTAG_SEL_ENABLE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SOFT_DIS_JTAG[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_PAD_JTAG[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT[]; +extern const esp_efuse_desc_t* ESP_EFUSE_USB_DREFH[]; +extern const esp_efuse_desc_t* ESP_EFUSE_USB_DREFL[]; +extern const esp_efuse_desc_t* ESP_EFUSE_USB_EXCHG_PINS[]; +extern const esp_efuse_desc_t* ESP_EFUSE_VDD_SPI_AS_GPIO[]; +extern const esp_efuse_desc_t* ESP_EFUSE_BTLC_GPIO_ENABLE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_POWERGLITCH_EN[]; +extern const esp_efuse_desc_t* ESP_EFUSE_POWER_GLITCH_DSENSE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WDT_DELAY_SEL[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_BOOT_CRYPT_CNT[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_BOOT_KEY_REVOKE0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_BOOT_KEY_REVOKE1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_BOOT_KEY_REVOKE2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_4[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY_PURPOSE_5[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_BOOT_EN[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_BOOT_AGGRESSIVE_REVOKE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FLASH_TPUW[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_DOWNLOAD_MODE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_LEGACY_SPI_BOOT[]; +extern const esp_efuse_desc_t* ESP_EFUSE_UART_PRINT_CHANNEL[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FLASH_ECC_MODE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_DIS_USB_DOWNLOAD_MODE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ENABLE_SECURITY_DOWNLOAD[]; +extern const esp_efuse_desc_t* ESP_EFUSE_UART_PRINT_CONTROL[]; +extern const esp_efuse_desc_t* ESP_EFUSE_PIN_POWER_SELECTION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FLASH_TYPE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FLASH_PAGE_SIZE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FLASH_ECC_EN[]; +extern const esp_efuse_desc_t* ESP_EFUSE_FORCE_SEND_RESUME[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SECURE_VERSION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_MAC_FACTORY[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_CLK[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_Q_D1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_D_D0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_CS[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_HD_D3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_WP_D2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_DQS[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_D4[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_D5[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_D6[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SPI_PAD_CONFIG_D7[]; +extern const esp_efuse_desc_t* ESP_EFUSE_WAFER_VERSION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_PKG_VERSION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_BLOCK1_VERSION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_OPTIONAL_UNIQUE_ID[]; +extern const esp_efuse_desc_t* ESP_EFUSE_BLOCK2_VERSION[]; +extern const esp_efuse_desc_t* ESP_EFUSE_TEMP_CALIB[]; +extern const esp_efuse_desc_t* ESP_EFUSE_OCODE[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_INIT_CODE_ATTEN0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_INIT_CODE_ATTEN1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_INIT_CODE_ATTEN2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_INIT_CODE_ATTEN3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_CAL_VOL_ATTEN0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_CAL_VOL_ATTEN1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_CAL_VOL_ATTEN2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_ADC1_CAL_VOL_ATTEN3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_USER_DATA[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY0[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY1[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY2[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY3[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY4[]; +extern const esp_efuse_desc_t* ESP_EFUSE_KEY5[]; +extern const esp_efuse_desc_t* ESP_EFUSE_SYS_DATA_PART2[]; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/efuse/include/esp_efuse.h b/tools/sdk/esp32c3/include/efuse/include/esp_efuse.h new file mode 100644 index 00000000..01965793 --- /dev/null +++ b/tools/sdk/esp32c3/include/efuse/include/esp_efuse.h @@ -0,0 +1,790 @@ +// Copyright 2017-2018 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "esp_err.h" +#include "esp_log.h" +#include "soc/soc_caps.h" +#include "sdkconfig.h" +#include_next "esp_efuse.h" + +#define ESP_ERR_EFUSE 0x1600 /*!< Base error code for efuse api. */ +#define ESP_OK_EFUSE_CNT (ESP_ERR_EFUSE + 0x01) /*!< OK the required number of bits is set. */ +#define ESP_ERR_EFUSE_CNT_IS_FULL (ESP_ERR_EFUSE + 0x02) /*!< Error field is full. */ +#define ESP_ERR_EFUSE_REPEATED_PROG (ESP_ERR_EFUSE + 0x03) /*!< Error repeated programming of programmed bits is strictly forbidden. */ +#define ESP_ERR_CODING (ESP_ERR_EFUSE + 0x04) /*!< Error while a encoding operation. */ +#define ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS (ESP_ERR_EFUSE + 0x05) /*!< Error not enough unused key blocks available */ + +/** + * @brief Type definition for an eFuse field + */ +typedef struct { + esp_efuse_block_t efuse_block: 8; /**< Block of eFuse */ + uint8_t bit_start; /**< Start bit [0..255] */ + uint16_t bit_count; /**< Length of bit field [1..-]*/ +} esp_efuse_desc_t; + +/** + * @brief Type definition for ROM log scheme + */ +typedef enum { + ESP_EFUSE_ROM_LOG_ALWAYS_ON, /**< Always enable ROM logging */ + ESP_EFUSE_ROM_LOG_ON_GPIO_LOW, /**< ROM logging is enabled when specific GPIO level is low during start up */ + ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH, /**< ROM logging is enabled when specific GPIO level is high during start up */ + ESP_EFUSE_ROM_LOG_ALWAYS_OFF /**< Disable ROM logging permanently */ +} esp_efuse_rom_log_scheme_t; + +/** + * @brief Reads bits from EFUSE field and writes it into an array. + * + * The number of read bits will be limited to the minimum value + * from the description of the bits in "field" structure or "dst_size_bits" required size. + * Use "esp_efuse_get_field_size()" function to determine the length of the field. + * + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * @param[in] field A pointer to the structure describing the fields of efuse. + * @param[out] dst A pointer to array that will contain the result of reading. + * @param[in] dst_size_bits The number of bits required to read. + * If the requested number of bits is greater than the field, + * the number will be limited to the field size. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + */ +esp_err_t esp_efuse_read_field_blob(const esp_efuse_desc_t* field[], void* dst, size_t dst_size_bits); + + +/** + * @brief Read a single bit eFuse field as a boolean value. + * + * @note The value must exist and must be a single bit wide. If there is any possibility of an error + * in the provided arguments, call esp_efuse_read_field_blob() and check the returned value instead. + * + * @note If assertions are enabled and the parameter is invalid, execution will abort + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * @param[in] field A pointer to the structure describing the fields of efuse. + * @return + * - true: The field parameter is valid and the bit is set. + * - false: The bit is not set, or the parameter is invalid and assertions are disabled. + * + */ +bool esp_efuse_read_field_bit(const esp_efuse_desc_t *field[]); + +/** + * @brief Reads bits from EFUSE field and returns number of bits programmed as "1". + * + * If the bits are set not sequentially, they will still be counted. + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * @param[in] field A pointer to the structure describing the fields of efuse. + * @param[out] out_cnt A pointer that will contain the number of programmed as "1" bits. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + */ +esp_err_t esp_efuse_read_field_cnt(const esp_efuse_desc_t* field[], size_t* out_cnt); + +/** + * @brief Writes array to EFUSE field. + * + * The number of write bits will be limited to the minimum value + * from the description of the bits in "field" structure or "src_size_bits" required size. + * Use "esp_efuse_get_field_size()" function to determine the length of the field. + * After the function is completed, the writing registers are cleared. + * @param[in] field A pointer to the structure describing the fields of efuse. + * @param[in] src A pointer to array that contains the data for writing. + * @param[in] src_size_bits The number of bits required to write. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_write_field_blob(const esp_efuse_desc_t* field[], const void* src, size_t src_size_bits); + +/** + * @brief Writes a required count of bits as "1" to EFUSE field. + * + * If there are no free bits in the field to set the required number of bits to "1", + * ESP_ERR_EFUSE_CNT_IS_FULL error is returned, the field will not be partially recorded. + * After the function is completed, the writing registers are cleared. + * @param[in] field A pointer to the structure describing the fields of efuse. + * @param[in] cnt Required number of programmed as "1" bits. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. + */ +esp_err_t esp_efuse_write_field_cnt(const esp_efuse_desc_t* field[], size_t cnt); + +/** + * @brief Write a single bit eFuse field to 1 + * + * For use with eFuse fields that are a single bit. This function will write the bit to value 1 if + * it is not already set, or does nothing if the bit is already set. + * + * This is equivalent to calling esp_efuse_write_field_cnt() with the cnt parameter equal to 1, + * except that it will return ESP_OK if the field is already set to 1. + * + * @param[in] field Pointer to the structure describing the efuse field. + * + * @return + * - ESP_OK: The operation was successfully completed, or the bit was already set to value 1. + * - ESP_ERR_INVALID_ARG: Error in the passed arugments, including if the efuse field is not 1 bit wide. + */ +esp_err_t esp_efuse_write_field_bit(const esp_efuse_desc_t* field[]); + +/** + * @brief Sets a write protection for the whole block. + * + * After that, it is impossible to write to this block. + * The write protection does not apply to block 0. + * @param[in] blk Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. + * - ESP_ERR_NOT_SUPPORTED: The block does not support this command. + */ +esp_err_t esp_efuse_set_write_protect(esp_efuse_block_t blk); + +/** + * @brief Sets a read protection for the whole block. + * + * After that, it is impossible to read from this block. + * The read protection does not apply to block 0. + * @param[in] blk Block number of eFuse. (EFUSE_BLK1, EFUSE_BLK2 and EFUSE_BLK3) + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_CNT_IS_FULL: Not all requested cnt bits is set. + * - ESP_ERR_NOT_SUPPORTED: The block does not support this command. + */ +esp_err_t esp_efuse_set_read_protect(esp_efuse_block_t blk); + +/** + * @brief Returns the number of bits used by field. + * + * @param[in] field A pointer to the structure describing the fields of efuse. + * + * @return Returns the number of bits used by field. + */ +int esp_efuse_get_field_size(const esp_efuse_desc_t* field[]); + +/** + * @brief Returns value of efuse register. + * + * This is a thread-safe implementation. + * Example: EFUSE_BLK2_RDATA3_REG where (blk=2, num_reg=3) + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * @param[in] blk Block number of eFuse. + * @param[in] num_reg The register number in the block. + * + * @return Value of register + */ +uint32_t esp_efuse_read_reg(esp_efuse_block_t blk, unsigned int num_reg); + +/** + * @brief Write value to efuse register. + * + * Apply a coding scheme if necessary. + * This is a thread-safe implementation. + * Example: EFUSE_BLK3_WDATA0_REG where (blk=3, num_reg=0) + * @param[in] blk Block number of eFuse. + * @param[in] num_reg The register number in the block. + * @param[in] val Value to write. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + */ +esp_err_t esp_efuse_write_reg(esp_efuse_block_t blk, unsigned int num_reg, uint32_t val); + +/** + * @brief Return efuse coding scheme for blocks. + * + * Note: The coding scheme is applicable only to 1, 2 and 3 blocks. For 0 block, the coding scheme is always ``NONE``. + * + * @param[in] blk Block number of eFuse. + * @return Return efuse coding scheme for blocks + */ +esp_efuse_coding_scheme_t esp_efuse_get_coding_scheme(esp_efuse_block_t blk); + +/** + * @brief Read key to efuse block starting at the offset and the required size. + * + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * @param[in] blk Block number of eFuse. + * @param[in] dst_key A pointer to array that will contain the result of reading. + * @param[in] offset_in_bits Start bit in block. + * @param[in] size_bits The number of bits required to read. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_read_block(esp_efuse_block_t blk, void* dst_key, size_t offset_in_bits, size_t size_bits); + +/** + * @brief Write key to efuse block starting at the offset and the required size. + * + * @param[in] blk Block number of eFuse. + * @param[in] src_key A pointer to array that contains the key for writing. + * @param[in] offset_in_bits Start bit in block. + * @param[in] size_bits The number of bits required to write. + * + * @return + * - ESP_OK: The operation was successfully completed. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits + */ +esp_err_t esp_efuse_write_block(esp_efuse_block_t blk, const void* src_key, size_t offset_in_bits, size_t size_bits); + +/** + * @brief Returns chip version from efuse + * + * @return chip version + */ +uint8_t esp_efuse_get_chip_ver(void); + +/** + * @brief Returns chip package from efuse + * + * @return chip package + */ +uint32_t esp_efuse_get_pkg_ver(void); + +/** + * @brief Permanently update values written to the efuse write registers + * + * After updating EFUSE_BLKx_WDATAx_REG registers with new values to + * write, call this function to permanently write them to efuse. + * + * @note Setting bits in efuse is permanent, they cannot be unset. + * + * @note Due to this restriction you don't need to copy values to + * Efuse write registers from the matching read registers, bits which + * are set in the read register but unset in the matching write + * register will be unchanged when new values are burned. + * + * @note This function is not threadsafe, if calling code updates + * efuse values from multiple tasks then this is caller's + * responsibility to serialise. + * + * After burning new efuses, the read registers are updated to match + * the new efuse values. + */ +void esp_efuse_burn_new_values(void); + +/** + * @brief Reset efuse write registers + * + * Efuse write registers are written to zero, to negate + * any changes that have been staged here. + * + * @note This function is not threadsafe, if calling code updates + * efuse values from multiple tasks then this is caller's + * responsibility to serialise. + */ +void esp_efuse_reset(void); + +#ifdef CONFIG_IDF_TARGET_ESP32 +/** + * @brief Disable BASIC ROM Console via efuse + * + * By default, if booting from flash fails the ESP32 will boot a + * BASIC console in ROM. + * + * Call this function (from bootloader or app) to permanently disable the console on this chip. + * + */ +void esp_efuse_disable_basic_rom_console(void); +#endif + + +/** + * @brief Disable ROM Download Mode via eFuse + * + * Permanently disables the ROM Download Mode feature. Once disabled, if the SoC is booted with + * strapping pins set for ROM Download Mode then an error is printed instead. + * + * @note Not all SoCs support this option. An error will be returned if called on an ESP32 + * with a silicon revision lower than 3, as these revisions do not support this option. + * + * @note If ROM Download Mode is already disabled, this function does nothing and returns success. + * + * @return + * - ESP_OK If the eFuse was successfully burned, or had already been burned. + * - ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of disabling UART download mode + * - ESP_ERR_INVALID_STATE (ESP32 only) This eFuse is write protected and cannot be written + */ +esp_err_t esp_efuse_disable_rom_download_mode(void); + +/** + * @brief Set boot ROM log scheme via eFuse + * + * @note By default, the boot ROM will always print to console. This API can be called to set the log scheme only once per chip, + * once the value is changed from the default it can't be changed again. + * + * @param log_scheme Supported ROM log scheme + * @return + * - ESP_OK If the eFuse was successfully burned, or had already been burned. + * - ESP_ERR_NOT_SUPPORTED (ESP32 only) This SoC is not capable of setting ROM log scheme + * - ESP_ERR_INVALID_STATE This eFuse is write protected or has been burned already + */ +esp_err_t esp_efuse_set_rom_log_scheme(esp_efuse_rom_log_scheme_t log_scheme); + +#if SOC_SUPPORTS_SECURE_DL_MODE +/** + * @brief Switch ROM Download Mode to Secure Download mode via eFuse + * + * Permanently enables Secure Download mode. This mode limits the use of ROM Download Mode functions + * to simple flash read, write and erase operations, plus a command to return a summary of currently + * enabled security features. + * + * @note If Secure Download mode is already enabled, this function does nothing and returns success. + * + * @note Disabling the ROM Download Mode also disables Secure Download Mode. + * + * @return + * - ESP_OK If the eFuse was successfully burned, or had already been burned. + * - ESP_ERR_INVALID_STATE ROM Download Mode has been disabled via eFuse, so Secure Download mode is unavailable. + */ +esp_err_t esp_efuse_enable_rom_secure_download_mode(void); +#endif + +/** + * @brief Write random data to efuse key block write registers + * + * @note Caller is responsible for ensuring efuse + * block is empty and not write protected, before calling. + * + * @note Behaviour depends on coding scheme: a 256-bit key is + * generated and written for Coding Scheme "None", a 192-bit key + * is generated, extended to 256-bits by the Coding Scheme, + * and then writtten for 3/4 Coding Scheme. + * + * @note This function does not burn the new values, caller should + * call esp_efuse_burn_new_values() when ready to do this. + * + * @param blk_wdata0_reg Address of the first data write register + * in the block + */ +void esp_efuse_write_random_key(uint32_t blk_wdata0_reg); + +/** + * @brief Return secure_version from efuse field. + * @return Secure version from efuse field + */ +uint32_t esp_efuse_read_secure_version(void); + +/** + * @brief Check secure_version from app and secure_version and from efuse field. + * + * @param secure_version Secure version from app. + * @return + * - True: If version of app is equal or more then secure_version from efuse. + */ +bool esp_efuse_check_secure_version(uint32_t secure_version); + +/** + * @brief Write efuse field by secure_version value. + * + * Update the secure_version value is available if the coding scheme is None. + * Note: Do not use this function in your applications. This function is called as part of the other API. + * + * @param[in] secure_version Secure version from app. + * @return + * - ESP_OK: Successful. + * - ESP_FAIL: secure version of app cannot be set to efuse field. + * - ESP_ERR_NOT_SUPPORTED: Anti rollback is not supported with the 3/4 and Repeat coding scheme. + */ +esp_err_t esp_efuse_update_secure_version(uint32_t secure_version); + +/** + * @brief Initializes variables: offset and size to simulate the work of an eFuse. + * + * Note: To simulate the work of an eFuse need to set CONFIG_BOOTLOADER_EFUSE_SECURE_VERSION_EMULATE option + * and to add in the partition.csv file a line `efuse_em, data, efuse, , 0x2000,`. + * + * @param[in] offset The starting address of the partition where the eFuse data will be located. + * @param[in] size The size of the partition. + */ +void esp_efuse_init(uint32_t offset, uint32_t size); + +/** + * @brief Set the batch mode of writing fields. + * + * This mode allows you to write the fields in the batch mode when need to burn several efuses at one time. + * To enable batch mode call begin() then perform as usually the necessary operations + * read and write and at the end call commit() to actually burn all written efuses. + * The batch mode can be used nested. The commit will be done by the last commit() function. + * The number of begin() functions should be equal to the number of commit() functions. + * + * @note Please note that reading in the batch mode does not show uncommitted changes. + * + * Note: If batch mode is enabled by the first task, at this time the second task cannot write/read efuses. + * The second task will wait for the first task to complete the batch operation. + * + * \code{c} + * // Example of using the batch writing mode. + * + * // set the batch writing mode + * esp_efuse_batch_write_begin(); + * + * // use any writing functions as usual + * esp_efuse_write_field_blob(ESP_EFUSE_...); + * esp_efuse_write_field_cnt(ESP_EFUSE_...); + * esp_efuse_set_write_protect(EFUSE_BLKx); + * esp_efuse_write_reg(EFUSE_BLKx, ...); + * esp_efuse_write_block(EFUSE_BLKx, ...); + * esp_efuse_write(ESP_EFUSE_1, 3); // ESP_EFUSE_1 == 1, here we write a new value = 3. The changes will be burn by the commit() function. + * esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 1 because uncommitted changes are not readable, it will be available only after commit. + * ... + * + * // esp_efuse_batch_write APIs can be called recursively. + * esp_efuse_batch_write_begin(); + * esp_efuse_set_write_protect(EFUSE_BLKx); + * esp_efuse_batch_write_commit(); // the burn will be skipped here, it will be done in the last commit(). + * + * ... + * + * // Write all of these fields to the efuse registers + * esp_efuse_batch_write_commit(); + * esp_efuse_read_...(ESP_EFUSE_1); // this function returns ESP_EFUSE_1 == 3. + * + * \endcode + * + * @return + * - ESP_OK: Successful. + */ +esp_err_t esp_efuse_batch_write_begin(void); + +/** + * @brief Reset the batch mode of writing fields. + * + * It will reset the batch writing mode and any written changes. + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_STATE: Tha batch mode was not set. + */ +esp_err_t esp_efuse_batch_write_cancel(void); + +/** + * @brief Writes all prepared data for the batch mode. + * + * Must be called to ensure changes are written to the efuse registers. + * After this the batch writing mode will be reset. + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_STATE: The deferred writing mode was not set. + */ +esp_err_t esp_efuse_batch_write_commit(void); + +/** + * @brief Checks that the given block is empty. + * + * @return + * - True: The block is empty. + * - False: The block is not empty or was an error. + */ +bool esp_efuse_block_is_empty(esp_efuse_block_t block); + +/** + * @brief Returns a read protection for the key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return True: The key block is read protected + * False: The key block is readable. + */ +bool esp_efuse_get_key_dis_read(esp_efuse_block_t block); + +/** + * @brief Sets a read protection for the key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_key_dis_read(esp_efuse_block_t block); + +/** + * @brief Returns a write protection for the key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return True: The key block is write protected + * False: The key block is writeable. + */ +bool esp_efuse_get_key_dis_write(esp_efuse_block_t block); + +/** + * @brief Sets a write protection for the key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_key_dis_write(esp_efuse_block_t block); + +/** + * @brief Returns true if the key block is unused, false otherwise. + * + * An unused key block is all zero content, not read or write protected, + * and has purpose 0 (ESP_EFUSE_KEY_PURPOSE_USER) + * + * @param block key block to check. + * + * @return + * - True if key block is unused, + * - False if key block is used or the specified block index is not a key block. + */ +bool esp_efuse_key_block_unused(esp_efuse_block_t block); + +#ifndef CONFIG_IDF_TARGET_ESP32 + +/** + * @brief Type of key purpose + */ +typedef enum { + ESP_EFUSE_KEY_PURPOSE_USER = 0, + ESP_EFUSE_KEY_PURPOSE_RESERVED = 1, + ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_1 = 2, + ESP_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_2 = 3, + ESP_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY = 4, + ESP_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL = 5, + ESP_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG = 6, + ESP_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE = 7, + ESP_EFUSE_KEY_PURPOSE_HMAC_UP = 8, + ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0 = 9, + ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1 = 10, + ESP_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2 = 11, + ESP_EFUSE_KEY_PURPOSE_MAX, +} esp_efuse_purpose_t; + + +/** + * @brief Returns a pointer to a key purpose for an efuse key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * To get the value of this field use esp_efuse_read_field_blob() or esp_efuse_get_key_purpose(). + * + * @return Pointer: If Successful returns a pointer to the corresponding efuse field otherwise NULL. + */ +const esp_efuse_desc_t **esp_efuse_get_purpose_field(esp_efuse_block_t block); + +/** + * @brief Returns a pointer to a key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return Pointer: If Successful returns a pointer to the corresponding efuse field otherwise NULL. + */ +const esp_efuse_desc_t** esp_efuse_get_key(esp_efuse_block_t block); + +/** + * @brief Returns the current purpose set for an efuse key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return + * - Value: If Successful, it returns the value of the purpose related to the given key block. + * - ESP_EFUSE_KEY_PURPOSE_MAX: Otherwise. + */ +esp_efuse_purpose_t esp_efuse_get_key_purpose(esp_efuse_block_t block); + +/** + * @brief Sets a key purpose for an efuse key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * @param[in] purpose Key purpose. + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_key_purpose(esp_efuse_block_t block, esp_efuse_purpose_t purpose); + +/** + * @brief Returns a write protection of the key purpose field for an efuse key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return True: The key purpose is write protected. + * False: The key purpose is writeable. + */ +bool esp_efuse_get_keypurpose_dis_write(esp_efuse_block_t block); + +/** + * @brief Sets a write protection of the key purpose field for an efuse key block. + * + * @param[in] block A key block in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_keypurpose_dis_write(esp_efuse_block_t block); + +/** + * @brief Find a key block with the particular purpose set. + * + * @param[in] purpose Purpose to search for. + * @param[out] block Pointer in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX which will be set to the key block if found. + * Can be NULL, if only need to test the key block exists. + * + * @return + * - True: If found, + * - False: If not found (value at block pointer is unchanged). + */ +bool esp_efuse_find_purpose(esp_efuse_purpose_t purpose, esp_efuse_block_t *block); + +/** + * @brief Search for an unused key block and return the first one found. + * + * See esp_efuse_key_block_unused for a description of an unused key block. + * + * @return First unused key block, or EFUSE_BLK_KEY_MAX if no unused key block is found. + */ +esp_efuse_block_t esp_efuse_find_unused_key_block(void); + +/** + * @brief Return the number of unused efuse key blocks in the range EFUSE_BLK_KEY0..EFUSE_BLK_KEY_MAX + */ +unsigned esp_efuse_count_unused_key_blocks(void); + +/** + * @brief Returns the status of the Secure Boot public key digest revocation bit. + * + * @param[in] num_digest The number of digest in range 0..2 + * + * @return + * - True: If key digest is revoked, + * - False; If key digest is not revoked. + */ +bool esp_efuse_get_digest_revoke(unsigned num_digest); + +/** + * @brief Sets the Secure Boot public key digest revocation bit. + * + * @param[in] num_digest The number of digest in range 0..2 + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_digest_revoke(unsigned num_digest); + +/** + * @brief Returns a write protection of the Secure Boot public key digest revocation bit. + * + * @param[in] num_digest The number of digest in range 0..2 + * + * @return True: The revocation bit is write protected. + * False: The revocation bit is writeable. + */ +bool esp_efuse_get_write_protect_of_digest_revoke(unsigned num_digest); + +/** + * @brief Sets a write protection of the Secure Boot public key digest revocation bit. + * + * @param[in] num_digest The number of digest in range 0..2 + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_set_write_protect_of_digest_revoke(unsigned num_digest); + +/** + * @brief Program a block of key data to an efuse block + * + * The burn of a key, protection bits, and a purpose happens in batch mode. + * + * @param[in] block Block to read purpose for. Must be in range EFUSE_BLK_KEY0 to EFUSE_BLK_KEY_MAX. Key block must be unused (esp_efuse_key_block_unused). + * @param[in] purpose Purpose to set for this key. Purpose must be already unset. + * @param[in] key Pointer to data to write. + * @param[in] key_size_bytes Bytes length of data to write. + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_write_key(esp_efuse_block_t block, esp_efuse_purpose_t purpose, const void *key, size_t key_size_bytes); + +/** + * @brief Program keys to unused efuse blocks + * + * The burn of keys, protection bits, and purposes happens in batch mode. + * + * @param[in] purposes Array of purposes (purpose[number_of_keys]). + * @param[in] keys Array of keys (uint8_t keys[number_of_keys][32]). Each key is 32 bytes long. + * @param[in] number_of_keys The number of keys to write (up to 6 keys). + * + * @return + * - ESP_OK: Successful. + * - ESP_ERR_INVALID_ARG: Error in the passed arguments. + * - ESP_ERR_INVALID_STATE: Error in efuses state, unused block not found. + * - ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS: Error not enough unused key blocks available + * - ESP_ERR_EFUSE_REPEATED_PROG: Error repeated programming of programmed bits is strictly forbidden. + * - ESP_ERR_CODING: Error range of data does not match the coding scheme. + */ +esp_err_t esp_efuse_write_keys(esp_efuse_purpose_t purposes[], uint8_t keys[][32], unsigned number_of_keys); + +#endif // not CONFIG_IDF_TARGET_ESP32 + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp-tls/esp-tls-crypto/esp_tls_crypto.h b/tools/sdk/esp32c3/include/esp-tls/esp-tls-crypto/esp_tls_crypto.h new file mode 100644 index 00000000..2336a9ce --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/esp-tls-crypto/esp_tls_crypto.h @@ -0,0 +1,68 @@ +// Copyright 2020 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. +#ifndef _ESP_TLS_CRYPTO_H +#define _ESP_TLS_CRYPTO_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Calculate sha1 sum + * esp-tls abstraction for crypto sha1 API, calculates the sha1 sum(digest) of + * the data provided in input which is of ilen size and returns + * a 20 char sha1 sum + * @param[in] input Input array + * @param[in] ilen Length of Input array + * @param[out] output calculated sha1 sum + * + * @return + * mbedtls stack:- + * - MBEDTLS_ERR_SHA1_BAD_INPUT_DATA on BAD INPUT. + * - 0 on success. + * wolfssl stack:- + * - -1 on failure. + * - 0 on success. + */ +int esp_crypto_sha1(const unsigned char *input, + size_t ilen, + unsigned char output[20]); + +/** + * @brief Do Base64 encode of the src data + * + * @param[in] dst destination buffer + * @param[in] dlen length of destination buffer + * @param[out] olen number of bytes written + * @param[in] src src buffer to be encoded + * @param[in] slen src buffer len + * + * @return + * mbedtls stack:- + * - MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL if buffer is of insufficient size. + * - 0 if successful. + * wolfssl stack:- + * - <0 on failure. + * - 0 if succcessful. + */ +int esp_crypto_base64_encode(unsigned char *dst, size_t dlen, + size_t *olen, const unsigned char *src, + size_t slen); + +#ifdef __cplusplus +} +#endif +#endif /* _ESP_TLS_CRYPTO_H */ diff --git a/tools/sdk/esp32c3/include/esp-tls/esp_tls.h b/tools/sdk/esp32c3/include/esp-tls/esp_tls.h new file mode 100644 index 00000000..72a78c5e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/esp_tls.h @@ -0,0 +1,606 @@ +// Copyright 2017-2018 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. +#ifndef _ESP_TLS_H_ +#define _ESP_TLS_H_ + +#include +#include +#include +#include "esp_err.h" +#include "esp_tls_errors.h" +#ifdef CONFIG_ESP_TLS_USING_MBEDTLS +#include "mbedtls/platform.h" +#include "mbedtls/net_sockets.h" +#include "mbedtls/esp_debug.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/error.h" +#include "mbedtls/certs.h" +#elif CONFIG_ESP_TLS_USING_WOLFSSL +#include "wolfssl/wolfcrypt/settings.h" +#include "wolfssl/ssl.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief ESP-TLS Connection State + */ +typedef enum esp_tls_conn_state { + ESP_TLS_INIT = 0, + ESP_TLS_CONNECTING, + ESP_TLS_HANDSHAKE, + ESP_TLS_FAIL, + ESP_TLS_DONE, +} esp_tls_conn_state_t; + +typedef enum esp_tls_role { + ESP_TLS_CLIENT = 0, + ESP_TLS_SERVER, +} esp_tls_role_t; + +/** + * @brief ESP-TLS preshared key and hint structure + */ +typedef struct psk_key_hint { + const uint8_t* key; /*!< key in PSK authentication mode in binary format */ + const size_t key_size; /*!< length of the key */ + const char* hint; /*!< hint in PSK authentication mode in string format */ +} psk_hint_key_t; + +/** +* @brief Keep alive parameters structure +*/ +typedef struct tls_keep_alive_cfg { + bool keep_alive_enable; /*!< Enable keep-alive timeout */ + int keep_alive_idle; /*!< Keep-alive idle time (second) */ + int keep_alive_interval; /*!< Keep-alive interval time (second) */ + int keep_alive_count; /*!< Keep-alive packet retry send count */ +} tls_keep_alive_cfg_t; + +/** + * @brief ESP-TLS configuration parameters + * + * @note Note about format of certificates: + * - This structure includes certificates of a Certificate Authority, of client or server as well + * as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be + * NULL terminated (with NULL character included in certificate size). + * - Certificate Authority's certificate may be a chain of certificates in case of PEM format, + * but could be only one certificate in case of DER format + * - Variables names of certificates and private key buffers and sizes are defined as unions providing + * backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format + * was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes. + */ +typedef struct esp_tls_cfg { + const char **alpn_protos; /*!< Application protocols required for HTTP2. + If HTTP2/ALPN support is required, a list + of protocols that should be negotiated. + The format is length followed by protocol + name. + For the most common cases the following is ok: + const char **alpn_protos = { "h2", NULL }; + - where 'h2' is the protocol name */ + + union { + const unsigned char *cacert_buf; /*!< Certificate Authority's certificate in a buffer. + Format may be PEM or DER, depending on mbedtls-support + This buffer should be NULL terminated in case of PEM */ + const unsigned char *cacert_pem_buf; /*!< CA certificate buffer legacy name */ + }; + + union { + unsigned int cacert_bytes; /*!< Size of Certificate Authority certificate + pointed to by cacert_buf + (including NULL-terminator in case of PEM format) */ + unsigned int cacert_pem_bytes; /*!< Size of Certificate Authority certificate legacy name */ + }; + + union { + const unsigned char *clientcert_buf; /*!< Client certificate in a buffer + Format may be PEM or DER, depending on mbedtls-support + This buffer should be NULL terminated in case of PEM */ + const unsigned char *clientcert_pem_buf; /*!< Client certificate legacy name */ + }; + + union { + unsigned int clientcert_bytes; /*!< Size of client certificate pointed to by + clientcert_pem_buf + (including NULL-terminator in case of PEM format) */ + unsigned int clientcert_pem_bytes; /*!< Size of client certificate legacy name */ + }; + + union { + const unsigned char *clientkey_buf; /*!< Client key in a buffer + Format may be PEM or DER, depending on mbedtls-support + This buffer should be NULL terminated in case of PEM */ + const unsigned char *clientkey_pem_buf; /*!< Client key legacy name */ + }; + + union { + unsigned int clientkey_bytes; /*!< Size of client key pointed to by + clientkey_pem_buf + (including NULL-terminator in case of PEM format) */ + unsigned int clientkey_pem_bytes; /*!< Size of client key legacy name */ + }; + + const unsigned char *clientkey_password;/*!< Client key decryption password string */ + + unsigned int clientkey_password_len; /*!< String length of the password pointed to by + clientkey_password */ + + bool non_block; /*!< Configure non-blocking mode. If set to true the + underneath socket will be configured in non + blocking mode after tls session is established */ + + bool use_secure_element; /*!< Enable this option to use secure element or + atecc608a chip ( Integrated with ESP32-WROOM-32SE ) */ + + int timeout_ms; /*!< Network timeout in milliseconds */ + + bool use_global_ca_store; /*!< Use a global ca_store for all the connections in which + this bool is set. */ + + const char *common_name; /*!< If non-NULL, server certificate CN must match this name. + If NULL, server certificate CN must match hostname. */ + + bool skip_common_name; /*!< Skip any validation of server certificate CN field */ + + tls_keep_alive_cfg_t *keep_alive_cfg; /*!< Enable TCP keep-alive timeout for SSL connection */ + + const psk_hint_key_t* psk_hint_key; /*!< Pointer to PSK hint and key. if not NULL (and certificates are NULL) + then PSK authentication is enabled with configured setup. + Important note: the pointer must be valid for connection */ + + esp_err_t (*crt_bundle_attach)(void *conf); + /*!< Function pointer to esp_crt_bundle_attach. Enables the use of certification + bundle for server verification, must be enabled in menuconfig */ + + void *ds_data; /*!< Pointer for digital signature peripheral context */ + bool is_plain_tcp; /*!< Use non-TLS connection: When set to true, the esp-tls uses + plain TCP transport rather then TLS/SSL connection */ + struct ifreq *if_name; /*!< The name of interface for data to go through. Use the default interface without setting */ +} esp_tls_cfg_t; + +#ifdef CONFIG_ESP_TLS_SERVER +typedef struct esp_tls_cfg_server { + const char **alpn_protos; /*!< Application protocols required for HTTP2. + If HTTP2/ALPN support is required, a list + of protocols that should be negotiated. + The format is length followed by protocol + name. + For the most common cases the following is ok: + const char **alpn_protos = { "h2", NULL }; + - where 'h2' is the protocol name */ + + union { + const unsigned char *cacert_buf; /*!< Client CA certificate in a buffer. + This buffer should be NULL terminated */ + const unsigned char *cacert_pem_buf; /*!< Client CA certificate legacy name */ + }; + + union { + unsigned int cacert_bytes; /*!< Size of client CA certificate + pointed to by cacert_pem_buf */ + unsigned int cacert_pem_bytes; /*!< Size of client CA certificate legacy name */ + }; + + union { + const unsigned char *servercert_buf; /*!< Server certificate in a buffer + This buffer should be NULL terminated */ + const unsigned char *servercert_pem_buf; /*!< Server certificate legacy name */ + }; + + union { + unsigned int servercert_bytes; /*!< Size of server certificate pointed to by + servercert_pem_buf */ + unsigned int servercert_pem_bytes; /*!< Size of server certificate legacy name */ + }; + + union { + const unsigned char *serverkey_buf; /*!< Server key in a buffer + This buffer should be NULL terminated */ + const unsigned char *serverkey_pem_buf; /*!< Server key legacy name */ + }; + + union { + unsigned int serverkey_bytes; /*!< Size of server key pointed to by + serverkey_pem_buf */ + unsigned int serverkey_pem_bytes; /*!< Size of server key legacy name */ + }; + + const unsigned char *serverkey_password; /*!< Server key decryption password string */ + + unsigned int serverkey_password_len; /*!< String length of the password pointed to by + serverkey_password */ + +} esp_tls_cfg_server_t; +#endif /* ! CONFIG_ESP_TLS_SERVER */ + +/** + * @brief ESP-TLS Connection Handle + */ +typedef struct esp_tls { +#ifdef CONFIG_ESP_TLS_USING_MBEDTLS + mbedtls_ssl_context ssl; /*!< TLS/SSL context */ + + mbedtls_entropy_context entropy; /*!< mbedTLS entropy context structure */ + + mbedtls_ctr_drbg_context ctr_drbg; /*!< mbedTLS ctr drbg context structure. + CTR_DRBG is deterministic random + bit generation based on AES-256 */ + + mbedtls_ssl_config conf; /*!< TLS/SSL configuration to be shared + between mbedtls_ssl_context + structures */ + + mbedtls_net_context server_fd; /*!< mbedTLS wrapper type for sockets */ + + mbedtls_x509_crt cacert; /*!< Container for the X.509 CA certificate */ + + mbedtls_x509_crt *cacert_ptr; /*!< Pointer to the cacert being used. */ + + mbedtls_x509_crt clientcert; /*!< Container for the X.509 client certificate */ + + mbedtls_pk_context clientkey; /*!< Container for the private key of the client + certificate */ +#ifdef CONFIG_ESP_TLS_SERVER + mbedtls_x509_crt servercert; /*!< Container for the X.509 server certificate */ + + mbedtls_pk_context serverkey; /*!< Container for the private key of the server + certificate */ +#endif +#elif CONFIG_ESP_TLS_USING_WOLFSSL + void *priv_ctx; + void *priv_ssl; +#endif + int sockfd; /*!< Underlying socket file descriptor. */ + + ssize_t (*read)(struct esp_tls *tls, char *data, size_t datalen); /*!< Callback function for reading data from TLS/SSL + connection. */ + + ssize_t (*write)(struct esp_tls *tls, const char *data, size_t datalen); /*!< Callback function for writing data to TLS/SSL + connection. */ + + esp_tls_conn_state_t conn_state; /*!< ESP-TLS Connection state */ + + fd_set rset; /*!< read file descriptors */ + + fd_set wset; /*!< write file descriptors */ + + bool is_tls; /*!< indicates connection type (TLS or NON-TLS) */ + + esp_tls_role_t role; /*!< esp-tls role + - ESP_TLS_CLIENT + - ESP_TLS_SERVER */ + + esp_tls_error_handle_t error_handle; /*!< handle to error descriptor */ + +} esp_tls_t; + + +/** + * @brief Create TLS connection + * + * This function allocates and initializes esp-tls structure handle. + * + * @return tls Pointer to esp-tls as esp-tls handle if successfully initialized, + * NULL if allocation error + */ +esp_tls_t *esp_tls_init(void); + + + + +/** + * @brief Create a new blocking TLS/SSL connection + * + * This function establishes a TLS/SSL connection with the specified host in blocking manner. + * + * Note: This API is present for backward compatibility reasons. Alternative function + * with the same functionality is `esp_tls_conn_new_sync` (and its asynchronous version + * `esp_tls_conn_new_async`) + * + * @param[in] hostname Hostname of the host. + * @param[in] hostlen Length of hostname. + * @param[in] port Port number of the host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. If you wish to open + * non-TLS connection, keep this NULL. For TLS connection, + * a pass pointer to esp_tls_cfg_t. At a minimum, this + * structure should be zero-initialized. + * + * @return pointer to esp_tls_t, or NULL if connection couldn't be opened. + */ +esp_tls_t *esp_tls_conn_new(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg) __attribute__ ((deprecated)); + +/** + * @brief Create a new blocking TLS/SSL connection + * + * This function establishes a TLS/SSL connection with the specified host in blocking manner. + * + * @param[in] hostname Hostname of the host. + * @param[in] hostlen Length of hostname. + * @param[in] port Port number of the host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. If you wish to open + * non-TLS connection, keep this NULL. For TLS connection, + * a pass pointer to esp_tls_cfg_t. At a minimum, this + * structure should be zero-initialized. + * @param[in] tls Pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 If connection establishment fails. + * - 1 If connection establishment is successful. + * - 0 If connection state is in progress. + */ +int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls); + +/** + * @brief Create a new blocking TLS/SSL connection with a given "HTTP" url + * + * The behaviour is same as esp_tls_conn_new() API. However this API accepts host's url. + * + * @param[in] url url of host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. If you wish to open + * non-TLS connection, keep this NULL. For TLS connection, + * a pass pointer to 'esp_tls_cfg_t'. At a minimum, this + * structure should be zero-initialized. + * @return pointer to esp_tls_t, or NULL if connection couldn't be opened. + */ +esp_tls_t *esp_tls_conn_http_new(const char *url, const esp_tls_cfg_t *cfg); + +/** + * @brief Create a new non-blocking TLS/SSL connection + * + * This function initiates a non-blocking TLS/SSL connection with the specified host, but due to + * its non-blocking nature, it doesn't wait for the connection to get established. + * + * @param[in] hostname Hostname of the host. + * @param[in] hostlen Length of hostname. + * @param[in] port Port number of the host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. `non_block` member of + * this structure should be set to be true. + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 If connection establishment fails. + * - 0 If connection establishment is in progress. + * - 1 If connection establishment is successful. + */ +int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls); + +/** + * @brief Create a new non-blocking TLS/SSL connection with a given "HTTP" url + * + * The behaviour is same as esp_tls_conn_new() API. However this API accepts host's url. + * + * @param[in] url url of host. + * @param[in] cfg TLS configuration as esp_tls_cfg_t. + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 If connection establishment fails. + * - 0 If connection establishment is in progress. + * - 1 If connection establishment is successful. + */ +int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls); + +/** + * @brief Write from buffer 'data' into specified tls connection. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * @param[in] data Buffer from which data will be written. + * @param[in] datalen Length of data buffer. + * + * @return + * - >=0 if write operation was successful, the return value is the number + * of bytes actually written to the TLS/SSL connection. + * - <0 if write operation was not successful, because either an + * error occured or an action must be taken by the calling process. + */ +static inline ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen) +{ + return tls->write(tls, (char *)data, datalen); +} + +/** + * @brief Read from specified tls connection into the buffer 'data'. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * @param[in] data Buffer to hold read data. + * @param[in] datalen Length of data buffer. + * + * @return + * - >0 if read operation was successful, the return value is the number + * of bytes actually read from the TLS/SSL connection. + * - 0 if read operation was not successful. The underlying + * connection was closed. + * - <0 if read operation was not successful, because either an + * error occured or an action must be taken by the calling process. + */ +static inline ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen) +{ + return tls->read(tls, (char *)data, datalen); +} + +/** + * @brief Compatible version of esp_tls_conn_destroy() to close the TLS/SSL connection + * + * @note This API will be removed in IDFv5.0 + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + */ +void esp_tls_conn_delete(esp_tls_t *tls); + +/** + * @brief Close the TLS/SSL connection and free any allocated resources. + * + * This function should be called to close each tls connection opened with esp_tls_conn_new() or + * esp_tls_conn_http_new() APIs. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return - 0 on success + * - -1 if socket error or an invalid argument + */ +int esp_tls_conn_destroy(esp_tls_t *tls); + +/** + * @brief Return the number of application data bytes remaining to be + * read from the current record + * + * This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API. + * + * @param[in] tls pointer to esp-tls as esp-tls handle. + * + * @return + * - -1 in case of invalid arg + * - bytes available in the application data + * record read buffer + */ +ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls); + +/** + * @brief Returns the connection socket file descriptor from esp_tls session + * + * @param[in] tls handle to esp_tls context + * + * @param[out] sockfd int pointer to sockfd value. + * + * @return - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection + * - ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL) + */ +esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd); + +/** + * @brief Create a global CA store, initially empty. + * + * This function should be called if the application wants to use the same CA store for multiple connections. + * This function initialises the global CA store which can be then set by calling esp_tls_set_global_ca_store(). + * To be effective, this function must be called before any call to esp_tls_set_global_ca_store(). + * + * @return + * - ESP_OK if creating global CA store was successful. + * - ESP_ERR_NO_MEM if an error occured when allocating the mbedTLS resources. + */ +esp_err_t esp_tls_init_global_ca_store(void); + +/** + * @brief Set the global CA store with the buffer provided in pem format. + * + * This function should be called if the application wants to set the global CA store for + * multiple connections i.e. to add the certificates in the provided buffer to the certificate chain. + * This function implicitly calls esp_tls_init_global_ca_store() if it has not already been called. + * The application must call this function before calling esp_tls_conn_new(). + * + * @param[in] cacert_pem_buf Buffer which has certificates in pem format. This buffer + * is used for creating a global CA store, which can be used + * by other tls connections. + * @param[in] cacert_pem_bytes Length of the buffer. + * + * @return + * - ESP_OK if adding certificates was successful. + * - Other if an error occured or an action must be taken by the calling process. + */ +esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes); + +/** + * @brief Free the global CA store currently being used. + * + * The memory being used by the global CA store to store all the parsed certificates is + * freed up. The application can call this API if it no longer needs the global CA store. + */ +void esp_tls_free_global_ca_store(void); + +/** + * @brief Returns last error in esp_tls with detailed mbedtls related error codes. + * The error information is cleared internally upon return + * + * @param[in] h esp-tls error handle. + * @param[out] esp_tls_code last error code returned from mbedtls api (set to zero if none) + * This pointer could be NULL if caller does not care about esp_tls_code + * @param[out] esp_tls_flags last certification verification flags (set to zero if none) + * This pointer could be NULL if caller does not care about esp_tls_code + * + * @return + * - ESP_ERR_INVALID_STATE if invalid parameters + * - ESP_OK (0) if no error occurred + * - specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise + */ +esp_err_t esp_tls_get_and_clear_last_error(esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags); + +/** + * @brief Returns the last error captured in esp_tls of a specific type + * The error information is cleared internally upon return + * + * @param[in] h esp-tls error handle. + * @param[in] err_type specific error type + * @param[out] error_code last error code returned from mbedtls api (set to zero if none) + * This pointer could be NULL if caller does not care about esp_tls_code + * @return + * - ESP_ERR_INVALID_STATE if invalid parameters + * - ESP_OK if a valid error returned and was cleared + */ +esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t err_type, int *error_code); + +#if CONFIG_ESP_TLS_USING_MBEDTLS +/** + * @brief Get the pointer to the global CA store currently being used. + * + * The application must first call esp_tls_set_global_ca_store(). Then the same + * CA store could be used by the application for APIs other than esp_tls. + * + * @note Modifying the pointer might cause a failure in verifying the certificates. + * + * @return + * - Pointer to the global CA store currently being used if successful. + * - NULL if there is no global CA store set. + */ +mbedtls_x509_crt *esp_tls_get_global_ca_store(void); + +#endif /* CONFIG_ESP_TLS_USING_MBEDTLS */ +#ifdef CONFIG_ESP_TLS_SERVER +/** + * @brief Create TLS/SSL server session + * + * This function creates a TLS/SSL server context for already accepted client connection + * and performs TLS/SSL handshake with the client + * + * @param[in] cfg Pointer to esp_tls_cfg_server_t + * @param[in] sockfd FD of accepted connection + * @param[out] tls Pointer to allocated esp_tls_t + * + * @return + * - 0 if successful + * - <0 in case of error + * + */ +int esp_tls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls); + +/** + * @brief Close the server side TLS/SSL connection and free any allocated resources. + * + * This function should be called to close each tls connection opened with esp_tls_server_session_create() + * + * @param[in] tls pointer to esp_tls_t + */ +void esp_tls_server_session_delete(esp_tls_t *tls); +#endif /* ! CONFIG_ESP_TLS_SERVER */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! _ESP_TLS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp-tls/esp_tls_errors.h b/tools/sdk/esp32c3/include/esp-tls/esp_tls_errors.h new file mode 100644 index 00000000..bb281b0d --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/esp_tls_errors.h @@ -0,0 +1,100 @@ +// Copyright 2021 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. + +#ifndef _ESP_TLS_ERRORS_H_ +#define _ESP_TLS_ERRORS_H_ + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_ERR_ESP_TLS_BASE 0x8000 /*!< Starting number of ESP-TLS error codes */ +#define ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME (ESP_ERR_ESP_TLS_BASE + 0x01) /*!< Error if hostname couldn't be resolved upon tls connection */ +#define ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET (ESP_ERR_ESP_TLS_BASE + 0x02) /*!< Failed to create socket */ +#define ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY (ESP_ERR_ESP_TLS_BASE + 0x03) /*!< Unsupported protocol family */ +#define ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST (ESP_ERR_ESP_TLS_BASE + 0x04) /*!< Failed to connect to host */ +#define ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED (ESP_ERR_ESP_TLS_BASE + 0x05) /*!< failed to set/get socket option */ +#define ESP_ERR_MBEDTLS_CERT_PARTLY_OK (ESP_ERR_ESP_TLS_BASE + 0x06) /*!< mbedtls parse certificates was partly successful */ +#define ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED (ESP_ERR_ESP_TLS_BASE + 0x07) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED (ESP_ERR_ESP_TLS_BASE + 0x08) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED (ESP_ERR_ESP_TLS_BASE + 0x09) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0A) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0B) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0C) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_SETUP_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0D) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_SSL_WRITE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0E) /*!< mbedtls api returned error */ +#define ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED (ESP_ERR_ESP_TLS_BASE + 0x0F) /*!< mbedtls api returned failed */ +#define ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x10) /*!< mbedtls api returned failed */ +#define ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED (ESP_ERR_ESP_TLS_BASE + 0x11) /*!< mbedtls api returned failed */ +#define ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT (ESP_ERR_ESP_TLS_BASE + 0x12) /*!< new connection in esp_tls_low_level_conn connection timeouted */ +#define ESP_ERR_WOLFSSL_SSL_SET_HOSTNAME_FAILED (ESP_ERR_ESP_TLS_BASE + 0x13) /*!< wolfSSL api returned error */ +#define ESP_ERR_WOLFSSL_SSL_CONF_ALPN_PROTOCOLS_FAILED (ESP_ERR_ESP_TLS_BASE + 0x14) /*!< wolfSSL api returned error */ +#define ESP_ERR_WOLFSSL_CERT_VERIFY_SETUP_FAILED (ESP_ERR_ESP_TLS_BASE + 0x15) /*!< wolfSSL api returned error */ +#define ESP_ERR_WOLFSSL_KEY_VERIFY_SETUP_FAILED (ESP_ERR_ESP_TLS_BASE + 0x16) /*!< wolfSSL api returned error */ +#define ESP_ERR_WOLFSSL_SSL_HANDSHAKE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x17) /*!< wolfSSL api returned failed */ +#define ESP_ERR_WOLFSSL_CTX_SETUP_FAILED (ESP_ERR_ESP_TLS_BASE + 0x18) /*!< wolfSSL api returned failed */ +#define ESP_ERR_WOLFSSL_SSL_SETUP_FAILED (ESP_ERR_ESP_TLS_BASE + 0x19) /*!< wolfSSL api returned failed */ +#define ESP_ERR_WOLFSSL_SSL_WRITE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x1A) /*!< wolfSSL api returned failed */ + +#define ESP_ERR_ESP_TLS_SE_FAILED (ESP_ERR_ESP_TLS_BASE + 0x1B) /*< esp-tls use Secure Element returned failed */ +#define ESP_ERR_ESP_TLS_TCP_CLOSED_FIN (ESP_ERR_ESP_TLS_BASE + 0x1C) /*< esp-tls's TPC transport connection has benn closed (in a clean way) */ + +/** +* Definition of errors reported from IO API (potentially non-blocking) in case of error: +* - esp_tls_conn_read() +* - esp_tls_conn_write() +*/ +#ifdef CONFIG_ESP_TLS_USING_MBEDTLS +#define ESP_TLS_ERR_SSL_WANT_READ MBEDTLS_ERR_SSL_WANT_READ +#define ESP_TLS_ERR_SSL_WANT_WRITE MBEDTLS_ERR_SSL_WANT_WRITE +#define ESP_TLS_ERR_SSL_TIMEOUT MBEDTLS_ERR_SSL_TIMEOUT +#elif CONFIG_ESP_TLS_USING_WOLFSSL /* CONFIG_ESP_TLS_USING_MBEDTLS */ +#define ESP_TLS_ERR_SSL_WANT_READ -0x6900 +#define ESP_TLS_ERR_SSL_WANT_WRITE -0x6880 +#define ESP_TLS_ERR_SSL_TIMEOUT WOLFSSL_CBIO_ERR_TIMEOUT +#endif /*CONFIG_ESP_TLS_USING_WOLFSSL */ + +/** +* Definition of different types/sources of error codes reported +* from different components +*/ +typedef enum { + ESP_TLS_ERR_TYPE_UNKNOWN = 0, + ESP_TLS_ERR_TYPE_SYSTEM, /*!< System error -- errno */ + ESP_TLS_ERR_TYPE_MBEDTLS, /*!< Error code from mbedTLS library */ + ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS, /*!< Certificate flags defined in mbedTLS */ + ESP_TLS_ERR_TYPE_ESP, /*!< ESP-IDF error type -- esp_err_t */ + ESP_TLS_ERR_TYPE_WOLFSSL, /*!< Error code from wolfSSL library */ + ESP_TLS_ERR_TYPE_WOLFSSL_CERT_FLAGS, /*!< Certificate flags defined in wolfSSL */ + ESP_TLS_ERR_TYPE_MAX, /*!< Last err type -- invalid entry */ +} esp_tls_error_type_t; + +typedef struct esp_tls_last_error* esp_tls_error_handle_t; + +/** +* @brief Error structure containing relevant errors in case tls error occurred +*/ +typedef struct esp_tls_last_error { + esp_err_t last_error; /*!< error code (based on ESP_ERR_ESP_TLS_BASE) of the last occurred error */ + int esp_tls_error_code; /*!< esp_tls error code from last esp_tls failed api */ + int esp_tls_flags; /*!< last certification verification flags */ +} esp_tls_last_error_t; + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_TLS_ERRORS_H_ diff --git a/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_error_capture_internal.h b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_error_capture_internal.h new file mode 100644 index 00000000..fd065b2b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_error_capture_internal.h @@ -0,0 +1,62 @@ +// Copyright 2017-2019 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. + +#ifndef __ESP_TLS_ERROR_CAPTURE_INTERNAL_H__ +#define __ESP_TLS_ERROR_CAPTURE_INTERNAL_H__ +/** +* Note: this is an implementation placeholder for error logger. +* This version is internal to esp-tls component and only saves single esp_err of last occurred error +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Error tracker logging macro to enable mapping tracking errors internally + * or using an external/global implementation + */ +#define ESP_INT_EVENT_TRACKER_CAPTURE(h, type, code) esp_tls_internal_event_tracker_capture(h, type, code) + +/** + * @brief Internal tracker capture error + * + * This implementation saves latest errors of available types + * + * @param[in] h esp-tls error handle + * @param[in] err_type Specific error type + * @param[int] code Error code to capture + * + */ +void esp_tls_internal_event_tracker_capture(esp_tls_error_handle_t h, uint32_t type, int code); + +/** + * @brief Create internal tracker storage + * + * @return Error tracker handle if success or NULL if allocation error + */ +esp_tls_error_handle_t esp_tls_internal_event_tracker_create(void); + +/** + * @brief Destroy internal tracker storage + * + * @param[in] h esp-tls error handle + */ + void esp_tls_internal_event_tracker_destroy(esp_tls_error_handle_t h); + +#ifdef __cplusplus +} +#endif + +#endif //__ESP_TLS_ERROR_CAPTURE_INTERNAL_H__ diff --git a/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_mbedtls.h b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_mbedtls.h new file mode 100644 index 00000000..7440f0c3 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_mbedtls.h @@ -0,0 +1,112 @@ +// Copyright 2019 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. + +#pragma once +#include "esp_tls.h" + +/** + * Internal Callback API for mbedtls_ssl_read + */ +ssize_t esp_mbedtls_read(esp_tls_t *tls, char *data, size_t datalen); + +/** + * Internal callback API for mbedtls_ssl_write + */ +ssize_t esp_mbedtls_write(esp_tls_t *tls, const char *data, size_t datalen); + +/** + * Internal Callback for mbedtls_handshake + */ +int esp_mbedtls_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg); + +/** + * Internal Callback for mbedtls_cleanup , frees up all the memory used by mbedtls + */ +void esp_mbedtls_cleanup(esp_tls_t *tls); + +/** + * Internal Callback for Certificate verification for mbedtls + */ +void esp_mbedtls_verify_certificate(esp_tls_t *tls); + +/** + * Internal Callback for deleting the mbedtls connection + */ +void esp_mbedtls_conn_delete(esp_tls_t *tls); + +/** + * Internal Callback for mbedtls_get_bytes_avail + */ +ssize_t esp_mbedtls_get_bytes_avail(esp_tls_t *tls); + +/** + * Internal Callback for creating ssl handle for mbedtls + */ +esp_err_t esp_create_mbedtls_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls); + +/** + * mbedTLS function for Initializing socket wrappers + */ +static inline void esp_mbedtls_net_init(esp_tls_t *tls) +{ + mbedtls_net_init(&tls->server_fd); +} + +#ifdef CONFIG_ESP_TLS_SERVER +/** + * Internal Callback for set_server_config + * + * /note :- can only be used with mbedtls ssl library + */ +esp_err_t set_server_config(esp_tls_cfg_server_t *cfg, esp_tls_t *tls); + +/** + * Internal Callback for mbedtls_server_session_create + * + * /note :- The function can only be used with mbedtls ssl library + */ +int esp_mbedtls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls); + +/** + * Internal Callback for mbedtls_server_session_delete + * + * /note :- The function can only be used with mbedtls ssl library + */ +void esp_mbedtls_server_session_delete(esp_tls_t *tls); +#endif + +/** + * Internal Callback for set_client_config_function + */ +esp_err_t set_client_config(const char *hostname, size_t hostlen, esp_tls_cfg_t *cfg, esp_tls_t *tls); + +/** + * Internal Callback for mbedtls_init_global_ca_store + */ +esp_err_t esp_mbedtls_init_global_ca_store(void); + +/** + * Callback function for setting global CA store data for TLS/SSL using mbedtls + */ +esp_err_t esp_mbedtls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes); + +/** + * Internal Callback for esp_tls_global_ca_store + */ +mbedtls_x509_crt *esp_mbedtls_get_global_ca_store(void); + +/** + * Callback function for freeing global ca store for TLS/SSL using mbedtls + */ +void esp_mbedtls_free_global_ca_store(void); diff --git a/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_wolfssl.h b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_wolfssl.h new file mode 100644 index 00000000..f29e9332 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp-tls/private_include/esp_tls_wolfssl.h @@ -0,0 +1,93 @@ +// Copyright 2019 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. + +#pragma once +#include "esp_tls.h" + +/** + * Internal Callback for creating ssl handle for wolfssl + */ +int esp_create_wolfssl_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls); + +/** + * Internal Callback for wolfssl_handshake + */ +int esp_wolfssl_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg); + +/** + * Internal Callback API for wolfssl_ssl_read + */ +ssize_t esp_wolfssl_read(esp_tls_t *tls, char *data, size_t datalen); + +/** + * Internal callback API for wolfssl_ssl_write + */ +ssize_t esp_wolfssl_write(esp_tls_t *tls, const char *data, size_t datalen); + +/** + * Internal Callback for wolfssl_cleanup , frees up all the memory used by wolfssl + */ +void esp_wolfssl_cleanup(esp_tls_t *tls); + +/** + * Internal Callback for Certificate verification for wolfssl + */ +void esp_wolfssl_verify_certificate(esp_tls_t *tls); + +/** + * Internal Callback for deleting the wolfssl connection + */ +void esp_wolfssl_conn_delete(esp_tls_t *tls); + +/** + * Internal Callback for wolfssl_get_bytes_avail + */ +ssize_t esp_wolfssl_get_bytes_avail(esp_tls_t *tls); + +/** + * Callback function for setting global CA store data for TLS/SSL using wolfssl + */ +esp_err_t esp_wolfssl_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes); + +/** + * Callback function for freeing global ca store for TLS/SSL using wolfssl + */ +void esp_wolfssl_free_global_ca_store(void); + +/** + * + * Callback function for Initializing the global ca store for TLS?SSL using wolfssl + */ +esp_err_t esp_wolfssl_init_global_ca_store(void); + +/** + * wolfSSL function for Initializing socket wrappers (no-operation for wolfSSL) + */ +static inline void esp_wolfssl_net_init(esp_tls_t *tls) +{ +} + +#ifdef CONFIG_ESP_TLS_SERVER + +/** + * Function to Create ESP-TLS Server session with wolfssl Stack + */ +int esp_wolfssl_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls); + +/* + * Delete Server Session + */ +void esp_wolfssl_server_session_delete(esp_tls_t *tls); + +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/brownout.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/brownout.h new file mode 100644 index 00000000..da58a093 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/brownout.h @@ -0,0 +1,31 @@ +// Copyright 2015-2021 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. + + +#ifndef __ESP_BROWNOUT_H +#define __ESP_BROWNOUT_H + +#ifdef __cplusplus +extern "C" { +#endif + +void esp_brownout_init(void); + +void esp_brownout_disable(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/cache_err_int.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/cache_err_int.h new file mode 100644 index 00000000..9c8d9ddb --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/cache_err_int.h @@ -0,0 +1,33 @@ +// Copyright 2015-2020 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. + + +/** + * @brief initialize cache invalid access interrupt + * + * This function enables cache invalid access interrupt source and connects it + * to interrupt input number ETS_CACHEERR_INUM (see soc/soc.h). It is called + * from the startup code. + */ +void esp_cache_err_int_init(void); + + +/** + * @brief get the CPU which caused cache invalid access interrupt + * @return + * - PRO_CPU_NUM, if PRO_CPU has caused cache IA interrupt + * - APP_CPU_NUM, if APP_CPU has caused cache IA interrupt + * - (-1) otherwise + */ +int esp_cache_err_get_cpuid(void); diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/clk.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/clk.h new file mode 100644 index 00000000..1d4e462b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/clk.h @@ -0,0 +1,84 @@ +// Copyright 2015-2020 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. + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file esp_clk.h + * + * This file contains declarations of clock related functions. + */ + +/** + * @brief Get the calibration value of RTC slow clock + * + * The value is in the same format as returned by rtc_clk_cal (microseconds, + * in Q13.19 fixed-point format). + * + * @return the calibration value obtained using rtc_clk_cal, at startup time + */ +uint32_t esp_clk_slowclk_cal_get(void); + +/** + * @brief Update the calibration value of RTC slow clock + * + * The value has to be in the same format as returned by rtc_clk_cal (microseconds, + * in Q13.19 fixed-point format). + * This value is used by timekeeping functions (such as gettimeofday) to + * calculate current time based on RTC counter value. + * @param value calibration value obtained using rtc_clk_cal + */ +void esp_clk_slowclk_cal_set(uint32_t value); + +/** + * @brief Return current CPU clock frequency + * When frequency switching is performed, this frequency may change. + * However it is guaranteed that the frequency never changes with a critical + * section. + * + * @return CPU clock frequency, in Hz + */ +int esp_clk_cpu_freq(void); + +/** + * @brief Return current APB clock frequency + * + * When frequency switching is performed, this frequency may change. + * However it is guaranteed that the frequency never changes with a critical + * section. + * + * @return APB clock frequency, in Hz + */ +int esp_clk_apb_freq(void); + + +/** + * @brief Read value of RTC counter, converting it to microseconds + * @attention The value returned by this function may change abruptly when + * calibration value of RTC counter is updated via esp_clk_slowclk_cal_set + * function. This should not happen unless application calls esp_clk_slowclk_cal_set. + * In ESP-IDF, esp_clk_slowclk_cal_set is only called in startup code. + * + * @return Value or RTC counter, expressed in microseconds + */ +uint64_t esp_clk_rtc_time(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/dport_access.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/dport_access.h new file mode 100644 index 00000000..f3f7007a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/dport_access.h @@ -0,0 +1,42 @@ +// Copyright 2010-2020 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. + +#ifndef _ESP_DPORT_ACCESS_H_ +#define _ESP_DPORT_ACCESS_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Read a sequence of DPORT registers to the buffer. + * + * @param[out] buff_out Contains the read data. + * @param[in] address Initial address for reading registers. + * @param[in] num_words The number of words. + */ +void esp_dport_access_read_buffer(uint32_t *buff_out, uint32_t address, uint32_t num_words); + +#define DPORT_STALL_OTHER_CPU_START() +#define DPORT_STALL_OTHER_CPU_END() +#define DPORT_INTERRUPT_DISABLE() +#define DPORT_INTERRUPT_RESTORE() + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP_DPORT_ACCESS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/memprot.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/memprot.h new file mode 100644 index 00000000..9085fd8e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/memprot.h @@ -0,0 +1,94 @@ +// Copyright 2020 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. + + +/* INTERNAL API + * generic interface to PMS memory protection features + */ + +#pragma once + +#include +#include "esp_attr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + MEMPROT_NONE = 0x00000000, + MEMPROT_IRAM0_SRAM = 0x00000001, + MEMPROT_DRAM0_SRAM = 0x00000002, + MEMPROT_ALL = 0xFFFFFFFF +} mem_type_prot_t; + +typedef enum { + MEMPROT_IRAM0_DRAM0_SPLITLINE, + MEMPROT_IRAM0_LINE_0_SPLITLINE, + MEMPROT_IRAM0_LINE_1_SPLITLINE, + MEMPROT_DRAM0_DMA_LINE_0_SPLITLINE, + MEMPROT_DRAM0_DMA_LINE_1_SPLITLINE +} split_line_t; + +typedef enum { + MEMPROT_IRAM0_PMS_AREA_0, + MEMPROT_IRAM0_PMS_AREA_1, + MEMPROT_IRAM0_PMS_AREA_2, + MEMPROT_IRAM0_PMS_AREA_3, + MEMPROT_DRAM0_PMS_AREA_0, + MEMPROT_DRAM0_PMS_AREA_1, + MEMPROT_DRAM0_PMS_AREA_2, + MEMPROT_DRAM0_PMS_AREA_3 +} pms_area_t; + + +const char *mem_type_to_str(mem_type_prot_t mem_type); +const char *split_line_to_str(split_line_t line_type); +const char *pms_to_str(pms_area_t area_type); + +void *esp_memprot_get_main_split_addr(void); +void esp_memprot_set_split_line_lock(bool lock); +bool esp_memprot_get_split_line_lock(void); +void esp_memprot_set_split_line(split_line_t line_type, const void *line_addr); + +void esp_memprot_set_pms_lock(mem_type_prot_t mem_type, bool lock); +bool esp_memprot_get_pms_lock(mem_type_prot_t mem_type); +void esp_memprot_iram_set_pms_area(pms_area_t area_type, bool r, bool w, bool x); +void esp_memprot_dram_set_pms_area(pms_area_t area_type, bool r, bool w); + +void esp_memprot_set_monitor_lock(mem_type_prot_t mem_type, bool lock); +bool esp_memprot_get_monitor_lock(mem_type_prot_t mem_type); +void esp_memprot_set_monitor_en(mem_type_prot_t mem_type, bool enable); +bool esp_memprot_get_monitor_en(mem_type_prot_t mem_type); + +int IRAM_ATTR esp_memprot_intr_get_cpuid(void); +void IRAM_ATTR esp_memprot_monitor_clear_intr(mem_type_prot_t mem_type); +mem_type_prot_t IRAM_ATTR esp_memprot_get_active_intr_memtype(void); +bool IRAM_ATTR esp_memprot_is_locked_any(void); +bool IRAM_ATTR esp_memprot_is_intr_ena_any(void); + +uint32_t IRAM_ATTR esp_memprot_get_violate_intr_on(mem_type_prot_t mem_type); +uint32_t IRAM_ATTR esp_memprot_get_violate_addr(mem_type_prot_t mem_type); +uint32_t IRAM_ATTR esp_memprot_get_violate_world(mem_type_prot_t mem_type); +uint32_t IRAM_ATTR esp_memprot_get_violate_wr(mem_type_prot_t mem_type); +uint32_t IRAM_ATTR esp_memprot_get_violate_loadstore(mem_type_prot_t mem_type); +uint32_t IRAM_ATTR esp_memprot_get_violate_byte_en(mem_type_prot_t mem_type); + +void esp_memprot_set_intr_matrix(mem_type_prot_t mem_type); +void esp_memprot_set_prot(bool invoke_panic_handler, bool lock_feature, uint32_t *mem_type_mask); +void esp_memprot_set_prot_int(bool invoke_panic_handler, bool lock_feature, void *split_addr, uint32_t *mem_type_mask); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/rtc.h b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/rtc.h new file mode 100644 index 00000000..b090ae5c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp32c3/rtc.h @@ -0,0 +1,40 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file esp32c3/rtc.h + * + * This file contains declarations of rtc related functions. + */ + +/** + * @brief Get current value of RTC counter in microseconds + * + * Note: this function may take up to 1 RTC_SLOW_CLK cycle to execute + * + * @return current value of RTC counter in microseconds + */ +uint64_t esp_rtc_get_time_us(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp_clk.h b/tools/sdk/esp32c3/include/esp32c3/include/esp_clk.h new file mode 100644 index 00000000..78f6678a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp_clk.h @@ -0,0 +1,77 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include + +/** + * @file esp_clk.h + * + * This file contains declarations of clock related functions. + */ + +/** + * @brief Get the calibration value of RTC slow clock + * + * The value is in the same format as returned by rtc_clk_cal (microseconds, + * in Q13.19 fixed-point format). + * + * @return the calibration value obtained using rtc_clk_cal, at startup time + */ +uint32_t esp_clk_slowclk_cal_get(void); + +/** + * @brief Update the calibration value of RTC slow clock + * + * The value has to be in the same format as returned by rtc_clk_cal (microseconds, + * in Q13.19 fixed-point format). + * This value is used by timekeeping functions (such as gettimeofday) to + * calculate current time based on RTC counter value. + * @param value calibration value obtained using rtc_clk_cal + */ +void esp_clk_slowclk_cal_set(uint32_t value); + +/** + * @brief Return current CPU clock frequency + * When frequency switching is performed, this frequency may change. + * However it is guaranteed that the frequency never changes with a critical + * section. + * + * @return CPU clock frequency, in Hz + */ +int esp_clk_cpu_freq(void); + +/** + * @brief Return current APB clock frequency + * + * When frequency switching is performed, this frequency may change. + * However it is guaranteed that the frequency never changes with a critical + * section. + * + * @return APB clock frequency, in Hz + */ +int esp_clk_apb_freq(void); + + +/** + * @brief Read value of RTC counter, converting it to microseconds + * @attention The value returned by this function may change abruptly when + * calibration value of RTC counter is updated via esp_clk_slowclk_cal_set + * function. This should not happen unless application calls esp_clk_slowclk_cal_set. + * In ESP-IDF, esp_clk_slowclk_cal_set is only called in startup code. + * + * @return Value or RTC counter, expressed in microseconds + */ +uint64_t esp_clk_rtc_time(void); diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp_crypto_lock.h b/tools/sdk/esp32c3/include/esp32c3/include/esp_crypto_lock.h new file mode 100644 index 00000000..3149d346 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp_crypto_lock.h @@ -0,0 +1,76 @@ +// Copyright 2015-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Acquire lock for HMAC cryptography peripheral + * + * Internally also locks the SHA peripheral, as the HMAC depends on the SHA peripheral + */ +void esp_crypto_hmac_lock_acquire(void); + +/** + * @brief Release lock for HMAC cryptography peripheral + * + * Internally also releases the SHA peripheral, as the HMAC depends on the SHA peripheral + */ +void esp_crypto_hmac_lock_release(void); + +/** + * @brief Acquire lock for DS cryptography peripheral + * + * Internally also locks the HMAC (which locks SHA), AES and MPI peripheral, as the DS depends on these peripherals + */ +void esp_crypto_ds_lock_acquire(void); + +/** + * @brief Release lock for DS cryptography peripheral + * + * Internally also releases the HMAC (which locks SHA), AES and MPI peripheral, as the DS depends on these peripherals + */ +void esp_crypto_ds_lock_release(void); + +/** + * @brief Acquire lock for the SHA and AES cryptography peripheral. + * + */ +void esp_crypto_sha_aes_lock_acquire(void); + +/** + * @brief Release lock for the SHA and AES cryptography peripheral. + * + */ +void esp_crypto_sha_aes_lock_release(void); + + +/** + * @brief Acquire lock for the mpi cryptography peripheral. + * + */ +void esp_crypto_mpi_lock_acquire(void); + +/** + * @brief Release lock for the mpi/rsa cryptography peripheral. + * + */ +void esp_crypto_mpi_lock_release(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp_ds.h b/tools/sdk/esp32c3/include/esp32c3/include/esp_ds.h new file mode 100644 index 00000000..911e44c8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp_ds.h @@ -0,0 +1,218 @@ +// Copyright 2020 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. + +#pragma once + +#include "esp_hmac.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP32C3_ERR_HW_CRYPTO_DS_HMAC_FAIL ESP_ERR_HW_CRYPTO_BASE + 0x1 /*!< HMAC peripheral problem */ +#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_KEY ESP_ERR_HW_CRYPTO_BASE + 0x2 /*!< given HMAC key isn't correct, + HMAC peripheral problem */ +#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_DIGEST ESP_ERR_HW_CRYPTO_BASE + 0x4 /*!< message digest check failed, + result is invalid */ +#define ESP32C3_ERR_HW_CRYPTO_DS_INVALID_PADDING ESP_ERR_HW_CRYPTO_BASE + 0x5 /*!< padding check failed, but result + is produced anyway and can be read*/ + +#define ESP_DS_IV_BIT_LEN 128 +#define ESP_DS_IV_LEN (ESP_DS_IV_BIT_LEN / 8) +#define ESP_DS_SIGNATURE_MAX_BIT_LEN 3072 +#define ESP_DS_SIGNATURE_MD_BIT_LEN 256 +#define ESP_DS_SIGNATURE_M_PRIME_BIT_LEN 32 +#define ESP_DS_SIGNATURE_L_BIT_LEN 32 +#define ESP_DS_SIGNATURE_PADDING_BIT_LEN 64 + +/* Length of parameter 'C' stored in flash, in bytes + - Operands Y, M and r_bar; each 3072 bits + - Operand MD (message digest); 256 bits + - Operands M' and L; each 32 bits + - Operand beta (padding value; 64 bits +*/ +#define ESP_DS_C_LEN (((ESP_DS_SIGNATURE_MAX_BIT_LEN * 3 \ + + ESP_DS_SIGNATURE_MD_BIT_LEN \ + + ESP_DS_SIGNATURE_M_PRIME_BIT_LEN \ + + ESP_DS_SIGNATURE_L_BIT_LEN \ + + ESP_DS_SIGNATURE_PADDING_BIT_LEN) / 8)) + +typedef struct esp_ds_context esp_ds_context_t; + +typedef enum { + ESP_DS_RSA_1024 = (1024 / 32) - 1, + ESP_DS_RSA_2048 = (2048 / 32) - 1, + ESP_DS_RSA_3072 = (3072 / 32) - 1 +} esp_digital_signature_length_t; + +/** + * Encrypted private key data. Recommended to store in flash in this format. + * + * @note This struct has to match to one from the ROM code! This documentation is mostly taken from there. + */ +typedef struct esp_digital_signature_data { + /** + * RSA LENGTH register parameters + * (number of words in RSA key & operands, minus one). + * + * Max value 127 (for RSA 3072). + * + * This value must match the length field encrypted and stored in 'c', + * or invalid results will be returned. (The DS peripheral will + * always use the value in 'c', not this value, so an attacker can't + * alter the DS peripheral results this way, it will just truncate or + * extend the message and the resulting signature in software.) + * + * @note In IDF, the enum type length is the same as of type unsigned, so they can be used interchangably. + * See the ROM code for the original declaration of struct \c ets_ds_data_t. + */ + esp_digital_signature_length_t rsa_length; + + /** + * IV value used to encrypt 'c' + */ + uint32_t iv[ESP_DS_IV_BIT_LEN / 32]; + + /** + * Encrypted Digital Signature parameters. Result of AES-CBC encryption + * of plaintext values. Includes an encrypted message digest. + */ + uint8_t c[ESP_DS_C_LEN]; +} esp_ds_data_t; + +/** + * Plaintext parameters used by Digital Signature. + * + * This is only used for encrypting the RSA parameters by calling esp_ds_encrypt_params(). + * Afterwards, the result can be stored in flash or in other persistent memory. + * The encryption is a prerequisite step before any signature operation can be done. + */ +typedef struct { + uint32_t Y[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA exponent + uint32_t M[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA modulus + uint32_t Rb[ESP_DS_SIGNATURE_MAX_BIT_LEN / 32]; //!< RSA r inverse operand + uint32_t M_prime; //!< RSA M prime operand + uint32_t length; //!< RSA length in words (32 bit) +} esp_ds_p_data_t; + +/** + * @brief Sign the message with a hardware key from specific key slot. + * + * This function is a wrapper around \c esp_ds_finish_sign() and \c esp_ds_start_sign(), so do not use them + * in parallel. + * It blocks until the signing is finished and then returns the signature. + * + * @note This function locks the HMAC, SHA, AES and RSA components during its entire execution time. + * + * @param message the message to be signed; its length is determined by data->rsa_length + * @param data the encrypted signing key data (AES encrypted RSA key + IV) + * @param key_id the HMAC key ID determining the HMAC key of the HMAC which will be used to decrypt the + * signing key data + * @param signature the destination of the signature, should be (data->rsa_length + 1)*4 bytes long + * + * @return + * - ESP_OK if successful, the signature was written to the parameter \c signature. + * - ESP_ERR_INVALID_ARG if one of the parameters is NULL or data->rsa_length is too long or 0 + * - ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL if there was an HMAC failure during retrieval of the decryption key + * - ESP_ERR_NO_MEM if there hasn't been enough memory to allocate the context object + * - ESP_ERR_HW_CRYPTO_DS_INVALID_KEY if there's a problem with passing the HMAC key to the DS component + * - ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST if the message digest didn't match; the signature is invalid. + * - ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING if the message padding is incorrect, the signature can be read though + * since the message digest matches. + */ +esp_err_t esp_ds_sign(const void *message, + const esp_ds_data_t *data, + hmac_key_id_t key_id, + void *signature); + +/** + * @brief Start the signing process. + * + * This function yields a context object which needs to be passed to \c esp_ds_finish_sign() to finish the signing + * process. + * + * @note This function locks the HMAC, SHA, AES and RSA components, so the user has to ensure to call + * \c esp_ds_finish_sign() in a timely manner. + * + * @param message the message to be signed; its length is determined by data->rsa_length + * @param data the encrypted signing key data (AES encrypted RSA key + IV) + * @param key_id the HMAC key ID determining the HMAC key of the HMAC which will be used to decrypt the + * signing key data + * @param esp_ds_ctx the context object which is needed for finishing the signing process later + * + * @return + * - ESP_OK if successful, the ds operation was started now and has to be finished with \c esp_ds_finish_sign() + * - ESP_ERR_INVALID_ARG if one of the parameters is NULL or data->rsa_length is too long or 0 + * - ESP_ERR_HW_CRYPTO_DS_HMAC_FAIL if there was an HMAC failure during retrieval of the decryption key + * - ESP_ERR_NO_MEM if there hasn't been enough memory to allocate the context object + * - ESP_ERR_HW_CRYPTO_DS_INVALID_KEY if there's a problem with passing the HMAC key to the DS component + */ +esp_err_t esp_ds_start_sign(const void *message, + const esp_ds_data_t *data, + hmac_key_id_t key_id, + esp_ds_context_t **esp_ds_ctx); + +/** + * Return true if the DS peripheral is busy, otherwise false. + * + * @note Only valid if \c esp_ds_start_sign() was called before. + */ +bool esp_ds_is_busy(void); + +/** + * @brief Finish the signing process. + * + * @param signature the destination of the signature, should be (data->rsa_length + 1)*4 bytes long + * @param esp_ds_ctx the context object retreived by \c esp_ds_start_sign() + * + * @return + * - ESP_OK if successful, the ds operation has been finished and the result is written to signature. + * - ESP_ERR_INVALID_ARG if one of the parameters is NULL + * - ESP_ERR_HW_CRYPTO_DS_INVALID_DIGEST if the message digest didn't match; the signature is invalid. + * This means that the encrypted RSA key parameters are invalid, indicating that they may have been tampered + * with or indicating a flash error, etc. + * - ESP_ERR_HW_CRYPTO_DS_INVALID_PADDING if the message padding is incorrect, the signature can be read though + * since the message digest matches (see TRM for more details). + */ +esp_err_t esp_ds_finish_sign(void *signature, esp_ds_context_t *esp_ds_ctx); + +/** + * @brief Encrypt the private key parameters. + * + * The encryption is a prerequisite step before any signature operation can be done. + * It is not strictly necessary to use this encryption function, the encryption could also happen on an external + * device. + * + * @param data Output buffer to store encrypted data, suitable for later use generating signatures. + * The allocated memory must be in internal memory and word aligned since it's filled by DMA. Both is asserted + * at run time. + * @param iv Pointer to 16 byte IV buffer, will be copied into 'data'. Should be randomly generated bytes each time. + * @param p_data Pointer to input plaintext key data. The expectation is this data will be deleted after this process + * is done and 'data' is stored. + * @param key Pointer to 32 bytes of key data. Type determined by key_type parameter. The expectation is the + * corresponding HMAC key will be stored to efuse and then permanently erased. + * + * @return + * - ESP_OK if successful, the ds operation has been finished and the result is written to signature. + * - ESP_ERR_INVALID_ARG if one of the parameters is NULL or p_data->rsa_length is too long + */ +esp_err_t esp_ds_encrypt_params(esp_ds_data_t *data, + const void *iv, + const esp_ds_p_data_t *p_data, + const void *key); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp32c3/include/esp_hmac.h b/tools/sdk/esp32c3/include/esp32c3/include/esp_hmac.h new file mode 100644 index 00000000..391ba12f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp32c3/include/esp_hmac.h @@ -0,0 +1,67 @@ +// Copyright 2015-2020 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. + +#ifndef _ESP_HMAC_H_ +#define _ESP_HMAC_H_ + +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The possible efuse keys for the HMAC peripheral + */ +typedef enum { + HMAC_KEY0 = 0, + HMAC_KEY1, + HMAC_KEY2, + HMAC_KEY3, + HMAC_KEY4, + HMAC_KEY5, + HMAC_KEY_MAX +} hmac_key_id_t; + +/** + * @brief + * Calculate the HMAC of a given message. + * + * Calculate the HMAC \c hmac of a given message \c message with length \c message_len. + * SHA256 is used for the calculation (fixed on ESP32S2). + * + * @note Uses the HMAC peripheral in "upstream" mode. + * + * @param key_id Determines which of the 6 key blocks in the efuses should be used for the HMAC calcuation. + * The corresponding purpose field of the key block in the efuse must be set to the HMAC upstream purpose value. + * @param message the message for which to calculate the HMAC + * @param message_len message length + * return ESP_ERR_INVALID_STATE if unsuccessful + * @param [out] hmac the hmac result; the buffer behind the provided pointer must be 32 bytes long + * + * @return + * * ESP_OK, if the calculation was successful, + * * ESP_FAIL, if the hmac calculation failed + */ +esp_err_t esp_hmac_calculate(hmac_key_id_t key_id, + const void *message, + size_t message_len, + uint8_t *hmac); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_HMAC_H_ diff --git a/tools/sdk/esp32c3/include/esp_adc_cal/include/esp_adc_cal.h b/tools/sdk/esp32c3/include/esp_adc_cal/include/esp_adc_cal.h new file mode 100644 index 00000000..9adf2807 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_adc_cal/include/esp_adc_cal.h @@ -0,0 +1,141 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_ADC_CAL_H__ +#define __ESP_ADC_CAL_H__ + +#include +#include "esp_err.h" +#include "driver/adc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Type of calibration value used in characterization + */ +typedef enum { + ESP_ADC_CAL_VAL_EFUSE_VREF = 0, /**< Characterization based on reference voltage stored in eFuse*/ + ESP_ADC_CAL_VAL_EFUSE_TP = 1, /**< Characterization based on Two Point values stored in eFuse*/ + ESP_ADC_CAL_VAL_DEFAULT_VREF = 2, /**< Characterization based on default reference voltage*/ + ESP_ADC_CAL_VAL_MAX, + ESP_ADC_CAL_VAL_NOT_SUPPORTED = ESP_ADC_CAL_VAL_MAX, +} esp_adc_cal_value_t; + +/** + * @brief Structure storing characteristics of an ADC + * + * @note Call esp_adc_cal_characterize() to initialize the structure + */ +typedef struct { + adc_unit_t adc_num; /**< ADC number*/ + adc_atten_t atten; /**< ADC attenuation*/ + adc_bits_width_t bit_width; /**< ADC bit width */ + uint32_t coeff_a; /**< Gradient of ADC-Voltage curve*/ + uint32_t coeff_b; /**< Offset of ADC-Voltage curve*/ + uint32_t vref; /**< Vref used by lookup table*/ + const uint32_t *low_curve; /**< Pointer to low Vref curve of lookup table (NULL if unused)*/ + const uint32_t *high_curve; /**< Pointer to high Vref curve of lookup table (NULL if unused)*/ +} esp_adc_cal_characteristics_t; + +/** + * @brief Checks if ADC calibration values are burned into eFuse + * + * This function checks if ADC reference voltage or Two Point values have been + * burned to the eFuse of the current ESP32 + * + * @param value_type Type of calibration value (ESP_ADC_CAL_VAL_EFUSE_VREF or ESP_ADC_CAL_VAL_EFUSE_TP) + * @note in ESP32S2, only ESP_ADC_CAL_VAL_EFUSE_TP is supported. Some old ESP32S2s do not support this, either. + * In which case you have to calibrate it manually, possibly by performing your own two-point calibration on the chip. + * + * @return + * - ESP_OK: The calibration mode is supported in eFuse + * - ESP_ERR_NOT_SUPPORTED: Error, eFuse values are not burned + * - ESP_ERR_INVALID_ARG: Error, invalid argument (ESP_ADC_CAL_VAL_DEFAULT_VREF) + */ +esp_err_t esp_adc_cal_check_efuse(esp_adc_cal_value_t value_type); + +/** + * @brief Characterize an ADC at a particular attenuation + * + * This function will characterize the ADC at a particular attenuation and generate + * the ADC-Voltage curve in the form of [y = coeff_a * x + coeff_b]. + * Characterization can be based on Two Point values, eFuse Vref, or default Vref + * and the calibration values will be prioritized in that order. + * + * @note + * For ESP32, Two Point values and eFuse Vref calibration can be enabled/disabled using menuconfig. + * For ESP32s2, only Two Point values calibration and only ADC_WIDTH_BIT_13 is supported. The parameter default_vref is unused. + * + * + * @param[in] adc_num ADC to characterize (ADC_UNIT_1 or ADC_UNIT_2) + * @param[in] atten Attenuation to characterize + * @param[in] bit_width Bit width configuration of ADC + * @param[in] default_vref Default ADC reference voltage in mV (Only in ESP32, used if eFuse values is not available) + * @param[out] chars Pointer to empty structure used to store ADC characteristics + * + * @return + * - ESP_ADC_CAL_VAL_EFUSE_VREF: eFuse Vref used for characterization + * - ESP_ADC_CAL_VAL_EFUSE_TP: Two Point value used for characterization (only in Linear Mode) + * - ESP_ADC_CAL_VAL_DEFAULT_VREF: Default Vref used for characterization + */ +esp_adc_cal_value_t esp_adc_cal_characterize(adc_unit_t adc_num, + adc_atten_t atten, + adc_bits_width_t bit_width, + uint32_t default_vref, + esp_adc_cal_characteristics_t *chars); + +/** + * @brief Convert an ADC reading to voltage in mV + * + * This function converts an ADC reading to a voltage in mV based on the ADC's + * characteristics. + * + * @note Characteristics structure must be initialized before this function + * is called (call esp_adc_cal_characterize()) + * + * @param[in] adc_reading ADC reading + * @param[in] chars Pointer to initialized structure containing ADC characteristics + * + * @return Voltage in mV + */ +uint32_t esp_adc_cal_raw_to_voltage(uint32_t adc_reading, const esp_adc_cal_characteristics_t *chars); + +/** + * @brief Reads an ADC and converts the reading to a voltage in mV + * + * This function reads an ADC then converts the raw reading to a voltage in mV + * based on the characteristics provided. The ADC that is read is also + * determined by the characteristics. + * + * @note The Characteristics structure must be initialized before this + * function is called (call esp_adc_cal_characterize()) + * + * @param[in] channel ADC Channel to read + * @param[in] chars Pointer to initialized ADC characteristics structure + * @param[out] voltage Pointer to store converted voltage + * + * @return + * - ESP_OK: ADC read and converted to mV + * - ESP_ERR_TIMEOUT: Error, timed out attempting to read ADC + * - ESP_ERR_INVALID_ARG: Error due to invalid arguments + */ +esp_err_t esp_adc_cal_get_voltage(adc_channel_t channel, const esp_adc_cal_characteristics_t *chars, uint32_t *voltage); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_ADC_CAL_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_assert.h b/tools/sdk/esp32c3/include/esp_common/include/esp_assert.h new file mode 100644 index 00000000..39d6a328 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_assert.h @@ -0,0 +1,37 @@ +// Copyright 2015-2017 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. +#ifndef __ESP_ASSERT_H__ +#define __ESP_ASSERT_H__ + +#include "assert.h" + +/* Assert at compile time if possible, runtime otherwise */ +#ifndef __cplusplus +/* __builtin_choose_expr() is only in C, makes this a lot cleaner */ +#define TRY_STATIC_ASSERT(CONDITION, MSG) do { \ + _Static_assert(__builtin_choose_expr(__builtin_constant_p(CONDITION), (CONDITION), 1), #MSG); \ + assert(#MSG && (CONDITION)); \ + } while(0) +#else +/* for C++, use __attribute__((error)) - works almost as well as _Static_assert */ +#define TRY_STATIC_ASSERT(CONDITION, MSG) do { \ + if (__builtin_constant_p(CONDITION) && !(CONDITION)) { \ + extern __attribute__((error(#MSG))) void failed_compile_time_assert(void); \ + failed_compile_time_assert(); \ + } \ + assert(#MSG && (CONDITION)); \ + } while(0) +#endif /* __cplusplus */ + +#endif /* __ESP_ASSERT_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_attr.h b/tools/sdk/esp32c3/include/esp_common/include/esp_attr.h new file mode 100644 index 00000000..21e52bd6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_attr.h @@ -0,0 +1,158 @@ + +// Copyright 2015-2016 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. +#ifndef __ESP_ATTR_H__ +#define __ESP_ATTR_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#define ROMFN_ATTR + +//Normally, the linker script will put all code and rodata in flash, +//and all variables in shared RAM. These macros can be used to redirect +//particular functions/variables to other memory regions. + +// Forces code into IRAM instead of flash +#define IRAM_ATTR _SECTION_ATTR_IMPL(".iram1", __COUNTER__) + +// Forces data into DRAM instead of flash +#define DRAM_ATTR _SECTION_ATTR_IMPL(".dram1", __COUNTER__) + +#ifdef CONFIG_ESP32_IRAM_AS_8BIT_ACCESSIBLE_MEMORY +// Forces data into IRAM instead of DRAM +#define IRAM_DATA_ATTR __attribute__((section(".iram.data"))) + +// Forces data into IRAM instead of DRAM and map it to coredump +#define COREDUMP_IRAM_DATA_ATTR _SECTION_ATTR_IMPL(".iram.data.coredump", __COUNTER__) + +// Forces bss into IRAM instead of DRAM +#define IRAM_BSS_ATTR __attribute__((section(".iram.bss"))) +#else +#define COREDUMP_IRAM_DATA_ATTR +#define IRAM_DATA_ATTR + +#define IRAM_BSS_ATTR +#endif + +// Forces data to be 4 bytes aligned +#define WORD_ALIGNED_ATTR __attribute__((aligned(4))) + +// Forces data to be placed to DMA-capable places +#define DMA_ATTR WORD_ALIGNED_ATTR DRAM_ATTR + +// Forces a function to be inlined +#define FORCE_INLINE_ATTR static inline __attribute__((always_inline)) + +// Forces a string into DRAM instead of flash +// Use as esp_rom_printf(DRAM_STR("Hello world!\n")); +#define DRAM_STR(str) (__extension__({static const DRAM_ATTR char __c[] = (str); (const char *)&__c;})) + +// Forces code into RTC fast memory. See "docs/deep-sleep-stub.rst" +#define RTC_IRAM_ATTR _SECTION_ATTR_IMPL(".rtc.text", __COUNTER__) + +#if CONFIG_SPIRAM_ALLOW_BSS_SEG_EXTERNAL_MEMORY +// Forces bss variable into external memory. " +#define EXT_RAM_ATTR _SECTION_ATTR_IMPL(".ext_ram.bss", __COUNTER__) +#else +#define EXT_RAM_ATTR +#endif + +// Forces data into RTC slow memory. See "docs/deep-sleep-stub.rst" +// Any variable marked with this attribute will keep its value +// during a deep sleep / wake cycle. +#define RTC_DATA_ATTR _SECTION_ATTR_IMPL(".rtc.data", __COUNTER__) + +// Forces read-only data into RTC memory. See "docs/deep-sleep-stub.rst" +#define RTC_RODATA_ATTR _SECTION_ATTR_IMPL(".rtc.rodata", __COUNTER__) + +// Allows to place data into RTC_SLOW memory. +#define RTC_SLOW_ATTR _SECTION_ATTR_IMPL(".rtc.force_slow", __COUNTER__) + +// Allows to place data into RTC_FAST memory. +#define RTC_FAST_ATTR _SECTION_ATTR_IMPL(".rtc.force_fast", __COUNTER__) + +// Forces data into noinit section to avoid initialization after restart. +#define __NOINIT_ATTR _SECTION_ATTR_IMPL(".noinit", __COUNTER__) + +// Forces data into RTC slow memory of .noinit section. +// Any variable marked with this attribute will keep its value +// after restart or during a deep sleep / wake cycle. +#define RTC_NOINIT_ATTR _SECTION_ATTR_IMPL(".rtc_noinit", __COUNTER__) + +// Forces code into DRAM instead of flash and map it to coredump +#define COREDUMP_DRAM_ATTR _SECTION_ATTR_IMPL(".dram1.coredump", __COUNTER__) + +// Forces data into RTC memory and map it to coredump +#define COREDUMP_RTC_DATA_ATTR _SECTION_ATTR_IMPL(".rtc.coredump", __COUNTER__) + +// Allows to place data into RTC_FAST memory and map it to coredump +#define COREDUMP_RTC_FAST_ATTR _SECTION_ATTR_IMPL(".rtc.fast.coredump", __COUNTER__) + +// Forces to not inline function +#define NOINLINE_ATTR __attribute__((noinline)) + +// This allows using enum as flags in C++ +// Format: FLAG_ATTR(flag_enum_t) +#ifdef __cplusplus + +// Inline is required here to avoid multiple definition error in linker +#define FLAG_ATTR_IMPL(TYPE, INT_TYPE) \ +FORCE_INLINE_ATTR constexpr TYPE operator~ (TYPE a) { return (TYPE)~(INT_TYPE)a; } \ +FORCE_INLINE_ATTR constexpr TYPE operator| (TYPE a, TYPE b) { return (TYPE)((INT_TYPE)a | (INT_TYPE)b); } \ +FORCE_INLINE_ATTR constexpr TYPE operator& (TYPE a, TYPE b) { return (TYPE)((INT_TYPE)a & (INT_TYPE)b); } \ +FORCE_INLINE_ATTR constexpr TYPE operator^ (TYPE a, TYPE b) { return (TYPE)((INT_TYPE)a ^ (INT_TYPE)b); } \ +FORCE_INLINE_ATTR constexpr TYPE operator>> (TYPE a, int b) { return (TYPE)((INT_TYPE)a >> b); } \ +FORCE_INLINE_ATTR constexpr TYPE operator<< (TYPE a, int b) { return (TYPE)((INT_TYPE)a << b); } \ +FORCE_INLINE_ATTR TYPE& operator|=(TYPE& a, TYPE b) { a = a | b; return a; } \ +FORCE_INLINE_ATTR TYPE& operator&=(TYPE& a, TYPE b) { a = a & b; return a; } \ +FORCE_INLINE_ATTR TYPE& operator^=(TYPE& a, TYPE b) { a = a ^ b; return a; } \ +FORCE_INLINE_ATTR TYPE& operator>>=(TYPE& a, int b) { a >>= b; return a; } \ +FORCE_INLINE_ATTR TYPE& operator<<=(TYPE& a, int b) { a <<= b; return a; } + +#define FLAG_ATTR_U32(TYPE) FLAG_ATTR_IMPL(TYPE, uint32_t) +#define FLAG_ATTR FLAG_ATTR_U32 + +#else +#define FLAG_ATTR(TYPE) +#endif + +// Implementation for a unique custom section +// +// This prevents gcc producing "x causes a section type conflict with y" +// errors if two variables in the same source file have different linkage (maybe const & non-const) but are placed in the same custom section +// +// Using unique sections also means --gc-sections can remove unused +// data with a custom section type set +#define _SECTION_ATTR_IMPL(SECTION, COUNTER) __attribute__((section(SECTION "." _COUNTER_STRINGIFY(COUNTER)))) + +#define _COUNTER_STRINGIFY(COUNTER) #COUNTER + +/* Use IDF_DEPRECATED attribute to mark anything deprecated from use in + ESP-IDF's own source code, but not deprecated for external users. +*/ +#ifdef IDF_CI_BUILD +#define IDF_DEPRECATED(REASON) __attribute__((deprecated(REASON))) +#else +#define IDF_DEPRECATED(REASON) +#endif + +#ifdef __cplusplus +} +#endif +#endif /* __ESP_ATTR_H__ */ + diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_bit_defs.h b/tools/sdk/esp32c3/include/esp_common/include/esp_bit_defs.h new file mode 100644 index 00000000..6c1600b6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_bit_defs.h @@ -0,0 +1,96 @@ +// Copyright 2010-2019 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. + +#pragma once + +//Register Bits{{ +#define BIT31 0x80000000 +#define BIT30 0x40000000 +#define BIT29 0x20000000 +#define BIT28 0x10000000 +#define BIT27 0x08000000 +#define BIT26 0x04000000 +#define BIT25 0x02000000 +#define BIT24 0x01000000 +#define BIT23 0x00800000 +#define BIT22 0x00400000 +#define BIT21 0x00200000 +#define BIT20 0x00100000 +#define BIT19 0x00080000 +#define BIT18 0x00040000 +#define BIT17 0x00020000 +#define BIT16 0x00010000 +#define BIT15 0x00008000 +#define BIT14 0x00004000 +#define BIT13 0x00002000 +#define BIT12 0x00001000 +#define BIT11 0x00000800 +#define BIT10 0x00000400 +#define BIT9 0x00000200 +#define BIT8 0x00000100 +#define BIT7 0x00000080 +#define BIT6 0x00000040 +#define BIT5 0x00000020 +#define BIT4 0x00000010 +#define BIT3 0x00000008 +#define BIT2 0x00000004 +#define BIT1 0x00000002 +#define BIT0 0x00000001 +//}} + +#define BIT63 (0x80000000ULL << 32) +#define BIT62 (0x40000000ULL << 32) +#define BIT61 (0x20000000ULL << 32) +#define BIT60 (0x10000000ULL << 32) +#define BIT59 (0x08000000ULL << 32) +#define BIT58 (0x04000000ULL << 32) +#define BIT57 (0x02000000ULL << 32) +#define BIT56 (0x01000000ULL << 32) +#define BIT55 (0x00800000ULL << 32) +#define BIT54 (0x00400000ULL << 32) +#define BIT53 (0x00200000ULL << 32) +#define BIT52 (0x00100000ULL << 32) +#define BIT51 (0x00080000ULL << 32) +#define BIT50 (0x00040000ULL << 32) +#define BIT49 (0x00020000ULL << 32) +#define BIT48 (0x00010000ULL << 32) +#define BIT47 (0x00008000ULL << 32) +#define BIT46 (0x00004000ULL << 32) +#define BIT45 (0x00002000ULL << 32) +#define BIT44 (0x00001000ULL << 32) +#define BIT43 (0x00000800ULL << 32) +#define BIT42 (0x00000400ULL << 32) +#define BIT41 (0x00000200ULL << 32) +#define BIT40 (0x00000100ULL << 32) +#define BIT39 (0x00000080ULL << 32) +#define BIT38 (0x00000040ULL << 32) +#define BIT37 (0x00000020ULL << 32) +#define BIT36 (0x00000010ULL << 32) +#define BIT35 (0x00000008ULL << 32) +#define BIT34 (0x00000004ULL << 32) +#define BIT33 (0x00000002ULL << 32) +#define BIT32 (0x00000001ULL << 32) + +#ifndef __ASSEMBLER__ +#ifndef BIT +#define BIT(nr) (1UL << (nr)) +#endif +#ifndef BIT64 +#define BIT64(nr) (1ULL << (nr)) +#endif +#else +#ifndef BIT +#define BIT(nr) (1 << (nr)) +#endif +#endif diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_check.h b/tools/sdk/esp32c3/include/esp_common/include/esp_check.h new file mode 100644 index 00000000..3ee631c3 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_check.h @@ -0,0 +1,188 @@ +// Copyright 2021 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. +#pragma once + +#include "esp_err.h" +#include "esp_log.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message and returns. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_RETURN_ON_ERROR(x, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + return err_rc_; \ + } \ + } while(0) +#else +#define ESP_RETURN_ON_ERROR(x, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ESP_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return err_rc_; \ + } \ + } while(0) +#endif + +/** + * A version of ESP_RETURN_ON_ERROR() macro that can be called from ISR. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_RETURN_ON_ERROR_ISR(x, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + return err_rc_; \ + } \ + } while(0) +#else +#define ESP_RETURN_ON_ERROR_ISR(x, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ESP_EARLY_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return err_rc_; \ + } \ + } while(0) +#endif + +/** + * Macro which can be used to check the error code. If the code is not ESP_OK, it prints the message, + * sets the local variable 'ret' to the code, and then exits by jumping to 'goto_tag'. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_GOTO_ON_ERROR(x, goto_tag, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ret = err_rc_; \ + goto goto_tag; \ + } \ + } while(0) +#else +#define ESP_GOTO_ON_ERROR(x, goto_tag, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ESP_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + ret = err_rc_; \ + goto goto_tag; \ + } \ + } while(0) +#endif + +/** + * A version of ESP_GOTO_ON_ERROR() macro that can be called from ISR. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_GOTO_ON_ERROR_ISR(x, goto_tag, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ret = err_rc_; \ + goto goto_tag; \ + } \ + } while(0) +#else +#define ESP_GOTO_ON_ERROR_ISR(x, goto_tag, log_tag, format, ...) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + ESP_EARLY_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + ret = err_rc_; \ + goto goto_tag; \ + } \ + } while(0) +#endif + +/** + * Macro which can be used to check the condition. If the condition is not 'true', it prints the message + * and returns with the supplied 'err_code'. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_RETURN_ON_FALSE(a, err_code, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + return err_code; \ + } \ + } while(0) +#else +#define ESP_RETURN_ON_FALSE(a, err_code, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ESP_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return err_code; \ + } \ + } while(0) +#endif + +/** + * A version of ESP_RETURN_ON_FALSE() macro that can be called from ISR. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_RETURN_ON_FALSE_ISR(a, err_code, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + return err_code; \ + } \ + } while(0) +#else +#define ESP_RETURN_ON_FALSE_ISR(a, err_code, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ESP_EARLY_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return err_code; \ + } \ + } while(0) +#endif + +/** + * Macro which can be used to check the condition. If the condition is not 'true', it prints the message, + * sets the local variable 'ret' to the supplied 'err_code', and then exits by jumping to 'goto_tag'. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_GOTO_ON_FALSE(a, err_code, goto_tag, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ret = err_code; \ + goto goto_tag; \ + } \ + } while (0) +#else +#define ESP_GOTO_ON_FALSE(a, err_code, goto_tag, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ESP_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + ret = err_code; \ + goto goto_tag; \ + } \ + } while (0) +#endif + +/** + * A version of ESP_GOTO_ON_FALSE() macro that can be called from ISR. + */ +#if defined(CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT) +#define ESP_GOTO_ON_FALSE_ISR(a, err_code, goto_tag, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ret = err_code; \ + goto goto_tag; \ + } \ + } while (0) +#else +#define ESP_GOTO_ON_FALSE_ISR(a, err_code, goto_tag, log_tag, format, ...) do { \ + if (unlikely(!(a))) { \ + ESP_EARLY_LOGE(log_tag, "%s(%d): " format, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + ret = err_code; \ + goto goto_tag; \ + } \ + } while (0) +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_compiler.h b/tools/sdk/esp32c3/include/esp_common/include/esp_compiler.h new file mode 100644 index 00000000..917c6602 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_compiler.h @@ -0,0 +1,59 @@ +// Copyright 2016-2019 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. +#ifndef __ESP_COMPILER_H +#define __ESP_COMPILER_H + +/* + * The likely and unlikely macro pairs: + * These macros are useful to place when application + * knows the majority ocurrence of a decision paths, + * placing one of these macros can hint the compiler + * to reorder instructions producing more optimized + * code. + */ +#if (CONFIG_COMPILER_OPTIMIZATION_PERF) +#ifndef likely +#define likely(x) __builtin_expect(!!(x), 1) +#endif +#ifndef unlikely +#define unlikely(x) __builtin_expect(!!(x), 0) +#endif +#else +#ifndef likely +#define likely(x) (x) +#endif +#ifndef unlikely +#define unlikely(x) (x) +#endif +#endif + +/* + * Utility macros used for designated initializers, which work differently + * in C99 and C++ standards mainly for aggregate types. + * The member separator, comma, is already part of the macro, please omit the trailing comma. + * Usage example: + * struct config_t { char* pchr; char arr[SIZE]; } config = { + * ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(pchr) + * ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_STR(arr, "Value") + * }; + */ +#ifdef __cplusplus +#define ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_STR(member, value) { .member = value }, +#define ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(member) .member = { }, +#else +#define ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_STR(member, value) .member = value, +#define ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(member) +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_err.h b/tools/sdk/esp32c3/include/esp_common/include/esp_err.h new file mode 100644 index 00000000..3a1c8c62 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_err.h @@ -0,0 +1,151 @@ +// Copyright 2015-2016 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. +#pragma once + +#include +#include +#include +#include "esp_compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef int esp_err_t; + +/* Definitions for error constants. */ +#define ESP_OK 0 /*!< esp_err_t value indicating success (no error) */ +#define ESP_FAIL -1 /*!< Generic esp_err_t code indicating failure */ + +#define ESP_ERR_NO_MEM 0x101 /*!< Out of memory */ +#define ESP_ERR_INVALID_ARG 0x102 /*!< Invalid argument */ +#define ESP_ERR_INVALID_STATE 0x103 /*!< Invalid state */ +#define ESP_ERR_INVALID_SIZE 0x104 /*!< Invalid size */ +#define ESP_ERR_NOT_FOUND 0x105 /*!< Requested resource not found */ +#define ESP_ERR_NOT_SUPPORTED 0x106 /*!< Operation or feature not supported */ +#define ESP_ERR_TIMEOUT 0x107 /*!< Operation timed out */ +#define ESP_ERR_INVALID_RESPONSE 0x108 /*!< Received response was invalid */ +#define ESP_ERR_INVALID_CRC 0x109 /*!< CRC or checksum was invalid */ +#define ESP_ERR_INVALID_VERSION 0x10A /*!< Version was invalid */ +#define ESP_ERR_INVALID_MAC 0x10B /*!< MAC address was invalid */ + +#define ESP_ERR_WIFI_BASE 0x3000 /*!< Starting number of WiFi error codes */ +#define ESP_ERR_MESH_BASE 0x4000 /*!< Starting number of MESH error codes */ +#define ESP_ERR_FLASH_BASE 0x6000 /*!< Starting number of flash error codes */ +#define ESP_ERR_HW_CRYPTO_BASE 0xc000 /*!< Starting number of HW cryptography module error codes */ + +/** + * @brief Returns string for esp_err_t error codes + * + * This function finds the error code in a pre-generated lookup-table and + * returns its string representation. + * + * The function is generated by the Python script + * tools/gen_esp_err_to_name.py which should be run each time an esp_err_t + * error is modified, created or removed from the IDF project. + * + * @param code esp_err_t error code + * @return string error message + */ +const char *esp_err_to_name(esp_err_t code); + +/** + * @brief Returns string for esp_err_t and system error codes + * + * This function finds the error code in a pre-generated lookup-table of + * esp_err_t errors and returns its string representation. If the error code + * is not found then it is attempted to be found among system errors. + * + * The function is generated by the Python script + * tools/gen_esp_err_to_name.py which should be run each time an esp_err_t + * error is modified, created or removed from the IDF project. + * + * @param code esp_err_t error code + * @param[out] buf buffer where the error message should be written + * @param buflen Size of buffer buf. At most buflen bytes are written into the buf buffer (including the terminating null byte). + * @return buf containing the string error message + */ +const char *esp_err_to_name_r(esp_err_t code, char *buf, size_t buflen); + +/** @cond */ +void _esp_error_check_failed(esp_err_t rc, const char *file, int line, const char *function, const char *expression) __attribute__((noreturn)); + +/** @cond */ +void _esp_error_check_failed_without_abort(esp_err_t rc, const char *file, int line, const char *function, const char *expression); + +#ifndef __ASSERT_FUNC +/* This won't happen on IDF, which defines __ASSERT_FUNC in assert.h, but it does happen when building on the host which + uses /usr/include/assert.h or equivalent. +*/ +#ifdef __ASSERT_FUNCTION +#define __ASSERT_FUNC __ASSERT_FUNCTION /* used in glibc assert.h */ +#else +#define __ASSERT_FUNC "??" +#endif +#endif +/** @endcond */ + +/** + * Macro which can be used to check the error code, + * and terminate the program in case the code is not ESP_OK. + * Prints the error code, error location, and the failed statement to serial output. + * + * Disabled if assertions are disabled. + */ +#ifdef NDEBUG +#define ESP_ERROR_CHECK(x) do { \ + esp_err_t err_rc_ = (x); \ + (void) sizeof(err_rc_); \ + } while(0) +#elif defined(CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT) +#define ESP_ERROR_CHECK(x) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + abort(); \ + } \ + } while(0) +#else +#define ESP_ERROR_CHECK(x) do { \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + _esp_error_check_failed(err_rc_, __FILE__, __LINE__, \ + __ASSERT_FUNC, #x); \ + } \ + } while(0) +#endif + +/** + * Macro which can be used to check the error code. Prints the error code, error location, and the failed statement to + * serial output. + * In comparison with ESP_ERROR_CHECK(), this prints the same error message but isn't terminating the program. + */ +#ifdef NDEBUG +#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) ({ \ + esp_err_t err_rc_ = (x); \ + err_rc_; \ + }) +#else +#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) ({ \ + esp_err_t err_rc_ = (x); \ + if (unlikely(err_rc_ != ESP_OK)) { \ + _esp_error_check_failed_without_abort(err_rc_, __FILE__, __LINE__, \ + __ASSERT_FUNC, #x); \ + } \ + err_rc_; \ + }) +#endif //NDEBUG + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_idf_version.h b/tools/sdk/esp32c3/include/esp_common/include/esp_idf_version.h new file mode 100644 index 00000000..7637b814 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_idf_version.h @@ -0,0 +1,62 @@ +// Copyright 2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** Major version number (X.x.x) */ +#define ESP_IDF_VERSION_MAJOR 4 +/** Minor version number (x.X.x) */ +#define ESP_IDF_VERSION_MINOR 4 +/** Patch version number (x.x.X) */ +#define ESP_IDF_VERSION_PATCH 0 + +/** + * Macro to convert IDF version number into an integer + * + * To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) + */ +#define ESP_IDF_VERSION_VAL(major, minor, patch) ((major << 16) | (minor << 8) | (patch)) + +/** + * Current IDF version, as an integer + * + * To be used in comparisons, such as ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 0, 0) + */ +#define ESP_IDF_VERSION ESP_IDF_VERSION_VAL(ESP_IDF_VERSION_MAJOR, \ + ESP_IDF_VERSION_MINOR, \ + ESP_IDF_VERSION_PATCH) + +#ifndef __ASSEMBLER__ + +/** + * Return full IDF version string, same as 'git describe' output. + * + * @note If you are printing the ESP-IDF version in a log file or other information, + * this function provides more information than using the numerical version macros. + * For example, numerical version macros don't differentiate between development, + * pre-release and release versions, but the output of this function does. + * + * @return constant string from IDF_VER + */ +const char* esp_get_idf_version(void); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_common/include/esp_types.h b/tools/sdk/esp32c3/include/esp_common/include/esp_types.h new file mode 100644 index 00000000..547024e3 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_common/include/esp_types.h @@ -0,0 +1,25 @@ +// Copyright 2010-2016 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. + +#ifndef __ESP_TYPES_H__ +#define __ESP_TYPES_H__ + +#ifdef __GNUC__ +#include +#endif /*__GNUC__*/ +#include +#include +#include + +#endif /* __ESP_TYPES_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_eth/include/esp_eth.h b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth.h new file mode 100644 index 00000000..480349d5 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth.h @@ -0,0 +1,261 @@ +// Copyright 2019 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. +#pragma once + +#include "esp_eth_com.h" +#include "esp_eth_mac.h" +#include "esp_eth_phy.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief Handle of Ethernet driver +* +*/ +typedef void *esp_eth_handle_t; + +/** +* @brief Configuration of Ethernet driver +* +*/ +typedef struct { + /** + * @brief Ethernet MAC object + * + */ + esp_eth_mac_t *mac; + + /** + * @brief Ethernet PHY object + * + */ + esp_eth_phy_t *phy; + + /** + * @brief Period time of checking Ethernet link status + * + */ + uint32_t check_link_period_ms; + + /** + * @brief Input frame buffer to user's stack + * + * @param[in] eth_handle: handle of Ethernet driver + * @param[in] buffer: frame buffer that will get input to upper stack + * @param[in] length: length of the frame buffer + * + * @return + * - ESP_OK: input frame buffer to upper stack successfully + * - ESP_FAIL: error occurred when inputting buffer to upper stack + * + */ + esp_err_t (*stack_input)(esp_eth_handle_t eth_handle, uint8_t *buffer, uint32_t length, void *priv); + + /** + * @brief Callback function invoked when lowlevel initialization is finished + * + * @param[in] eth_handle: handle of Ethernet driver + * + * @return + * - ESP_OK: process extra lowlevel initialization successfully + * - ESP_FAIL: error occurred when processing extra lowlevel initialization + */ + esp_err_t (*on_lowlevel_init_done)(esp_eth_handle_t eth_handle); + + /** + * @brief Callback function invoked when lowlevel deinitialization is finished + * + * @param[in] eth_handle: handle of Ethernet driver + * + * @return + * - ESP_OK: process extra lowlevel deinitialization successfully + * - ESP_FAIL: error occurred when processing extra lowlevel deinitialization + */ + esp_err_t (*on_lowlevel_deinit_done)(esp_eth_handle_t eth_handle); + +} esp_eth_config_t; + +/** + * @brief Default configuration for Ethernet driver + * + */ +#define ETH_DEFAULT_CONFIG(emac, ephy) \ + { \ + .mac = emac, \ + .phy = ephy, \ + .check_link_period_ms = 2000, \ + .stack_input = NULL, \ + .on_lowlevel_init_done = NULL, \ + .on_lowlevel_deinit_done = NULL, \ + } + +/** +* @brief Install Ethernet driver +* +* @param[in] config: configuration of the Ethernet driver +* @param[out] out_hdl: handle of Ethernet driver +* +* @return +* - ESP_OK: install esp_eth driver successfully +* - ESP_ERR_INVALID_ARG: install esp_eth driver failed because of some invalid argument +* - ESP_ERR_NO_MEM: install esp_eth driver failed because there's no memory for driver +* - ESP_FAIL: install esp_eth driver failed because some other error occurred +*/ +esp_err_t esp_eth_driver_install(const esp_eth_config_t *config, esp_eth_handle_t *out_hdl); + +/** +* @brief Uninstall Ethernet driver +* @note It's not recommended to uninstall Ethernet driver unless it won't get used any more in application code. +* To uninstall Ethernet driver, you have to make sure, all references to the driver are released. +* Ethernet driver can only be uninstalled successfully when reference counter equals to one. +* +* @param[in] hdl: handle of Ethernet driver +* +* @return +* - ESP_OK: uninstall esp_eth driver successfully +* - ESP_ERR_INVALID_ARG: uninstall esp_eth driver failed because of some invalid argument +* - ESP_ERR_INVALID_STATE: uninstall esp_eth driver failed because it has more than one reference +* - ESP_FAIL: uninstall esp_eth driver failed because some other error occurred +*/ +esp_err_t esp_eth_driver_uninstall(esp_eth_handle_t hdl); + +/** +* @brief Start Ethernet driver **ONLY** in standalone mode (i.e. without TCP/IP stack) +* +* @note This API will start driver state machine and internal software timer (for checking link status). +* +* @param[in] hdl handle of Ethernet driver +* +* @return +* - ESP_OK: start esp_eth driver successfully +* - ESP_ERR_INVALID_ARG: start esp_eth driver failed because of some invalid argument +* - ESP_ERR_INVALID_STATE: start esp_eth driver failed because driver has started already +* - ESP_FAIL: start esp_eth driver failed because some other error occurred +*/ +esp_err_t esp_eth_start(esp_eth_handle_t hdl); + +/** +* @brief Stop Ethernet driver +* +* @note This function does the oppsite operation of `esp_eth_start`. +* +* @param[in] hdl handle of Ethernet driver +* @return +* - ESP_OK: stop esp_eth driver successfully +* - ESP_ERR_INVALID_ARG: stop esp_eth driver failed because of some invalid argument +* - ESP_ERR_INVALID_STATE: stop esp_eth driver failed because driver has not started yet +* - ESP_FAIL: stop esp_eth driver failed because some other error occurred +*/ +esp_err_t esp_eth_stop(esp_eth_handle_t hdl); + +/** +* @brief Update Ethernet data input path (i.e. specify where to pass the input buffer) +* +* @note After install driver, Ethernet still don't know where to deliver the input buffer. +* In fact, this API registers a callback function which get invoked when Ethernet received new packets. +* +* @param[in] hdl handle of Ethernet driver +* @param[in] stack_input function pointer, which does the actual process on incoming packets +* @param[in] priv private resource, which gets passed to `stack_input` callback without any modification +* @return +* - ESP_OK: update input path successfully +* - ESP_ERR_INVALID_ARG: update input path failed because of some invalid argument +* - ESP_FAIL: update input path failed because some other error occurred +*/ +esp_err_t esp_eth_update_input_path( + esp_eth_handle_t hdl, + esp_err_t (*stack_input)(esp_eth_handle_t hdl, uint8_t *buffer, uint32_t length, void *priv), + void *priv); + +/** +* @brief General Transmit +* +* @param[in] hdl: handle of Ethernet driver +* @param[in] buf: buffer of the packet to transfer +* @param[in] length: length of the buffer to transfer +* +* @return +* - ESP_OK: transmit frame buffer successfully +* - ESP_ERR_INVALID_ARG: transmit frame buffer failed because of some invalid argument +* - ESP_FAIL: transmit frame buffer failed because some other error occurred +*/ +esp_err_t esp_eth_transmit(esp_eth_handle_t hdl, void *buf, size_t length); + +/** +* @brief General Receive is deprecated and shall not be accessed from app code, +* as polling is not supported by Ethernet. +* +* @param[in] hdl: handle of Ethernet driver +* @param[out] buf: buffer to preserve the received packet +* @param[out] length: length of the received packet +* +* @note Before this function got invoked, the value of "length" should set by user, equals the size of buffer. +* After the function returned, the value of "length" means the real length of received data. +* @note This API was exposed by accident, users should not use this API in their applications. +* Ethernet driver is interrupt driven, and doesn't support polling mode. +* Instead, users should register input callback with ``esp_eth_update_input_path``. +* +* @return +* - ESP_OK: receive frame buffer successfully +* - ESP_ERR_INVALID_ARG: receive frame buffer failed because of some invalid argument +* - ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. +* in this case, value of returned "length" indicates the real size of incoming data. +* - ESP_FAIL: receive frame buffer failed because some other error occurred +*/ +esp_err_t esp_eth_receive(esp_eth_handle_t hdl, uint8_t *buf, uint32_t *length) __attribute__((deprecated("Ethernet driver is interrupt driven only, please register input callback with esp_eth_update_input_path"))); + +/** +* @brief Misc IO function of Etherent driver +* +* @param[in] hdl: handle of Ethernet driver +* @param[in] cmd: IO control command +* @param[in] data: specificed data for command +* +* @return +* - ESP_OK: process io command successfully +* - ESP_ERR_INVALID_ARG: process io command failed because of some invalid argument +* - ESP_FAIL: process io command failed because some other error occurred +*/ +esp_err_t esp_eth_ioctl(esp_eth_handle_t hdl, esp_eth_io_cmd_t cmd, void *data); + +/** +* @brief Increase Ethernet driver reference +* @note Ethernet driver handle can be obtained by os timer, netif, etc. +* It's dangerous when thread A is using Ethernet but thread B uninstall the driver. +* Using reference counter can prevent such risk, but care should be taken, when you obtain Ethernet driver, +* this API must be invoked so that the driver won't be uninstalled during your using time. +* +* +* @param[in] hdl: handle of Ethernet driver +* @return +* - ESP_OK: increase reference successfully +* - ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument +*/ +esp_err_t esp_eth_increase_reference(esp_eth_handle_t hdl); + +/** +* @brief Decrease Ethernet driver reference +* +* @param[in] hdl: handle of Ethernet driver +* @return +* - ESP_OK: increase reference successfully +* - ESP_ERR_INVALID_ARG: increase reference failed because of some invalid argument +*/ +esp_err_t esp_eth_decrease_reference(esp_eth_handle_t hdl); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_com.h b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_com.h new file mode 100644 index 00000000..b8d831cf --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_com.h @@ -0,0 +1,227 @@ +// Copyright 2019 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. +#pragma once + +#include "esp_err.h" +#include "esp_event_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Maximum Ethernet payload size + * + */ +#define ETH_MAX_PAYLOAD_LEN (1500) + +/** + * @brief Minimum Ethernet payload size + * + */ +#define ETH_MIN_PAYLOAD_LEN (46) + +/** + * @brief Ethernet frame header size: Dest addr(6 Bytes) + Src addr(6 Bytes) + length/type(2 Bytes) + * + */ +#define ETH_HEADER_LEN (14) + +/** + * @brief Ethernet frame CRC length + * + */ +#define ETH_CRC_LEN (4) + +/** + * @brief Optional 802.1q VLAN Tag length + * + */ +#define ETH_VLAN_TAG_LEN (4) + +/** + * @brief Jumbo frame payload size + * + */ +#define ETH_JUMBO_FRAME_PAYLOAD_LEN (9000) + +/** + * @brief Maximum frame size (1522 Bytes) + * + */ +#define ETH_MAX_PACKET_SIZE (ETH_HEADER_LEN + ETH_VLAN_TAG_LEN + ETH_MAX_PAYLOAD_LEN + ETH_CRC_LEN) + +/** + * @brief Minimum frame size (64 Bytes) + * + */ +#define ETH_MIN_PACKET_SIZE (ETH_HEADER_LEN + ETH_MIN_PAYLOAD_LEN + ETH_CRC_LEN) + +/** +* @brief Ethernet driver state +* +*/ +typedef enum { + ETH_STATE_LLINIT, /*!< Lowlevel init done */ + ETH_STATE_DEINIT, /*!< Deinit done */ + ETH_STATE_LINK, /*!< Link status changed */ + ETH_STATE_SPEED, /*!< Speed updated */ + ETH_STATE_DUPLEX, /*!< Duplex updated */ + ETH_STATE_PAUSE, /*!< Pause ability updated */ +} esp_eth_state_t; + +/** +* @brief Command list for ioctl API +* +*/ +typedef enum { + ETH_CMD_G_MAC_ADDR, /*!< Get MAC address */ + ETH_CMD_S_MAC_ADDR, /*!< Set MAC address */ + ETH_CMD_G_PHY_ADDR, /*!< Get PHY address */ + ETH_CMD_S_PHY_ADDR, /*!< Set PHY address */ + ETH_CMD_G_SPEED, /*!< Get Speed */ + ETH_CMD_S_PROMISCUOUS, /*!< Set promiscuous mode */ + ETH_CMD_S_FLOW_CTRL, /*!< Set flow control */ + ETH_CMD_G_DUPLEX_MODE, /*!< Get Duplex mode */ +} esp_eth_io_cmd_t; + +/** +* @brief Ethernet link status +* +*/ +typedef enum { + ETH_LINK_UP, /*!< Ethernet link is up */ + ETH_LINK_DOWN /*!< Ethernet link is down */ +} eth_link_t; + +/** +* @brief Ethernet speed +* +*/ +typedef enum { + ETH_SPEED_10M, /*!< Ethernet speed is 10Mbps */ + ETH_SPEED_100M /*!< Ethernet speed is 100Mbps */ +} eth_speed_t; + +/** +* @brief Ethernet duplex mode +* +*/ +typedef enum { + ETH_DUPLEX_HALF, /*!< Ethernet is in half duplex */ + ETH_DUPLEX_FULL /*!< Ethernet is in full duplex */ +} eth_duplex_t; + +/** +* @brief Ethernet mediator +* +*/ +typedef struct esp_eth_mediator_s esp_eth_mediator_t; + +/** +* @brief Ethernet mediator +* +*/ +struct esp_eth_mediator_s { + /** + * @brief Read PHY register + * + * @param[in] eth: mediator of Ethernet driver + * @param[in] phy_addr: PHY Chip address (0~31) + * @param[in] phy_reg: PHY register index code + * @param[out] reg_value: PHY register value + * + * @return + * - ESP_OK: read PHY register successfully + * - ESP_FAIL: read PHY register failed because some error occurred + * + */ + esp_err_t (*phy_reg_read)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value); + + /** + * @brief Write PHY register + * + * @param[in] eth: mediator of Ethernet driver + * @param[in] phy_addr: PHY Chip address (0~31) + * @param[in] phy_reg: PHY register index code + * @param[in] reg_value: PHY register value + * + * @return + * - ESP_OK: write PHY register successfully + * - ESP_FAIL: write PHY register failed because some error occurred + */ + esp_err_t (*phy_reg_write)(esp_eth_mediator_t *eth, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value); + + /** + * @brief Deliver packet to upper stack + * + * @param[in] eth: mediator of Ethernet driver + * @param[in] buffer: packet buffer + * @param[in] length: length of the packet + * + * @return + * - ESP_OK: deliver packet to upper stack successfully + * - ESP_FAIL: deliver packet failed because some error occurred + * + */ + esp_err_t (*stack_input)(esp_eth_mediator_t *eth, uint8_t *buffer, uint32_t length); + + /** + * @brief Callback on Ethernet state changed + * + * @param[in] eth: mediator of Ethernet driver + * @param[in] state: new state + * @param[in] args: optional argument for the new state + * + * @return + * - ESP_OK: process the new state successfully + * - ESP_FAIL: process the new state failed because some error occurred + * + */ + esp_err_t (*on_state_changed)(esp_eth_mediator_t *eth, esp_eth_state_t state, void *args); +}; + +/** +* @brief Ethernet event declarations +* +*/ +typedef enum { + ETHERNET_EVENT_START, /*!< Ethernet driver start */ + ETHERNET_EVENT_STOP, /*!< Ethernet driver stop */ + ETHERNET_EVENT_CONNECTED, /*!< Ethernet got a valid link */ + ETHERNET_EVENT_DISCONNECTED, /*!< Ethernet lost a valid link */ +} eth_event_t; + +/** +* @brief Ethernet event base declaration +* +*/ +ESP_EVENT_DECLARE_BASE(ETH_EVENT); + +/** +* @brief Detect PHY address +* +* @param[in] eth: mediator of Ethernet driver +* @param[out] detected_addr: a valid address after detection +* @return +* - ESP_OK: detect phy address successfully +* - ESP_ERR_INVALID_ARG: invalid parameter +* - ESP_ERR_NOT_FOUND: can't detect any PHY device +* - ESP_FAIL: detect phy address failed because some error occurred +*/ +esp_err_t esp_eth_detect_phy_addr(esp_eth_mediator_t *eth, int *detected_addr); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_mac.h b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_mac.h new file mode 100644 index 00000000..7543fdd2 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_mac.h @@ -0,0 +1,414 @@ +// Copyright 2019 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. +#pragma once + +#include +#include "esp_eth_com.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** +* @brief Ethernet MAC +* +*/ +typedef struct esp_eth_mac_s esp_eth_mac_t; + +/** +* @brief Ethernet MAC +* +*/ +struct esp_eth_mac_s { + /** + * @brief Set mediator for Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[in] eth: Ethernet mediator + * + * @return + * - ESP_OK: set mediator for Ethernet MAC successfully + * - ESP_ERR_INVALID_ARG: set mediator for Ethernet MAC failed because of invalid argument + * + */ + esp_err_t (*set_mediator)(esp_eth_mac_t *mac, esp_eth_mediator_t *eth); + + /** + * @brief Initialize Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * + * @return + * - ESP_OK: initialize Ethernet MAC successfully + * - ESP_ERR_TIMEOUT: initialize Ethernet MAC failed because of timeout + * - ESP_FAIL: initialize Ethernet MAC failed because some other error occurred + * + */ + esp_err_t (*init)(esp_eth_mac_t *mac); + + /** + * @brief Deinitialize Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * + * @return + * - ESP_OK: deinitialize Ethernet MAC successfully + * - ESP_FAIL: deinitialize Ethernet MAC failed because some error occurred + * + */ + esp_err_t (*deinit)(esp_eth_mac_t *mac); + + /** + * @brief Start Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * + * @return + * - ESP_OK: start Ethernet MAC successfully + * - ESP_FAIL: start Ethernet MAC failed because some other error occurred + * + */ + esp_err_t (*start)(esp_eth_mac_t *mac); + + /** + * @brief Stop Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * + * @return + * - ESP_OK: stop Ethernet MAC successfully + * - ESP_FAIL: stop Ethernet MAC failed because some error occurred + * + */ + esp_err_t (*stop)(esp_eth_mac_t *mac); + + /** + * @brief Transmit packet from Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[in] buf: packet buffer to transmit + * @param[in] length: length of packet + * + * @return + * - ESP_OK: transmit packet successfully + * - ESP_ERR_INVALID_ARG: transmit packet failed because of invalid argument + * - ESP_ERR_INVALID_STATE: transmit packet failed because of wrong state of MAC + * - ESP_FAIL: transmit packet failed because some other error occurred + * + */ + esp_err_t (*transmit)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t length); + + /** + * @brief Receive packet from Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[out] buf: packet buffer which will preserve the received frame + * @param[out] length: length of the received packet + * + * @note Memory of buf is allocated in the Layer2, make sure it get free after process. + * @note Before this function got invoked, the value of "length" should set by user, equals the size of buffer. + * After the function returned, the value of "length" means the real length of received data. + * + * @return + * - ESP_OK: receive packet successfully + * - ESP_ERR_INVALID_ARG: receive packet failed because of invalid argument + * - ESP_ERR_INVALID_SIZE: input buffer size is not enough to hold the incoming data. + * in this case, value of returned "length" indicates the real size of incoming data. + * - ESP_FAIL: receive packet failed because some other error occurred + * + */ + esp_err_t (*receive)(esp_eth_mac_t *mac, uint8_t *buf, uint32_t *length); + + /** + * @brief Read PHY register + * + * @param[in] mac: Ethernet MAC instance + * @param[in] phy_addr: PHY chip address (0~31) + * @param[in] phy_reg: PHY register index code + * @param[out] reg_value: PHY register value + * + * @return + * - ESP_OK: read PHY register successfully + * - ESP_ERR_INVALID_ARG: read PHY register failed because of invalid argument + * - ESP_ERR_INVALID_STATE: read PHY register failed because of wrong state of MAC + * - ESP_ERR_TIMEOUT: read PHY register failed because of timeout + * - ESP_FAIL: read PHY register failed because some other error occurred + * + */ + esp_err_t (*read_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t *reg_value); + + /** + * @brief Write PHY register + * + * @param[in] mac: Ethernet MAC instance + * @param[in] phy_addr: PHY chip address (0~31) + * @param[in] phy_reg: PHY register index code + * @param[in] reg_value: PHY register value + * + * @return + * - ESP_OK: write PHY register successfully + * - ESP_ERR_INVALID_STATE: write PHY register failed because of wrong state of MAC + * - ESP_ERR_TIMEOUT: write PHY register failed because of timeout + * - ESP_FAIL: write PHY register failed because some other error occurred + * + */ + esp_err_t (*write_phy_reg)(esp_eth_mac_t *mac, uint32_t phy_addr, uint32_t phy_reg, uint32_t reg_value); + + /** + * @brief Set MAC address + * + * @param[in] mac: Ethernet MAC instance + * @param[in] addr: MAC address + * + * @return + * - ESP_OK: set MAC address successfully + * - ESP_ERR_INVALID_ARG: set MAC address failed because of invalid argument + * - ESP_FAIL: set MAC address failed because some other error occurred + * + */ + esp_err_t (*set_addr)(esp_eth_mac_t *mac, uint8_t *addr); + + /** + * @brief Get MAC address + * + * @param[in] mac: Ethernet MAC instance + * @param[out] addr: MAC address + * + * @return + * - ESP_OK: get MAC address successfully + * - ESP_ERR_INVALID_ARG: get MAC address failed because of invalid argument + * - ESP_FAIL: get MAC address failed because some other error occurred + * + */ + esp_err_t (*get_addr)(esp_eth_mac_t *mac, uint8_t *addr); + + /** + * @brief Set speed of MAC + * + * @param[in] ma:c Ethernet MAC instance + * @param[in] speed: MAC speed + * + * @return + * - ESP_OK: set MAC speed successfully + * - ESP_ERR_INVALID_ARG: set MAC speed failed because of invalid argument + * - ESP_FAIL: set MAC speed failed because some other error occurred + * + */ + esp_err_t (*set_speed)(esp_eth_mac_t *mac, eth_speed_t speed); + + /** + * @brief Set duplex mode of MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[in] duplex: MAC duplex + * + * @return + * - ESP_OK: set MAC duplex mode successfully + * - ESP_ERR_INVALID_ARG: set MAC duplex failed because of invalid argument + * - ESP_FAIL: set MAC duplex failed because some other error occurred + * + */ + esp_err_t (*set_duplex)(esp_eth_mac_t *mac, eth_duplex_t duplex); + + /** + * @brief Set link status of MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[in] link: Link status + * + * @return + * - ESP_OK: set link status successfully + * - ESP_ERR_INVALID_ARG: set link status failed because of invalid argument + * - ESP_FAIL: set link status failed because some other error occurred + * + */ + esp_err_t (*set_link)(esp_eth_mac_t *mac, eth_link_t link); + + /** + * @brief Set promiscuous of MAC + * + * @param[in] mac: Ethernet MAC instance + * @param[in] enable: set true to enable promiscuous mode; set false to disable promiscuous mode + * + * @return + * - ESP_OK: set promiscuous mode successfully + * - ESP_FAIL: set promiscuous mode failed because some error occurred + * + */ + esp_err_t (*set_promiscuous)(esp_eth_mac_t *mac, bool enable); + + /** + * @brief Enable flow control on MAC layer or not + * + * @param[in] mac: Ethernet MAC instance + * @param[in] enable: set true to enable flow control; set false to disable flow control + * + * @return + * - ESP_OK: set flow control successfully + * - ESP_FAIL: set flow control failed because some error occurred + * + */ + esp_err_t (*enable_flow_ctrl)(esp_eth_mac_t *mac, bool enable); + + /** + * @brief Set the PAUSE ability of peer node + * + * @param[in] mac: Ethernet MAC instance + * @param[in] ability: zero indicates that pause function is supported by link partner; non-zero indicates that pause function is not supported by link partner + * + * @return + * - ESP_OK: set peer pause ability successfully + * - ESP_FAIL: set peer pause ability failed because some error occurred + */ + esp_err_t (*set_peer_pause_ability)(esp_eth_mac_t *mac, uint32_t ability); + + /** + * @brief Free memory of Ethernet MAC + * + * @param[in] mac: Ethernet MAC instance + * + * @return + * - ESP_OK: free Ethernet MAC instance successfully + * - ESP_FAIL: free Ethernet MAC instance failed because some error occurred + * + */ + esp_err_t (*del)(esp_eth_mac_t *mac); +}; + +/** +* @brief Configuration of Ethernet MAC object +* +*/ +typedef struct { + uint32_t sw_reset_timeout_ms; /*!< Software reset timeout value (Unit: ms) */ + uint32_t rx_task_stack_size; /*!< Stack size of the receive task */ + uint32_t rx_task_prio; /*!< Priority of the receive task */ + int smi_mdc_gpio_num; /*!< SMI MDC GPIO number, set to -1 could bypass the SMI GPIO configuration */ + int smi_mdio_gpio_num; /*!< SMI MDIO GPIO number, set to -1 could bypass the SMI GPIO configuration */ + uint32_t flags; /*!< Flags that specify extra capability for mac driver */ +} eth_mac_config_t; + +#define ETH_MAC_FLAG_WORK_WITH_CACHE_DISABLE (1 << 0) /*!< MAC driver can work when cache is disabled */ +#define ETH_MAC_FLAG_PIN_TO_CORE (1 << 1) /*!< Pin MAC task to the CPU core where driver installation happened */ + +/** + * @brief Default configuration for Ethernet MAC object + * + */ +#define ETH_MAC_DEFAULT_CONFIG() \ + { \ + .sw_reset_timeout_ms = 100, \ + .rx_task_stack_size = 4096, \ + .rx_task_prio = 15, \ + .smi_mdc_gpio_num = 23, \ + .smi_mdio_gpio_num = 18, \ + .flags = 0, \ + } + +#if CONFIG_ETH_USE_ESP32_EMAC +/** +* @brief Create ESP32 Ethernet MAC instance +* +* @param config: Ethernet MAC configuration +* +* @return +* - instance: create MAC instance successfully +* - NULL: create MAC instance failed because some error occurred +*/ +esp_eth_mac_t *esp_eth_mac_new_esp32(const eth_mac_config_t *config); +#endif // CONFIG_ETH_USE_ESP32_EMAC + +#if CONFIG_ETH_SPI_ETHERNET_DM9051 +/** + * @brief DM9051 specific configuration + * + */ +typedef struct { + void *spi_hdl; /*!< Handle of SPI device driver */ + int int_gpio_num; /*!< Interrupt GPIO number */ +} eth_dm9051_config_t; + +/** + * @brief Default DM9051 specific configuration + * + */ +#define ETH_DM9051_DEFAULT_CONFIG(spi_device) \ + { \ + .spi_hdl = spi_device, \ + .int_gpio_num = 4, \ + } + +/** +* @brief Create DM9051 Ethernet MAC instance +* +* @param dm9051_config: DM9051 specific configuration +* @param mac_config: Ethernet MAC configuration +* +* @return +* - instance: create MAC instance successfully +* - NULL: create MAC instance failed because some error occurred +*/ +esp_eth_mac_t *esp_eth_mac_new_dm9051(const eth_dm9051_config_t *dm9051_config, const eth_mac_config_t *mac_config); +#endif // CONFIG_ETH_SPI_ETHERNET_DM9051 + +#if CONFIG_ETH_SPI_ETHERNET_W5500 +/** + * @brief W5500 specific configuration + * + */ +typedef struct { + void *spi_hdl; /*!< Handle of SPI device driver */ + int int_gpio_num; /*!< Interrupt GPIO number */ +} eth_w5500_config_t; + +/** + * @brief Default W5500 specific configuration + * + */ +#define ETH_W5500_DEFAULT_CONFIG(spi_device) \ + { \ + .spi_hdl = spi_device, \ + .int_gpio_num = 4, \ + } + +/** +* @brief Create W5500 Ethernet MAC instance +* +* @param w5500_config: W5500 specific configuration +* @param mac_config: Ethernet MAC configuration +* +* @return +* - instance: create MAC instance successfully +* - NULL: create MAC instance failed because some error occurred +*/ +esp_eth_mac_t *esp_eth_mac_new_w5500(const eth_w5500_config_t *w5500_config, const eth_mac_config_t *mac_config); +#endif // CONFIG_ETH_SPI_ETHERNET_W5500 + +#if CONFIG_ETH_USE_OPENETH +/** +* @brief Create OpenCores Ethernet MAC instance +* +* @param config: Ethernet MAC configuration +* +* @return +* - instance: create MAC instance successfully +* - NULL: create MAC instance failed because some error occurred +*/ +esp_eth_mac_t *esp_eth_mac_new_openeth(const eth_mac_config_t *config); +#endif // CONFIG_ETH_USE_OPENETH + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_netif_glue.h b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_netif_glue.h new file mode 100644 index 00000000..5e88b5ba --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_netif_glue.h @@ -0,0 +1,66 @@ +// Copyright 2019 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. +#pragma once + +#include "esp_eth.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Create a netif glue for Ethernet driver + * @note netif glue is used to attach io driver to TCP/IP netif + * + * @param eth_hdl Ethernet driver handle + * @return glue object, which inherits esp_netif_driver_base_t + */ +void *esp_eth_new_netif_glue(esp_eth_handle_t eth_hdl); + +/** + * @brief Delete netif glue of Ethernet driver + * + * @param glue netif glue + * @return -ESP_OK: delete netif glue successfully + */ +esp_err_t esp_eth_del_netif_glue(void *glue); + +/** + * @brief Register default IP layer handlers for Ethernet + * + * @note: Ethernet handle might not yet properly initialized when setting up these default handlers + * + * @param[in] esp_netif esp network interface handle created for Ethernet driver + * @return + * - ESP_ERR_INVALID_ARG: invalid parameter (esp_netif is NULL) + * - ESP_OK: set default IP layer handlers successfully + * - others: other failure occurred during register esp_event handler + */ + +esp_err_t esp_eth_set_default_handlers(void *esp_netif); + +/** + * @brief Unregister default IP layer handlers for Ethernet + * + * @param[in] esp_netif esp network interface handle created for Ethernet driver + * @return + * - ESP_ERR_INVALID_ARG: invalid parameter (esp_netif is NULL) + * - ESP_OK: clear default IP layer handlers successfully + * - others: other failure occurred during unregister esp_event handler + */ +esp_err_t esp_eth_clear_default_handlers(void *esp_netif); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_phy.h b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_phy.h new file mode 100644 index 00000000..9dbc2ef9 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/esp_eth_phy.h @@ -0,0 +1,305 @@ +// Copyright 2019 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. +#pragma once + +#include +#include "esp_eth_com.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_ETH_PHY_ADDR_AUTO (-1) + +/** +* @brief Ethernet PHY +* +*/ +typedef struct esp_eth_phy_s esp_eth_phy_t; + +/** +* @brief Ethernet PHY +* +*/ +struct esp_eth_phy_s { + /** + * @brief Set mediator for PHY + * + * @param[in] phy: Ethernet PHY instance + * @param[in] mediator: mediator of Ethernet driver + * + * @return + * - ESP_OK: set mediator for Ethernet PHY instance successfully + * - ESP_ERR_INVALID_ARG: set mediator for Ethernet PHY instance failed because of some invalid arguments + * + */ + esp_err_t (*set_mediator)(esp_eth_phy_t *phy, esp_eth_mediator_t *mediator); + + /** + * @brief Software Reset Ethernet PHY + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: reset Ethernet PHY successfully + * - ESP_FAIL: reset Ethernet PHY failed because some error occurred + * + */ + esp_err_t (*reset)(esp_eth_phy_t *phy); + + /** + * @brief Hardware Reset Ethernet PHY + * + * @note Hardware reset is mostly done by pull down and up PHY's nRST pin + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: reset Ethernet PHY successfully + * - ESP_FAIL: reset Ethernet PHY failed because some error occurred + * + */ + esp_err_t (*reset_hw)(esp_eth_phy_t *phy); + + /** + * @brief Initialize Ethernet PHY + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: initialize Ethernet PHY successfully + * - ESP_FAIL: initialize Ethernet PHY failed because some error occurred + * + */ + esp_err_t (*init)(esp_eth_phy_t *phy); + + /** + * @brief Deinitialize Ethernet PHY + * + * @param[in] phyL Ethernet PHY instance + * + * @return + * - ESP_OK: deinitialize Ethernet PHY successfully + * - ESP_FAIL: deinitialize Ethernet PHY failed because some error occurred + * + */ + esp_err_t (*deinit)(esp_eth_phy_t *phy); + + /** + * @brief Start auto negotiation + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: restart auto negotiation successfully + * - ESP_FAIL: restart auto negotiation failed because some error occurred + * + */ + esp_err_t (*negotiate)(esp_eth_phy_t *phy); + + /** + * @brief Get Ethernet PHY link status + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: get Ethernet PHY link status successfully + * - ESP_FAIL: get Ethernet PHY link status failed because some error occurred + * + */ + esp_err_t (*get_link)(esp_eth_phy_t *phy); + + /** + * @brief Power control of Ethernet PHY + * + * @param[in] phy: Ethernet PHY instance + * @param[in] enable: set true to power on Ethernet PHY; ser false to power off Ethernet PHY + * + * @return + * - ESP_OK: control Ethernet PHY power successfully + * - ESP_FAIL: control Ethernet PHY power failed because some error occurred + * + */ + esp_err_t (*pwrctl)(esp_eth_phy_t *phy, bool enable); + + /** + * @brief Set PHY chip address + * + * @param[in] phy: Ethernet PHY instance + * @param[in] addr: PHY chip address + * + * @return + * - ESP_OK: set Ethernet PHY address successfully + * - ESP_FAIL: set Ethernet PHY address failed because some error occurred + * + */ + esp_err_t (*set_addr)(esp_eth_phy_t *phy, uint32_t addr); + + /** + * @brief Get PHY chip address + * + * @param[in] phy: Ethernet PHY instance + * @param[out] addr: PHY chip address + * + * @return + * - ESP_OK: get Ethernet PHY address successfully + * - ESP_ERR_INVALID_ARG: get Ethernet PHY address failed because of invalid argument + * + */ + esp_err_t (*get_addr)(esp_eth_phy_t *phy, uint32_t *addr); + + /** + * @brief Advertise pause function supported by MAC layer + * + * @param[in] phy: Ethernet PHY instance + * @param[out] addr: Pause ability + * + * @return + * - ESP_OK: Advertise pause ability successfully + * - ESP_ERR_INVALID_ARG: Advertise pause ability failed because of invalid argument + * + */ + esp_err_t (*advertise_pause_ability)(esp_eth_phy_t *phy, uint32_t ability); + + /** + * @brief Free memory of Ethernet PHY instance + * + * @param[in] phy: Ethernet PHY instance + * + * @return + * - ESP_OK: free PHY instance successfully + * - ESP_FAIL: free PHY instance failed because some error occurred + * + */ + esp_err_t (*del)(esp_eth_phy_t *phy); +}; + +/** +* @brief Ethernet PHY configuration +* +*/ +typedef struct { + int32_t phy_addr; /*!< PHY address, set -1 to enable PHY address detection at initialization stage */ + uint32_t reset_timeout_ms; /*!< Reset timeout value (Unit: ms) */ + uint32_t autonego_timeout_ms; /*!< Auto-negotiation timeout value (Unit: ms) */ + int reset_gpio_num; /*!< Reset GPIO number, -1 means no hardware reset */ +} eth_phy_config_t; + +/** + * @brief Default configuration for Ethernet PHY object + * + */ +#define ETH_PHY_DEFAULT_CONFIG() \ + { \ + .phy_addr = ESP_ETH_PHY_ADDR_AUTO, \ + .reset_timeout_ms = 100, \ + .autonego_timeout_ms = 4000, \ + .reset_gpio_num = 5, \ + } + +/** +* @brief Create a PHY instance of IP101 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_ip101(const eth_phy_config_t *config); + +/** +* @brief Create a PHY instance of RTL8201 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_rtl8201(const eth_phy_config_t *config); + +/** +* @brief Create a PHY instance of LAN8720 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_lan8720(const eth_phy_config_t *config); + +/** +* @brief Create a PHY instance of DP83848 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_dp83848(const eth_phy_config_t *config); + +/** +* @brief Create a PHY instance of KSZ8041 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_ksz8041(const eth_phy_config_t *config); + +/** +* @brief Create a PHY instance of KSZ8081 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_ksz8081(const eth_phy_config_t *config); + +#if CONFIG_ETH_SPI_ETHERNET_DM9051 +/** +* @brief Create a PHY instance of DM9051 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_dm9051(const eth_phy_config_t *config); +#endif + +#if CONFIG_ETH_SPI_ETHERNET_W5500 +/** +* @brief Create a PHY instance of W5500 +* +* @param[in] config: configuration of PHY +* +* @return +* - instance: create PHY instance successfully +* - NULL: create PHY instance failed because some error occurred +*/ +esp_eth_phy_t *esp_eth_phy_new_w5500(const eth_phy_config_t *config); +#endif +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_eth/include/eth_phy_regs_struct.h b/tools/sdk/esp32c3/include/esp_eth/include/eth_phy_regs_struct.h new file mode 100644 index 00000000..e725333e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_eth/include/eth_phy_regs_struct.h @@ -0,0 +1,163 @@ +// Copyright 2019 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. +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/******************Basic PHY Registers*******************/ + +/** + * @brief BMCR(Basic Mode Control Register) + * + */ +typedef union { + struct { + uint32_t reserved : 7; /*!< Reserved */ + uint32_t collision_test : 1; /*!< Collision test */ + uint32_t duplex_mode : 1; /*!< Duplex mode:Full Duplex(1) and Half Duplex(0) */ + uint32_t restart_auto_nego : 1; /*!< Restart auto-negotiation */ + uint32_t isolate : 1; /*!< Isolate the PHY from MII except the SMI interface */ + uint32_t power_down : 1; /*!< Power off PHY except SMI interface */ + uint32_t en_auto_nego : 1; /*!< Enable auto negotiation */ + uint32_t speed_select : 1; /*!< Select speed: 100Mbps(1) and 10Mbps(0) */ + uint32_t en_loopback : 1; /*!< Enables transmit data to be routed to the receive path */ + uint32_t reset : 1; /*!< Reset PHY registers. This bit is self-clearing. */ + }; + uint32_t val; +} bmcr_reg_t; +#define ETH_PHY_BMCR_REG_ADDR (0x00) + +/** + * @brief BMSR(Basic Mode Status Register) + * + */ +typedef union { + struct { + uint32_t ext_capability : 1; /*!< Extended register capability */ + uint32_t jabber_detect : 1; /*!< Jabber condition detected */ + uint32_t link_status : 1; /*!< Link status */ + uint32_t auto_nego_ability : 1; /*!< Auto negotiation ability */ + uint32_t remote_fault : 1; /*!< Remote fault detected */ + uint32_t auto_nego_complete : 1; /*!< Auto negotiation completed */ + uint32_t mf_preamble_suppress : 1; /*!< Preamble suppression capability for management frame */ + uint32_t reserved : 1; /*!< Reserved */ + uint32_t ext_status : 1; /*!< Extended Status */ + uint32_t base100_t2_hdx : 1; /*!< 100Base-T2 Half Duplex capability */ + uint32_t base100_t2_fdx : 1; /*!< 100Base-T2 Full Duplex capability */ + uint32_t base10_t_hdx : 1; /*!< 10Base-T Half Duplex capability */ + uint32_t base10_t_fdx : 1; /*!< 10Base-T Full Duplex capability */ + uint32_t base100_tx_hdx : 1; /*!< 100Base-Tx Half Duplex capability */ + uint32_t base100_tx_fdx : 1; /*!< 100Base-Tx Full Duplex capability */ + uint32_t based100_t4 : 1; /*!< 100Base-T4 capability */ + }; + uint32_t val; +} bmsr_reg_t; +#define ETH_PHY_BMSR_REG_ADDR (0x01) + +/** + * @brief PHYIDR1(PHY Identifier Register 1) + * + */ +typedef union { + struct { + uint32_t oui_msb : 16; /*!< Organizationally Unique Identifier(OUI) most significant bits */ + }; + uint32_t val; +} phyidr1_reg_t; +#define ETH_PHY_IDR1_REG_ADDR (0x02) + +/** + * @brief PHYIDR2(PHY Identifier Register 2) + * + */ +typedef union { + struct { + uint32_t model_revision : 4; /*!< Model revision number */ + uint32_t vendor_model : 6; /*!< Vendor model number */ + uint32_t oui_lsb : 6; /*!< Organizationally Unique Identifier(OUI) least significant bits */ + }; + uint32_t val; +} phyidr2_reg_t; +#define ETH_PHY_IDR2_REG_ADDR (0x03) + +/** + * @brief ANAR(Auto-Negotiation Advertisement Register) + * + */ +typedef union { + struct { + uint32_t protocol_select : 5; /*!< Binary encoded selector supported by this PHY */ + uint32_t base10_t : 1; /*!< 10Base-T support */ + uint32_t base10_t_fd : 1; /*!< 10Base-T full duplex support */ + uint32_t base100_tx : 1; /*!< 100Base-TX support */ + uint32_t base100_tx_fd : 1; /*!< 100Base-TX full duplex support */ + uint32_t base100_t4 : 1; /*!< 100Base-T4 support */ + uint32_t symmetric_pause : 1; /*!< Symmetric pause support for full duplex links */ + uint32_t asymmetric_pause : 1; /*!< Asymmetric pause support for full duplex links */ + uint32_t reserved1 : 1; /*!< Reserved */ + uint32_t remote_fault : 1; /*!< Advertise remote fault detection capability */ + uint32_t acknowledge : 1; /*!< Link partner ability data reception acknowledged */ + uint32_t next_page : 1; /*!< Next page indication, if set, next page transfer is desired */ + }; + uint32_t val; +} anar_reg_t; +#define ETH_PHY_ANAR_REG_ADDR (0x04) + +/** + * @brief ANLPAR(Auto-Negotiation Link Partner Ability Register) + * + */ +typedef union { + struct { + uint32_t protocol_select : 5; /*!< Link Partner’s binary encoded node selector */ + uint32_t base10_t : 1; /*!< 10Base-T support */ + uint32_t base10_t_fd : 1; /*!< 10Base-T full duplex support */ + uint32_t base100_tx : 1; /*!< 100Base-TX support */ + uint32_t base100_tx_fd : 1; /*!< 100Base-TX full duplex support */ + uint32_t base100_t4 : 1; /*!< 100Base-T4 support */ + uint32_t symmetric_pause : 1; /*!< Symmetric pause supported by Link Partner */ + uint32_t asymmetric_pause : 1; /*!< Asymmetric pause supported by Link Partner */ + uint32_t reserved : 1; /*!< Reserved */ + uint32_t remote_fault : 1; /*!< Link partner is indicating a remote fault */ + uint32_t acknowledge : 1; /*!< Acknowledges from link partner */ + uint32_t next_page : 1; /*!< Next page indication */ + }; + uint32_t val; +} anlpar_reg_t; +#define ETH_PHY_ANLPAR_REG_ADDR (0x05) + +/** + * @brief ANER(Auto-Negotiate Expansion Register) + * + */ +typedef union { + struct { + uint32_t link_partner_auto_nego_able : 1; /*!< Link partner auto-negotiation ability */ + uint32_t link_page_received : 1; /*!< Link code word page has received */ + uint32_t next_page_able : 1; /*!< Next page ablility */ + uint32_t link_partner_next_page_able : 1; /*!< Link partner next page ability */ + uint32_t parallel_detection_fault : 1; /*!< Parallel detection fault */ + uint32_t reserved : 11; /*!< Reserved */ + }; + uint32_t val; +} aner_reg_t; +#define ETH_PHY_ANER_REG_ADDR (0x06) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_event/include/esp_event.h b/tools/sdk/esp32c3/include/esp_event/include/esp_event.h new file mode 100644 index 00000000..b5d7b14d --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_event/include/esp_event.h @@ -0,0 +1,522 @@ +// Copyright 2018 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. + +#ifndef ESP_EVENT_H_ +#define ESP_EVENT_H_ + +#include "esp_err.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "freertos/semphr.h" + +#include "esp_event_base.h" +#include "esp_event_legacy.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// Configuration for creating event loops +typedef struct { + int32_t queue_size; /**< size of the event loop queue */ + const char *task_name; /**< name of the event loop task; if NULL, + a dedicated task is not created for event loop*/ + UBaseType_t task_priority; /**< priority of the event loop task, ignored if task name is NULL */ + uint32_t task_stack_size; /**< stack size of the event loop task, ignored if task name is NULL */ + BaseType_t task_core_id; /**< core to which the event loop task is pinned to, + ignored if task name is NULL */ +} esp_event_loop_args_t; + +/** + * @brief Create a new event loop. + * + * @param[in] event_loop_args configuration structure for the event loop to create + * @param[out] event_loop handle to the created event loop + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for event loops list + * - ESP_FAIL: Failed to create task loop + * - Others: Fail + */ +esp_err_t esp_event_loop_create(const esp_event_loop_args_t *event_loop_args, esp_event_loop_handle_t *event_loop); + +/** + * @brief Delete an existing event loop. + * + * @param[in] event_loop event loop to delete + * + * @return + * - ESP_OK: Success + * - Others: Fail + */ +esp_err_t esp_event_loop_delete(esp_event_loop_handle_t event_loop); + +/** + * @brief Create default event loop + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for event loops list + * - ESP_FAIL: Failed to create task loop + * - Others: Fail + */ +esp_err_t esp_event_loop_create_default(void); + +/** + * @brief Delete the default event loop + * + * @return + * - ESP_OK: Success + * - Others: Fail + */ +esp_err_t esp_event_loop_delete_default(void); + +/** + * @brief Dispatch events posted to an event loop. + * + * This function is used to dispatch events posted to a loop with no dedicated task, i.e task name was set to NULL + * in event_loop_args argument during loop creation. This function includes an argument to limit the amount of time + * it runs, returning control to the caller when that time expires (or some time afterwards). There is no guarantee + * that a call to this function will exit at exactly the time of expiry. There is also no guarantee that events have + * been dispatched during the call, as the function might have spent all of the alloted time waiting on the event queue. + * Once an event has been unqueued, however, it is guaranteed to be dispatched. This guarantee contributes to not being + * able to exit exactly at time of expiry as (1) blocking on internal mutexes is necessary for dispatching the unqueued + * event, and (2) during dispatch of the unqueued event there is no way to control the time occupied by handler code + * execution. The guaranteed time of exit is therefore the alloted time + amount of time required to dispatch + * the last unqueued event. + * + * In cases where waiting on the queue times out, ESP_OK is returned and not ESP_ERR_TIMEOUT, since it is + * normal behavior. + * + * @param[in] event_loop event loop to dispatch posted events from + * @param[in] ticks_to_run number of ticks to run the loop + * + * @note encountering an unknown event that has been posted to the loop will only generate a warning, not an error. + * + * @return + * - ESP_OK: Success + * - Others: Fail + */ +esp_err_t esp_event_loop_run(esp_event_loop_handle_t event_loop, TickType_t ticks_to_run); + +/** + * @brief Register an event handler to the system event loop (legacy). + * + * @note This function is obsolete and will be deprecated soon, please use esp_event_handler_instance_register() + * instead. + * + * This function can be used to register a handler for either: (1) specific events, + * (2) all events of a certain event base, or (3) all events known by the system event loop. + * + * - specific events: specify exact event_base and event_id + * - all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id + * - all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id + * + * Registering multiple handlers to events is possible. Registering a single handler to multiple events is + * also possible. However, registering the same handler to the same event multiple times would cause the + * previous registrations to be overwritten. + * + * @param[in] event_base the base id of the event to register the handler for + * @param[in] event_id the id of the event to register the handler for + * @param[in] event_handler the handler function which gets called when the event is dispatched + * @param[in] event_handler_arg data, aside from event data, that is passed to the handler when it is called + * + * @note the event loop library does not maintain a copy of event_handler_arg, therefore the user should + * ensure that event_handler_arg still points to a valid location by the time the handler gets called + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for the handler + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_handler_register(esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler, + void *event_handler_arg); + +/** + * @brief Register an event handler to a specific loop (legacy). + * + * @note This function is obsolete and will be deprecated soon, please use esp_event_handler_instance_register_with() + * instead. + * + * This function behaves in the same manner as esp_event_handler_register, except the additional + * specification of the event loop to register the handler to. + * + * @param[in] event_loop the event loop to register this handler function to + * @param[in] event_base the base id of the event to register the handler for + * @param[in] event_id the id of the event to register the handler for + * @param[in] event_handler the handler function which gets called when the event is dispatched + * @param[in] event_handler_arg data, aside from event data, that is passed to the handler when it is called + * + * @note the event loop library does not maintain a copy of event_handler_arg, therefore the user should + * ensure that event_handler_arg still points to a valid location by the time the handler gets called + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for the handler + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_handler_register_with(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler, + void *event_handler_arg); + +/** + * @brief Register an instance of event handler to a specific loop. + * + * This function can be used to register a handler for either: (1) specific events, + * (2) all events of a certain event base, or (3) all events known by the system event loop. + * + * - specific events: specify exact event_base and event_id + * - all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id + * - all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id + * + * Besides the error, the function returns an instance object as output parameter to identify each registration. + * This is necessary to remove (unregister) the registration before the event loop is deleted. + * + * Registering multiple handlers to events, registering a single handler to multiple events as well as registering + * the same handler to the same event multiple times is possible. + * Each registration yields a distinct instance object which identifies it over the registration + * lifetime. + * + * @param[in] event_loop the event loop to register this handler function to + * @param[in] event_base the base id of the event to register the handler for + * @param[in] event_id the id of the event to register the handler for + * @param[in] event_handler the handler function which gets called when the event is dispatched + * @param[in] event_handler_arg data, aside from event data, that is passed to the handler when it is called + * @param[out] instance An event handler instance object related to the registered event handler and data, can be NULL. + * This needs to be kept if the specific callback instance should be unregistered before deleting the whole + * event loop. Registering the same event handler multiple times is possible and yields distinct instance + * objects. The data can be the same for all registrations. + * If no unregistration is needed but the handler should be deleted when the event loop is deleted, + * instance can be NULL. + * + * @note the event loop library does not maintain a copy of event_handler_arg, therefore the user should + * ensure that event_handler_arg still points to a valid location by the time the handler gets called + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for the handler + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id or instance is NULL + * - Others: Fail + */ +esp_err_t esp_event_handler_instance_register_with(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler, + void *event_handler_arg, + esp_event_handler_instance_t *instance); + +/** + * @brief Register an instance of event handler to the default loop. + * + * This function does the same as esp_event_handler_instance_register_with, except that it registers the + * handler to the default event loop. + * + * @param[in] event_base the base id of the event to register the handler for + * @param[in] event_id the id of the event to register the handler for + * @param[in] event_handler the handler function which gets called when the event is dispatched + * @param[in] event_handler_arg data, aside from event data, that is passed to the handler when it is called + * @param[out] instance An event handler instance object related to the registered event handler and data, can be NULL. + * This needs to be kept if the specific callback instance should be unregistered before deleting the whole + * event loop. Registering the same event handler multiple times is possible and yields distinct instance + * objects. The data can be the same for all registrations. + * If no unregistration is needed but the handler should be deleted when the event loop is deleted, + * instance can be NULL. + * + * @note the event loop library does not maintain a copy of event_handler_arg, therefore the user should + * ensure that event_handler_arg still points to a valid location by the time the handler gets called + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for the handler + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id or instance is NULL + * - Others: Fail + */ +esp_err_t esp_event_handler_instance_register(esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler, + void *event_handler_arg, + esp_event_handler_instance_t *instance); + +/** + * @brief Unregister a handler with the system event loop (legacy). + * + * @note This function is obsolete and will be deprecated soon, please use esp_event_handler_instance_unregister() + * instead. + * + * This function can be used to unregister a handler so that it no longer gets called during dispatch. + * Handlers can be unregistered for either: (1) specific events, (2) all events of a certain event base, + * or (3) all events known by the system event loop + * + * - specific events: specify exact event_base and event_id + * - all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id + * - all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id + * + * This function ignores unregistration of handlers that has not been previously registered. + * + * @param[in] event_base the base of the event with which to unregister the handler + * @param[in] event_id the id of the event with which to unregister the handler + * @param[in] event_handler the handler to unregister + * + * @return ESP_OK success + * @return ESP_ERR_INVALID_ARG invalid combination of event base and event id + * @return others fail + */ +esp_err_t esp_event_handler_unregister(esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler); + +/** + * @brief Unregister a handler from a specific event loop (legacy). + * + * @note This function is obsolete and will be deprecated soon, please use esp_event_handler_instance_unregister_with() + * instead. + * + * This function behaves in the same manner as esp_event_handler_unregister, except the additional specification of + * the event loop to unregister the handler with. + * + * @param[in] event_loop the event loop with which to unregister this handler function + * @param[in] event_base the base of the event with which to unregister the handler + * @param[in] event_id the id of the event with which to unregister the handler + * @param[in] event_handler the handler to unregister + * + * @return + * - ESP_OK: Success + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_handler_unregister_with(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_t event_handler); + +/** + * @brief Unregister a handler instance from a specific event loop. + * + * This function can be used to unregister a handler so that it no longer gets called during dispatch. + * Handlers can be unregistered for either: (1) specific events, (2) all events of a certain event base, + * or (3) all events known by the system event loop + * + * - specific events: specify exact event_base and event_id + * - all events of a certain base: specify exact event_base and use ESP_EVENT_ANY_ID as the event_id + * - all events known by the loop: use ESP_EVENT_ANY_BASE for event_base and ESP_EVENT_ANY_ID as the event_id + * + * This function ignores unregistration of handler instances that have not been previously registered. + * + * @param[in] event_loop the event loop with which to unregister this handler function + * @param[in] event_base the base of the event with which to unregister the handler + * @param[in] event_id the id of the event with which to unregister the handler + * @param[in] instance the instance object of the registration to be unregistered + * + * @return + * - ESP_OK: Success + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_handler_instance_unregister_with(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_instance_t instance); + +/** + * @brief Unregister a handler from the system event loop. + * + * This function does the same as esp_event_handler_instance_unregister_with, except that it unregisters the + * handler instance from the default event loop. + * + * @param[in] event_base the base of the event with which to unregister the handler + * @param[in] event_id the id of the event with which to unregister the handler + * @param[in] instance the instance object of the registration to be unregistered + * + * @return + * - ESP_OK: Success + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_handler_instance_unregister(esp_event_base_t event_base, + int32_t event_id, + esp_event_handler_instance_t instance); + +/** + * @brief Posts an event to the system default event loop. The event loop library keeps a copy of event_data and manages + * the copy's lifetime automatically (allocation + deletion); this ensures that the data the + * handler recieves is always valid. + * + * @param[in] event_base the event base that identifies the event + * @param[in] event_id the event id that identifies the event + * @param[in] event_data the data, specific to the event occurence, that gets passed to the handler + * @param[in] event_data_size the size of the event data + * @param[in] ticks_to_wait number of ticks to block on a full event queue + * + * @return + * - ESP_OK: Success + * - ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, + * queue full when posting from ISR + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_post(esp_event_base_t event_base, + int32_t event_id, + void *event_data, + size_t event_data_size, + TickType_t ticks_to_wait); + +/** + * @brief Posts an event to the specified event loop. The event loop library keeps a copy of event_data and manages + * the copy's lifetime automatically (allocation + deletion); this ensures that the data the + * handler recieves is always valid. + * + * This function behaves in the same manner as esp_event_post_to, except the additional specification of the event loop + * to post the event to. + * + * @param[in] event_loop the event loop to post to + * @param[in] event_base the event base that identifies the event + * @param[in] event_id the event id that identifies the event + * @param[in] event_data the data, specific to the event occurence, that gets passed to the handler + * @param[in] event_data_size the size of the event data + * @param[in] ticks_to_wait number of ticks to block on a full event queue + * + * @return + * - ESP_OK: Success + * - ESP_ERR_TIMEOUT: Time to wait for event queue to unblock expired, + * queue full when posting from ISR + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id + * - Others: Fail + */ +esp_err_t esp_event_post_to(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + void *event_data, + size_t event_data_size, + TickType_t ticks_to_wait); + +#if CONFIG_ESP_EVENT_POST_FROM_ISR +/** + * @brief Special variant of esp_event_post for posting events from interrupt handlers. + * + * @param[in] event_base the event base that identifies the event + * @param[in] event_id the event id that identifies the event + * @param[in] event_data the data, specific to the event occurence, that gets passed to the handler + * @param[in] event_data_size the size of the event data; max is 4 bytes + * @param[out] task_unblocked an optional parameter (can be NULL) which indicates that an event task with + * higher priority than currently running task has been unblocked by the posted event; + * a context switch should be requested before the interrupt is existed. + * + * @note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled + * @note when this function is called from an interrupt handler placed in IRAM, this function should + * be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR + * + * @return + * - ESP_OK: Success + * - ESP_FAIL: Event queue for the default event loop full + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id, + * data size of more than 4 bytes + * - Others: Fail + */ +esp_err_t esp_event_isr_post(esp_event_base_t event_base, + int32_t event_id, + void *event_data, + size_t event_data_size, + BaseType_t *task_unblocked); + +/** + * @brief Special variant of esp_event_post_to for posting events from interrupt handlers + * + * @param[in] event_loop the event loop to post to + * @param[in] event_base the event base that identifies the event + * @param[in] event_id the event id that identifies the event + * @param[in] event_data the data, specific to the event occurence, that gets passed to the handler + * @param[in] event_data_size the size of the event data + * @param[out] task_unblocked an optional parameter (can be NULL) which indicates that an event task with + * higher priority than currently running task has been unblocked by the posted event; + * a context switch should be requested before the interrupt is existed. + * + * @note this function is only available when CONFIG_ESP_EVENT_POST_FROM_ISR is enabled + * @note when this function is called from an interrupt handler placed in IRAM, this function should + * be placed in IRAM as well by enabling CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR + * + * @return + * - ESP_OK: Success + * - ESP_FAIL: Event queue for the loop full + * - ESP_ERR_INVALID_ARG: Invalid combination of event base and event id, + * data size of more than 4 bytes + * - Others: Fail + */ +esp_err_t esp_event_isr_post_to(esp_event_loop_handle_t event_loop, + esp_event_base_t event_base, + int32_t event_id, + void *event_data, + size_t event_data_size, + BaseType_t *task_unblocked); +#endif + +/** + * @brief Dumps statistics of all event loops. + * + * Dumps event loop info in the format: + * + @verbatim + event loop + handler + handler + ... + event loop + handler + handler + ... + + where: + + event loop + format: address,name rx:total_recieved dr:total_dropped + where: + address - memory address of the event loop + name - name of the event loop, 'none' if no dedicated task + total_recieved - number of successfully posted events + total_dropped - number of events unsuccessfully posted due to queue being full + + handler + format: address ev:base,id inv:total_invoked run:total_runtime + where: + address - address of the handler function + base,id - the event specified by event base and id this handler executes + total_invoked - number of times this handler has been invoked + total_runtime - total amount of time used for invoking this handler + + @endverbatim + * + * @param[in] file the file stream to output to + * + * @note this function is a noop when CONFIG_ESP_EVENT_LOOP_PROFILING is disabled + * + * @return + * - ESP_OK: Success + * - ESP_ERR_NO_MEM: Cannot allocate memory for event loops list + * - Others: Fail + */ +esp_err_t esp_event_dump(FILE *file); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // #ifndef ESP_EVENT_H_ diff --git a/tools/sdk/esp32c3/include/esp_event/include/esp_event_base.h b/tools/sdk/esp32c3/include/esp_event/include/esp_event_base.h new file mode 100644 index 00000000..fc5a1deb --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_event/include/esp_event_base.h @@ -0,0 +1,43 @@ +// Copyright 2018 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. + +#ifndef ESP_EVENT_BASE_H_ +#define ESP_EVENT_BASE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// Defines for declaring and defining event base +#define ESP_EVENT_DECLARE_BASE(id) extern esp_event_base_t id +#define ESP_EVENT_DEFINE_BASE(id) esp_event_base_t id = #id + +// Event loop library types +typedef const char* esp_event_base_t; /**< unique pointer to a subsystem that exposes events */ +typedef void* esp_event_loop_handle_t; /**< a number that identifies an event with respect to a base */ +typedef void (*esp_event_handler_t)(void* event_handler_arg, + esp_event_base_t event_base, + int32_t event_id, + void* event_data); /**< function called when an event is posted to the queue */ +typedef void* esp_event_handler_instance_t; /**< context identifying an instance of a registered event handler */ + +// Defines for registering/unregistering event handlers +#define ESP_EVENT_ANY_BASE NULL /**< register handler for any event base */ +#define ESP_EVENT_ANY_ID -1 /**< register handler for any event id */ + +#ifdef __cplusplus +} +#endif + +#endif // #ifndef ESP_EVENT_BASE_H_ diff --git a/tools/sdk/esp32c3/include/esp_event/include/esp_event_legacy.h b/tools/sdk/esp32c3/include/esp_event/include/esp_event_legacy.h new file mode 100644 index 00000000..021ac407 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_event/include/esp_event_legacy.h @@ -0,0 +1,260 @@ +// Copyright 2015-2018 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. + +#pragma once + +#include +#include + +#include "esp_err.h" +#include "esp_wifi_types.h" +#include "esp_netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** System event types enumeration */ +typedef enum { + SYSTEM_EVENT_WIFI_READY = 0, /*!< ESP32 WiFi ready */ + SYSTEM_EVENT_SCAN_DONE, /*!< ESP32 finish scanning AP */ + SYSTEM_EVENT_STA_START, /*!< ESP32 station start */ + SYSTEM_EVENT_STA_STOP, /*!< ESP32 station stop */ + SYSTEM_EVENT_STA_CONNECTED, /*!< ESP32 station connected to AP */ + SYSTEM_EVENT_STA_DISCONNECTED, /*!< ESP32 station disconnected from AP */ + SYSTEM_EVENT_STA_AUTHMODE_CHANGE, /*!< the auth mode of AP connected by ESP32 station changed */ + SYSTEM_EVENT_STA_GOT_IP, /*!< ESP32 station got IP from connected AP */ + SYSTEM_EVENT_STA_LOST_IP, /*!< ESP32 station lost IP and the IP is reset to 0 */ + SYSTEM_EVENT_STA_BSS_RSSI_LOW, /*!< ESP32 station connected BSS rssi goes below threshold */ + SYSTEM_EVENT_STA_WPS_ER_SUCCESS, /*!< ESP32 station wps succeeds in enrollee mode */ + SYSTEM_EVENT_STA_WPS_ER_FAILED, /*!< ESP32 station wps fails in enrollee mode */ + SYSTEM_EVENT_STA_WPS_ER_TIMEOUT, /*!< ESP32 station wps timeout in enrollee mode */ + SYSTEM_EVENT_STA_WPS_ER_PIN, /*!< ESP32 station wps pin code in enrollee mode */ + SYSTEM_EVENT_STA_WPS_ER_PBC_OVERLAP, /*!< ESP32 station wps overlap in enrollee mode */ + SYSTEM_EVENT_AP_START, /*!< ESP32 soft-AP start */ + SYSTEM_EVENT_AP_STOP, /*!< ESP32 soft-AP stop */ + SYSTEM_EVENT_AP_STACONNECTED, /*!< a station connected to ESP32 soft-AP */ + SYSTEM_EVENT_AP_STADISCONNECTED, /*!< a station disconnected from ESP32 soft-AP */ + SYSTEM_EVENT_AP_STAIPASSIGNED, /*!< ESP32 soft-AP assign an IP to a connected station */ + SYSTEM_EVENT_AP_PROBEREQRECVED, /*!< Receive probe request packet in soft-AP interface */ + SYSTEM_EVENT_ACTION_TX_STATUS, /*!< Receive status of Action frame transmitted */ + SYSTEM_EVENT_ROC_DONE, /*!< Indicates the completion of Remain-on-Channel operation status */ + SYSTEM_EVENT_STA_BEACON_TIMEOUT, /*!< ESP32 station beacon timeout */ + SYSTEM_EVENT_FTM_REPORT, /*!< Receive report of FTM procedure */ + SYSTEM_EVENT_GOT_IP6, /*!< ESP32 station or ap or ethernet interface v6IP addr is preferred */ + SYSTEM_EVENT_ETH_START, /*!< ESP32 ethernet start */ + SYSTEM_EVENT_ETH_STOP, /*!< ESP32 ethernet stop */ + SYSTEM_EVENT_ETH_CONNECTED, /*!< ESP32 ethernet phy link up */ + SYSTEM_EVENT_ETH_DISCONNECTED, /*!< ESP32 ethernet phy link down */ + SYSTEM_EVENT_ETH_GOT_IP, /*!< ESP32 ethernet got IP from connected AP */ + SYSTEM_EVENT_MAX /*!< Number of members in this enum */ +} system_event_id_t; + +/* add this macro define for compatible with old IDF version */ +#ifndef SYSTEM_EVENT_AP_STA_GOT_IP6 +#define SYSTEM_EVENT_AP_STA_GOT_IP6 SYSTEM_EVENT_GOT_IP6 +#endif + + +/** Argument structure of SYSTEM_EVENT_STA_WPS_ER_FAILED event */ +typedef wifi_event_sta_wps_fail_reason_t system_event_sta_wps_fail_reason_t; + +/** Argument structure of SYSTEM_EVENT_SCAN_DONE event */ +typedef wifi_event_sta_scan_done_t system_event_sta_scan_done_t; + +/** Argument structure of SYSTEM_EVENT_STA_CONNECTED event */ +typedef wifi_event_sta_connected_t system_event_sta_connected_t; + +/** Argument structure of SYSTEM_EVENT_STA_DISCONNECTED event */ +typedef wifi_event_sta_disconnected_t system_event_sta_disconnected_t; + +/** Argument structure of SYSTEM_EVENT_STA_AUTHMODE_CHANGE event */ +typedef wifi_event_sta_authmode_change_t system_event_sta_authmode_change_t; + +/** Argument structure of SYSTEM_EVENT_STA_WPS_ER_PIN event */ +typedef wifi_event_sta_wps_er_pin_t system_event_sta_wps_er_pin_t; + +/** Argument structure of SYSTEM_EVENT_STA_WPS_ER_PIN event */ +typedef wifi_event_sta_wps_er_success_t system_event_sta_wps_er_success_t; + +/** Argument structure of event */ +typedef wifi_event_ap_staconnected_t system_event_ap_staconnected_t; + +/** Argument structure of event */ +typedef wifi_event_ap_stadisconnected_t system_event_ap_stadisconnected_t; + +/** Argument structure of event */ +typedef wifi_event_ap_probe_req_rx_t system_event_ap_probe_req_rx_t; + +/** Argument structure of SYSTEM_EVENT_FTM_REPORT event */ +typedef wifi_event_ftm_report_t system_event_ftm_report_t; + +/** Argument structure of event */ +typedef ip_event_ap_staipassigned_t system_event_ap_staipassigned_t; + +/** Argument structure of event */ +typedef ip_event_got_ip_t system_event_sta_got_ip_t; + +/** Argument structure of event */ +typedef ip_event_got_ip6_t system_event_got_ip6_t; + +/** Union of all possible system_event argument structures */ +typedef union { + system_event_sta_connected_t connected; /*!< ESP32 station connected to AP */ + system_event_sta_disconnected_t disconnected; /*!< ESP32 station disconnected to AP */ + system_event_sta_scan_done_t scan_done; /*!< ESP32 station scan (APs) done */ + system_event_sta_authmode_change_t auth_change; /*!< the auth mode of AP ESP32 station connected to changed */ + system_event_sta_got_ip_t got_ip; /*!< ESP32 station got IP, first time got IP or when IP is changed */ + system_event_sta_wps_er_pin_t sta_er_pin; /*!< ESP32 station WPS enrollee mode PIN code received */ + system_event_sta_wps_fail_reason_t sta_er_fail_reason; /*!< ESP32 station WPS enrollee mode failed reason code received */ + system_event_sta_wps_er_success_t sta_er_success; /*!< ESP32 station WPS enrollee success */ + system_event_ap_staconnected_t sta_connected; /*!< a station connected to ESP32 soft-AP */ + system_event_ap_stadisconnected_t sta_disconnected; /*!< a station disconnected to ESP32 soft-AP */ + system_event_ap_probe_req_rx_t ap_probereqrecved; /*!< ESP32 soft-AP receive probe request packet */ + system_event_ftm_report_t ftm_report; /*!< Report of FTM procedure */ + system_event_ap_staipassigned_t ap_staipassigned; /**< ESP32 soft-AP assign an IP to the station*/ + system_event_got_ip6_t got_ip6; /*!< ESP32 station or ap or ethernet ipv6 addr state change to preferred */ +} system_event_info_t; + +/** Event, as a tagged enum */ +typedef struct { + system_event_id_t event_id; /*!< event ID */ + system_event_info_t event_info; /*!< event information */ +} system_event_t; + +/** Event handler function type */ +typedef esp_err_t (*system_event_handler_t)(esp_event_base_t event_base, + int32_t event_id, + void* event_data, + size_t event_data_size, + TickType_t ticks_to_wait); + +/** + * @brief Send a event to event task + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + * Other task/modules, such as the tcpip_adapter, can call this API to send an event to event task + * + * @param event Event to send + * + * @return ESP_OK : succeed + * @return others : fail + */ +esp_err_t esp_event_send(system_event_t *event) __attribute__ ((deprecated)); + +/** + * @brief Send a event to event task + * + * @note This API is used by WiFi Driver only. + * + * Other task/modules, such as the tcpip_adapter, can call this API to send an event to event task + * + * @param[in] event_base the event base that identifies the event + * @param[in] event_id the event id that identifies the event + * @param[in] event_data the data, specific to the event occurence, that gets passed to the handler + * @param[in] event_data_size the size of the event data + * @param[in] ticks_to_wait number of ticks to block on a full event queue + * + * @return ESP_OK : succeed + * @return others : fail + */ +esp_err_t esp_event_send_internal(esp_event_base_t event_base, + int32_t event_id, + void* event_data, + size_t event_data_size, + TickType_t ticks_to_wait); + +/** + * @brief Default event handler for system events + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + * This function performs default handling of system events. + * When using esp_event_loop APIs, it is called automatically before invoking the user-provided + * callback function. + * + * Applications which implement a custom event loop must call this function + * as part of event processing. + * + * @param event pointer to event to be handled + * @return ESP_OK if an event was handled successfully + */ +esp_err_t esp_event_process_default(system_event_t *event) __attribute__ ((deprecated)); + +/** + * @brief Install default event handlers for Ethernet interface + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + */ +void esp_event_set_default_eth_handlers(void); + +/** + * @brief Install default event handlers for Wi-Fi interfaces (station and AP) + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + */ +void esp_event_set_default_wifi_handlers(void) __attribute__ ((deprecated)); + +/** + * @brief Application specified event callback function + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + * + * @param ctx reserved for user + * @param event event type defined in this file + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +typedef esp_err_t (*system_event_cb_t)(void *ctx, system_event_t *event); + +/** + * @brief Initialize event loop + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + * Create the event handler and task + * + * @param cb application specified event callback, it can be modified by call esp_event_set_cb + * @param ctx reserved for user + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_event_loop_init(system_event_cb_t cb, void *ctx) __attribute__ ((deprecated)); + +/** + * @brief Set application specified event callback function + * + * @note This API is part of the legacy event system. New code should use event library API in esp_event.h + * + * @attention 1. If cb is NULL, means application don't need to handle + * If cb is not NULL, it will be call when an event is received, after the default event callback is completed + * + * @param cb application callback function + * @param ctx argument to be passed to callback + * + * + * @return old callback + */ +system_event_cb_t esp_event_loop_set_cb(system_event_cb_t cb, void *ctx) __attribute__ ((deprecated)); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_event/include/esp_event_loop.h b/tools/sdk/esp32c3/include/esp_event/include/esp_event_loop.h new file mode 100644 index 00000000..14ab627e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_event/include/esp_event_loop.h @@ -0,0 +1,3 @@ +#pragma once +#warning "esp_event_loop.h is deprecated, please include esp_event.h instead" +#include "esp_event.h" diff --git a/tools/sdk/esp32c3/include/esp_gdbstub/esp32c3/gdbstub_target_config.h b/tools/sdk/esp32c3/include/esp_gdbstub/esp32c3/gdbstub_target_config.h new file mode 100644 index 00000000..527dc5e2 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_gdbstub/esp32c3/gdbstub_target_config.h @@ -0,0 +1,15 @@ +// Copyright 2020 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. + +#pragma once diff --git a/tools/sdk/esp32c3/include/esp_gdbstub/include/esp_gdbstub.h b/tools/sdk/esp32c3/include/esp_gdbstub/include/esp_gdbstub.h new file mode 100644 index 00000000..02fda63e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_gdbstub/include/esp_gdbstub.h @@ -0,0 +1,27 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "esp_gdbstub_arch.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void esp_gdbstub_panic_handler(esp_gdbstub_frame_t *frame) __attribute__((noreturn)); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_gdbstub/riscv/esp_gdbstub_arch.h b/tools/sdk/esp32c3/include/esp_gdbstub/riscv/esp_gdbstub_arch.h new file mode 100644 index 00000000..d7c3aca0 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_gdbstub/riscv/esp_gdbstub_arch.h @@ -0,0 +1,34 @@ +// Copyright 2015-2019 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. + +#pragma once +#include +#include "riscv/rvruntime-frames.h" +#include "gdbstub_target_config.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef RvExcFrame esp_gdbstub_frame_t; + +/* GDB regfile structure, configuration dependent */ +typedef struct { + uint32_t x[32]; + uint32_t pc; +} esp_gdbstub_gdb_regfile_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hid_common.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hid_common.h new file mode 100644 index 00000000..9fd7a2c6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hid_common.h @@ -0,0 +1,257 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +/* HID Report Map Values */ +#define HID_RM_INPUT 0x80 +#define HID_RM_OUTPUT 0x90 +#define HID_RM_FEATURE 0xb0 +#define HID_RM_COLLECTION 0xa0 +#define HID_RM_END_COLLECTION 0xc0 +#define HID_RM_USAGE_PAGE 0x04 +#define HID_RM_LOGICAL_MINIMUM 0x14 +#define HID_RM_LOGICAL_MAXIMUM 0x24 +#define HID_RM_PHYSICAL_MINIMUM 0x34 +#define HID_RM_PHYSICAL_MAXIMUM 0x44 +#define HID_RM_UNIT_EXPONENT 0x54 +#define HID_RM_UNIT 0x64 +#define HID_RM_REPORT_SIZE 0x74 +#define HID_RM_REPORT_ID 0x84 +#define HID_RM_REPORT_COUNT 0x94 +#define HID_RM_PUSH 0xa4 +#define HID_RM_POP 0xb4 +#define HID_RM_USAGE 0x08 +#define HID_RM_USAGE_MINIMUM 0x18 +#define HID_RM_USAGE_MAXIMUM 0x28 +#define HID_RM_DESIGNATOR_INDEX 0x38 +#define HID_RM_DESIGNATOR_MINIMUM 0x48 +#define HID_RM_DESIGNATOR_MAXIMUM 0x58 +#define HID_RM_STRING_INDEX 0x78 +#define HID_RM_STRING_MINIMUM 0x88 +#define HID_RM_STRING_MAXIMUM 0x98 +#define HID_RM_DELIMITER 0xa8 + +/* HID Usage Pages and Usages */ +#define HID_USAGE_PAGE_GENERIC_DESKTOP 0x01 +#define HID_USAGE_KEYBOARD 0x06 +#define HID_USAGE_MOUSE 0x02 +#define HID_USAGE_JOYSTICK 0x04 +#define HID_USAGE_GAMEPAD 0x05 + +#define HID_USAGE_PAGE_CONSUMER_DEVICE 0x0C +#define HID_USAGE_CONSUMER_CONTROL 0x01 + +/* HID BT COD Peripheral Min Values Main Role */ +#define ESP_HID_COD_MIN_KEYBOARD 0x10 +#define ESP_HID_COD_MIN_MOUSE 0x20 + +/* HID BLE Appearances */ +#define ESP_HID_APPEARANCE_GENERIC 0x03C0 +#define ESP_HID_APPEARANCE_KEYBOARD 0x03C1 +#define ESP_HID_APPEARANCE_MOUSE 0x03C2 +#define ESP_HID_APPEARANCE_JOYSTICK 0x03C3 +#define ESP_HID_APPEARANCE_GAMEPAD 0x03C4 + +/* HID Report Types */ +#define ESP_HID_REPORT_TYPE_INPUT 1 +#define ESP_HID_REPORT_TYPE_OUTPUT 2 +#define ESP_HID_REPORT_TYPE_FEATURE 3 + +/* HID Protocol Modes */ +#define ESP_HID_PROTOCOL_MODE_BOOT 0x00 // Boot Protocol Mode +#define ESP_HID_PROTOCOL_MODE_REPORT 0x01 // Report Protocol Mode + +/* HID information flags */ +#define ESP_HID_FLAGS_REMOTE_WAKE 0x01 // RemoteWake +#define ESP_HID_FLAGS_NORMALLY_CONNECTABLE 0x02 // NormallyConnectable + +/* Control point commands */ +#define ESP_HID_CONTROL_SUSPEND 0x00 // Suspend +#define ESP_HID_CONTROL_EXIT_SUSPEND 0x01 // Exit Suspend + +/* Client Characteristic Configuration values */ +#define ESP_HID_CCC_NOTIFICATIONS_ENABLED 0x01 // Notifications enabled +#define ESP_HID_CCC_INDICATIONS_ENABLED 0x02 // Indications enabled + +/* HID Transports */ +typedef enum { + ESP_HID_TRANSPORT_BT, + ESP_HID_TRANSPORT_BLE, + ESP_HID_TRANSPORT_USB, + ESP_HID_TRANSPORT_MAX +} esp_hid_transport_t; + +/* HID Usage Types */ +typedef enum { + ESP_HID_USAGE_GENERIC = 0, + ESP_HID_USAGE_KEYBOARD = 1, + ESP_HID_USAGE_MOUSE = 2, + ESP_HID_USAGE_JOYSTICK = 4, + ESP_HID_USAGE_GAMEPAD = 8, + ESP_HID_USAGE_TABLET = 16, + ESP_HID_USAGE_CCONTROL = 32, + ESP_HID_USAGE_VENDOR = 64 +} esp_hid_usage_t; + +/* HID BT COD Peripheral Min Values. Mask of (keyboard|mouse|ESP_HIDH_COD_*) */ +typedef enum { + ESP_HID_COD_MIN_GENERIC, + ESP_HID_COD_MIN_JOYSTICK, + ESP_HID_COD_MIN_GAMEPAD, + ESP_HID_COD_MIN_REMOTE, + ESP_HID_COD_MIN_SENSOR, + ESP_HID_COD_MIN_TABLET, + ESP_HID_COD_MIN_CARD_READER, + ESP_HID_COD_MIN_MAX +} esp_hid_cod_min_t; + +/** + * @brief HID report item structure + */ +typedef struct { + uint8_t map_index; /*!< HID report map index */ + uint8_t report_id; /*!< HID report id */ + uint8_t report_type; /*!< HID report type */ + uint8_t protocol_mode; /*!< HID protocol mode */ + esp_hid_usage_t usage; /*!< HID usage type */ + uint16_t value_len; /*!< HID report length in bytes */ +} esp_hid_report_item_t; + +/** + * @brief HID parsed report map structure + */ +typedef struct { + esp_hid_usage_t usage; /*!< Dominant HID usage. (keyboard > mouse > joystick > gamepad > generic) */ + uint16_t appearance; /*!< Calculated HID Appearance based on the dominant usage */ + uint8_t reports_len; /*!< Number of reports discovered in the report map */ + esp_hid_report_item_t *reports; /*!< Reports discovered in the report map */ +} esp_hid_report_map_t; + +/** + * @brief HID raw report map structure + */ +typedef struct { + const uint8_t *data; /*!< Pointer to the HID report map data */ + uint16_t len; /*!< HID report map data length */ +} esp_hid_raw_report_map_t; + +/** + * @brief HID device config structure + */ +typedef struct { + uint16_t vendor_id; /*!< HID Vendor ID */ + uint16_t product_id; /*!< HID Product ID */ + uint16_t version; /*!< HID Product Version */ + const char *device_name; /*!< HID Device Name */ + const char *manufacturer_name; /*!< HID Manufacturer */ + const char *serial_number; /*!< HID Serial Number */ + esp_hid_raw_report_map_t *report_maps; /*!< Array of the raw HID report maps */ + uint8_t report_maps_len; /*!< number of raw report maps in the array */ +} esp_hid_device_config_t; + +/* + * @brief Parse RAW HID report map + * It is a responsibility of the user to free the parsed report map, + * when it's no longer needed. Use esp_hid_free_report_map + * @param hid_rm : pointer to the hid report map data + * @param hid_rm_len : length to the hid report map data + * + * @return: pointer to the parsed report map + */ +esp_hid_report_map_t *esp_hid_parse_report_map(const uint8_t *hid_rm, size_t hid_rm_len); + +/* + * @brief Free parsed HID report map + * @param map : pointer to the parsed hid report map + */ +void esp_hid_free_report_map(esp_hid_report_map_t *map); + +/** + * @brief Calculate the HID Device usage type from the BLE Apperance + * @param appearance : BLE Apperance value + * + * @return: the hid usage type + */ +esp_hid_usage_t esp_hid_usage_from_appearance(uint16_t appearance); + +/** + * @brief Calculate the HID Device usage type from the BT CoD + * @param cod : BT CoD value + * + * @return: the hid usage type + */ +esp_hid_usage_t esp_hid_usage_from_cod(uint32_t cod); + +/** + * @brief Convert device usage type to string + * @param usage : The HID usage type to convert + * + * @return: a pointer to the string or NULL + */ +const char *esp_hid_usage_str(esp_hid_usage_t usage); + +/** + * @brief Convert HID protocol mode to string + * @param protocol_mode : The HID protocol mode to convert + * BOOT/REPORT + * + * @return: a pointer to the string or NULL + */ +const char *esp_hid_protocol_mode_str(uint8_t protocol_mode); + +/** + * @brief Convert HID report type to string + * @param report_type : The HID report type to convert + * INPUT/OUTPUT/FEATURE + * + * @return: a pointer to the string or NULL + */ +const char *esp_hid_report_type_str(uint8_t report_type); + +/** + * @brief Convert BT CoD major to string + * @param cod_major : The CoD major value to convert + * + * @return: a pointer to the string or NULL + */ +const char *esp_hid_cod_major_str(uint8_t cod_major); + +/** + * @brief Print BT CoD minor value + * @param cod_min : The CoD minor value to print + * @param fp : pointer to the output file + */ +void esp_hid_cod_minor_print(uint8_t cod_min, FILE *fp); + +/** + * @brief Convert BLE disconnect reason to string + * @param reason : The value of the reason + * + * @return: a pointer to the string or NULL + */ +const char *esp_hid_disconnect_reason_str(esp_hid_transport_t transport, int reason); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd.h new file mode 100644 index 00000000..ef596c6b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd.h @@ -0,0 +1,206 @@ +// Copyright 2017-2019 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. + +#pragma once + +#include "sdkconfig.h" +#include "esp_err.h" +#include "esp_event.h" +#include "esp_hid_common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_hidd_transport.h" + +ESP_EVENT_DECLARE_BASE(ESP_HIDD_EVENTS); // Declare the event base for HID device + +/** + * @brief HIDD callback events enum + */ +typedef enum { + ESP_HIDD_ANY_EVENT = ESP_EVENT_ANY_ID, /*!< HID device any event */ + ESP_HIDD_START_EVENT = 0, /*!< HID device stack started */ + ESP_HIDD_CONNECT_EVENT, /*!< HID device connected */ + ESP_HIDD_PROTOCOL_MODE_EVENT, /*!< HID device protocol mode change */ + ESP_HIDD_CONTROL_EVENT, /*!< HID device control request */ + ESP_HIDD_OUTPUT_EVENT, /*!< HID device output report event */ + ESP_HIDD_FEATURE_EVENT, /*!< HID device feature report event */ + ESP_HIDD_DISCONNECT_EVENT, /*!< HID device disconnected */ + ESP_HIDD_STOP_EVENT, /*!< HID device stack stopped */ + ESP_HIDD_MAX_EVENT, /*!< HID events end marker */ +} esp_hidd_event_t; + +/** + * @brief HIDD structure forward declaration + */ +struct esp_hidd_dev_s; +typedef struct esp_hidd_dev_s esp_hidd_dev_t; + +/** + * @brief HIDD callback parameters union + */ +typedef union { + /** + * @brief ESP_HIDD_CONNECT_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + } connect; /*!< HID callback param of ESP_HIDD_CONNECT_EVENT */ + + /** + * @brief ESP_HIDD_DISCONNECT_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + int reason; /*!< Indicate the reason of disconnection */ + } disconnect; /*!< HID callback param of ESP_HIDD_DISCONNECT_EVENT */ + + /** + * @brief ESP_HIDD_OUTPUT_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + esp_hid_usage_t usage; /*!< HID report usage */ + uint16_t report_id; /*!< HID report index */ + uint16_t length; /*!< data length */ + uint8_t *data; /*!< The pointer to the data */ + uint8_t map_index; /*!< HID config report map index */ + } output; /*!< HID callback param of ESP_HIDD_OUTPUT_EVENT */ + + /** + * @brief ESP_HIDD_FEATURE_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + esp_hid_usage_t usage; /*!< HID report usage */ + uint16_t report_id; /*!< HID report index */ + uint16_t length; /*!< data length */ + uint8_t *data; /*!< The pointer to the data */ + uint8_t map_index; /*!< HID config report map index */ + } feature; /*!< HID callback param of ESP_HIDD_FEATURE_EVENT */ + + /** + * @brief ESP_HIDD_PROTOCOL_MODE_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + uint8_t protocol_mode; /*!< HID Protocol Mode */ + uint8_t map_index; /*!< HID config report map index */ + } protocol_mode; /*!< HID callback param of ESP_HIDD_PROTOCOL_MODE_EVENT */ + + /** + * @brief ESP_HIDD_CONTROL_EVENT + */ + struct { + esp_hidd_dev_t *dev; /*!< HID device structure */ + uint8_t control; /*!< HID Control Point */ + uint8_t map_index; /*!< HID config report map index */ + } control; /*!< HID callback param of ESP_HIDD_CONTROL_EVENT */ + +} esp_hidd_event_data_t; + +/** + * @brief Init HID Device + * @param config : configuration for the device + * @param transport: protocol that the device will use (ESP_HID_TRANSPORT_BLE/BT/USB) + * @param callback : function to call when events for this device are generated. + * Can be NULL, but will miss the START event. + * @param[out] dev : location to return the pointer to the device structure + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_init(const esp_hid_device_config_t *config, esp_hid_transport_t transport, esp_event_handler_t callback, esp_hidd_dev_t **dev); + +/** + * @brief Deinit HID Device + * @param dev : pointer to the device to deinit + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_deinit(esp_hidd_dev_t *dev); + +/** + * @brief Get the HID Device Transport + * @param dev : pointer to the HID Device + * + * @return: the transport of the connected device or ESP_HID_TRANSPORT_MAX + */ +esp_hid_transport_t esp_hidd_dev_transport_get(esp_hidd_dev_t *dev); + +/** + * @brief Check if HID Device is connected + * @param dev : pointer to the device + * + * @return: true if the device is connected + */ +bool esp_hidd_dev_connected(esp_hidd_dev_t *dev); + +/** + * @brief Set the battery level reported by the HID Device + * @param dev : pointer to the device + * @param level : battery level (0-100) + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_battery_set(esp_hidd_dev_t *dev, uint8_t level); + +/** + * @brief Send an INPUT report to the host + * @param dev : pointer to the device + * @param map_index : index of the device report map in the init config + * @param report_id : id of the HID INPUT report + * @param data : pointer to the data to send + * @param length : length of the data to send + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_input_set(esp_hidd_dev_t *dev, size_t map_index, size_t report_id, uint8_t *data, size_t length); + +/** + * @brief Send a FEATURE report to the host + * @param dev : pointer to the device + * @param map_index : index of the device report map in the init config + * @param report_id : id of the HID FEATURE report + * @param data : pointer to the data to send + * @param length : length of the data to send + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_feature_set(esp_hidd_dev_t *dev, size_t map_index, size_t report_id, uint8_t *data, size_t length); + +/** + * @brief Register function to listen for device events + * @param dev : pointer to the device + * @param callback : event handler function + * @param event : event to listen for (ESP_HIDD_ANY_EVENT for all) + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_event_handler_register(esp_hidd_dev_t *dev, esp_event_handler_t callback, esp_hidd_event_t event); + +/** + * @brief Unregister function that is listening for device events + * @param dev : pointer to the device + * @param callback : event handler function + * @param event : event that is listening for (ESP_HIDD_ANY_EVENT for all) + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidd_dev_event_handler_unregister(esp_hidd_dev_t *dev, esp_event_handler_t callback, esp_hidd_event_t event); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_gatts.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_gatts.h new file mode 100644 index 00000000..732ab1a9 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_gatts.h @@ -0,0 +1,40 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#if CONFIG_GATTS_ENABLE + +#include "esp_gatts_api.h" //for the callback + +/** + * @brief HID BLE GATTS System Callback. Attach it in your code + * or call it from your gatts event handler to allow the HID stack to function + * @param event : Event type + * @param gatts_if : GATTS Interface ID + * @param param : Point to callback parameter, currently is union type + */ +void esp_hidd_gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); + +#endif /* CONFIG_GATTS_ENABLE */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_transport.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_transport.h new file mode 100644 index 00000000..ee8d681b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidd_transport.h @@ -0,0 +1,31 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#if CONFIG_GATTS_ENABLE +#include "esp_hidd_gatts.h" +#else +typedef int esp_gatt_conn_reason_t; +#endif /* CONFIG_GATTS_ENABLE */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh.h new file mode 100644 index 00000000..b1a82643 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh.h @@ -0,0 +1,294 @@ +// Copyright 2017-2019 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. + +#pragma once + +#include "sdkconfig.h" +#include "esp_err.h" +#include "esp_log.h" +#include "esp_event.h" +#include "esp_hid_common.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief HIDH structure forward declaration + */ +struct esp_hidh_dev_s; +typedef struct esp_hidh_dev_s esp_hidh_dev_t; + +ESP_EVENT_DECLARE_BASE(ESP_HIDH_EVENTS); + +/** + * @brief HIDH callback events enum + */ +typedef enum { + ESP_HIDH_ANY_EVENT = ESP_EVENT_ANY_ID, /*!< HID device any event */ + ESP_HIDH_OPEN_EVENT = 0, /*!< HID device opened */ + ESP_HIDH_BATTERY_EVENT, /*!< HID device battery level changed */ + ESP_HIDH_INPUT_EVENT, /*!< Received HID device INPUT report */ + ESP_HIDH_FEATURE_EVENT, /*!< Received HID device FEATURE report */ + ESP_HIDH_CLOSE_EVENT, /*!< HID device closed */ + ESP_HIDH_MAX_EVENT, /*!< HID events end marker */ +} esp_hidh_event_t; + +/** + * @brief HIDH callback parameters union + */ +typedef union { + /** + * @brief ESP_HIDH_OPEN_EVENT + */ + struct { + esp_hidh_dev_t *dev; /*!< HID Remote bluetooth device */ + } open; /*!< HID callback param of ESP_HIDH_OPEN_EVENT */ + + /** + * @brief ESP_HIDH_CLOSE_EVENT + */ + struct { + esp_hidh_dev_t *dev; /*!< HID Remote bluetooth device. */ + int reason; /*!< Reason why the connection was closed. BLE Only */ + } close; /*!< HID callback param of ESP_HIDH_CLOSE_EVENT */ + + /** + * @brief ESP_HIDH_BATTERY_EVENT + */ + struct { + esp_hidh_dev_t *dev; /*!< HID Remote bluetooth device */ + uint8_t level; /*!< Battery Level (0-100%) */ + } battery; /*!< HID callback param of ESP_HIDH_BATTERY_EVENT */ + + /** + * @brief ESP_HIDH_INPUT_EVENT + */ + struct { + esp_hidh_dev_t *dev; /*!< HID Remote bluetooth device */ + esp_hid_usage_t usage; /*!< HID report usage */ + uint16_t report_id; /*!< HID report index */ + uint16_t length; /*!< HID data length */ + uint8_t *data; /*!< The pointer to the HID data */ + uint8_t map_index; /*!< HID report map index */ + } input; /*!< HID callback param of ESP_HIDH_INPUT_EVENT */ + + /** + * @brief ESP_HIDH_FEATURE_EVENT + */ + struct { + esp_hidh_dev_t *dev; /*!< HID Remote bluetooth device */ + esp_hid_usage_t usage; /*!< HID report usage */ + uint16_t report_id; /*!< HID report index */ + uint16_t length; /*!< HID data length */ + uint8_t *data; /*!< The pointer to the HID data */ + uint8_t map_index; /*!< HID report map index */ + } feature; /*!< HID callback param of ESP_HIDH_FEATURE_EVENT */ + +} esp_hidh_event_data_t; + +typedef struct { + esp_event_handler_t callback; +} esp_hidh_config_t; + +/** + * @brief Initialize the HID Host component + * @param config : pointer to esp_hidh_config_t structure + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_init(const esp_hidh_config_t *config); + +/** + * @brief De-initialize the HID Host component + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_deinit(void); + +/** + * @brief Close HID Device + * @param dev : pointer to the device + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_close(esp_hidh_dev_t *dev); + +/** + * @brief Free HID Device Memory + * This function MUST be called when handling ESP_HIDH_CLOSE_EVENT + * Only then all memory used for the device will be freed. + * @param dev : pointer to the device + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_free(esp_hidh_dev_t *dev); + +/** + * @brief Send an OUTPUT report to the device + * @param dev : pointer to the device + * @param map_index : index of the device report map + * @param report_id : id of the HID OUTPUT report + * @param data : pointer to the data to send + * @param length : length of the data to send + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_output_set(esp_hidh_dev_t *dev, size_t map_index, size_t report_id, uint8_t *data, size_t length); + +/** + * @brief Send a FEATURE report to the device + * @param dev : pointer to the device + * @param map_index : index of the device report map + * @param report_id : id of the HID FEATURE report + * @param data : pointer to the data to send + * @param length : length of the data to send + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_feature_set(esp_hidh_dev_t *dev, size_t map_index, size_t report_id, uint8_t *data, size_t length); + +/** + * @brief Get the value a FEATURE report from the device + * @param dev : pointer to the device + * @param map_index : index of the device report map + * @param report_id : id of the HID FEATURE report + * @param max_len : size of the buffer that will hold the data + * @param data : pointer to the data buffer + * @param length : pointer to the value that will be set to the number of bytes received + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_feature_get(esp_hidh_dev_t *dev, size_t map_index, size_t report_id, size_t max_len, uint8_t *data, size_t *length); + +/** + * @brief Dump the properties of HID Device to UART + * @param dev : pointer to the HID Device + * @param fp : pointer to the output file + */ +void esp_hidh_dev_dump(esp_hidh_dev_t *dev, FILE *fp); + +/** + * @brief Get the BT Device Address of a HID Device + * @param dev : pointer to the HID Device + * + * @return: pointer to the BDA byte array or NULL + */ +const uint8_t *esp_hidh_dev_bda_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the HID Device Transport + * @param dev : pointer to the HID Device + * + * @return: the transport of the connected device or ESP_HID_TRANSPORT_MAX + */ +esp_hid_transport_t esp_hidh_dev_transport_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the HID Device Cofiguration + * @param dev : pointer to the HID Device + * + * @return: pointer to the config structure or NULL + */ +const esp_hid_device_config_t *esp_hidh_dev_config_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the name of a HID Device + * @param dev : pointer to the HID Device + * + * @return: pointer to the character array or NULL + */ +const char *esp_hidh_dev_name_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the manufacturer of a HID Device + * @param dev : pointer to the HID Device + * + * @return: pointer to the character array + */ +const char *esp_hidh_dev_manufacturer_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the serial number of a HID Device + * @param dev : pointer to the HID Device + * + * @return: pointer to the character array or NULL + */ +const char *esp_hidh_dev_serial_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the VID of a HID Device + * @param dev : pointer to the HID Device + * + * @return: the VID value + */ +uint16_t esp_hidh_dev_vendor_id_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the PID of a HID Device + * @param dev : pointer to the HID Device + * + * @return: the PID value + */ +uint16_t esp_hidh_dev_product_id_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the version HID Device + * @param dev : pointer to the HID Device + * + * @return: the version value + */ +uint16_t esp_hidh_dev_version_get(esp_hidh_dev_t *dev); + +/** + * @brief Get the appearance of BLE HID Device + * @param dev : pointer to the BLE HID Device + * + * @return: the appearance value + */ +uint16_t esp_hidh_dev_appearance_get(esp_hidh_dev_t *dev); //BLE Only + +/** + * @brief Get the calculated HID Device usage type + * @param dev : pointer to the HID Device + * + * @return: the hid usage type + */ +esp_hid_usage_t esp_hidh_dev_usage_get(esp_hidh_dev_t *dev); + +/** + * @brief Get an array of all reports found on a device + * @param dev : pointer to the device + * @param num_reports : pointer to the value that will be set to the number of reports + * @param reports : location to set to the pointer of the reports array + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_reports_get(esp_hidh_dev_t *dev, size_t *num_reports, esp_hid_report_item_t **reports); + +/** + * @brief Get an array of the report maps found on a device + * @param dev : pointer to the device + * @param num_maps : pointer to the value that will be set to the number of report maps found + * @param maps : location to set to the pointer of the report maps array + * + * @return: ESP_OK on success + */ +esp_err_t esp_hidh_dev_report_maps_get(esp_hidh_dev_t *dev, size_t *num_maps, esp_hid_raw_report_map_t **maps); + +#include "esp_hidh_transport.h" + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_bluedroid.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_bluedroid.h new file mode 100644 index 00000000..e89d0b40 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_bluedroid.h @@ -0,0 +1,41 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#if CONFIG_BLUEDROID_ENABLED + +#include "esp_bt_defs.h" + +/** + * @brief Open BlueTooth HID Device using BlueDroid + * @param bda : BT Device Address + * @param transport : BT Device Protocol (Classic/HID) + * @param remote_addr_type : BLE Remote address type + * + * @return: ESP_OK on success + */ +esp_hidh_dev_t *esp_hidh_dev_open(esp_bd_addr_t bda, esp_hid_transport_t transport, uint8_t remote_addr_type); + +#endif /* CONFIG_BLUEDROID_ENABLED */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_gattc.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_gattc.h new file mode 100644 index 00000000..e58141dc --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_gattc.h @@ -0,0 +1,40 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#if CONFIG_GATTC_ENABLE + +#include "esp_gattc_api.h" //for the callback + +/** + * @brief HID BLE GATTC System Callback. Attach it in your code + * or call it from your gattc event handler to allow the HID stack to function + * @param event : Event type + * @param gattc_if : GATTC Interface ID + * @param param : Point to callback parameter, currently is union type + */ +void esp_hidh_gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param); + +#endif /* CONFIG_GATTC_ENABLE */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_transport.h b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_transport.h new file mode 100644 index 00000000..22138aef --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hid/include/esp_hidh_transport.h @@ -0,0 +1,33 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sdkconfig.h" + +#if CONFIG_GATTC_ENABLE +#include "esp_hidh_gattc.h" +#endif + +#if CONFIG_BLUEDROID_ENABLED +#include "esp_hidh_bluedroid.h" +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_http_client/include/esp_http_client.h b/tools/sdk/esp32c3/include/esp_http_client/include/esp_http_client.h new file mode 100644 index 00000000..ee19f70c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_http_client/include/esp_http_client.h @@ -0,0 +1,588 @@ +// Copyright 2015-2018 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. + +#ifndef _ESP_HTTP_CLIENT_H +#define _ESP_HTTP_CLIENT_H + +#include "freertos/FreeRTOS.h" +#include "http_parser.h" +#include "sdkconfig.h" +#include "esp_err.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define DEFAULT_HTTP_BUF_SIZE (512) + +typedef struct esp_http_client *esp_http_client_handle_t; +typedef struct esp_http_client_event *esp_http_client_event_handle_t; + +/** + * @brief HTTP Client events id + */ +typedef enum { + HTTP_EVENT_ERROR = 0, /*!< This event occurs when there are any errors during execution */ + HTTP_EVENT_ON_CONNECTED, /*!< Once the HTTP has been connected to the server, no data exchange has been performed */ + HTTP_EVENT_HEADERS_SENT, /*!< After sending all the headers to the server */ + HTTP_EVENT_HEADER_SENT = HTTP_EVENT_HEADERS_SENT, /*!< This header has been kept for backward compatability + and will be deprecated in future versions esp-idf */ + HTTP_EVENT_ON_HEADER, /*!< Occurs when receiving each header sent from the server */ + HTTP_EVENT_ON_DATA, /*!< Occurs when receiving data from the server, possibly multiple portions of the packet */ + HTTP_EVENT_ON_FINISH, /*!< Occurs when finish a HTTP session */ + HTTP_EVENT_DISCONNECTED, /*!< The connection has been disconnected */ +} esp_http_client_event_id_t; + +/** + * @brief HTTP Client events data + */ +typedef struct esp_http_client_event { + esp_http_client_event_id_t event_id; /*!< event_id, to know the cause of the event */ + esp_http_client_handle_t client; /*!< esp_http_client_handle_t context */ + void *data; /*!< data of the event */ + int data_len; /*!< data length of data */ + void *user_data; /*!< user_data context, from esp_http_client_config_t user_data */ + char *header_key; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header key */ + char *header_value; /*!< For HTTP_EVENT_ON_HEADER event_id, it's store current http header value */ +} esp_http_client_event_t; + + +/** + * @brief HTTP Client transport + */ +typedef enum { + HTTP_TRANSPORT_UNKNOWN = 0x0, /*!< Unknown */ + HTTP_TRANSPORT_OVER_TCP, /*!< Transport over tcp */ + HTTP_TRANSPORT_OVER_SSL, /*!< Transport over ssl */ +} esp_http_client_transport_t; + +typedef esp_err_t (*http_event_handle_cb)(esp_http_client_event_t *evt); + +/** + * @brief HTTP method + */ +typedef enum { + HTTP_METHOD_GET = 0, /*!< HTTP GET Method */ + HTTP_METHOD_POST, /*!< HTTP POST Method */ + HTTP_METHOD_PUT, /*!< HTTP PUT Method */ + HTTP_METHOD_PATCH, /*!< HTTP PATCH Method */ + HTTP_METHOD_DELETE, /*!< HTTP DELETE Method */ + HTTP_METHOD_HEAD, /*!< HTTP HEAD Method */ + HTTP_METHOD_NOTIFY, /*!< HTTP NOTIFY Method */ + HTTP_METHOD_SUBSCRIBE, /*!< HTTP SUBSCRIBE Method */ + HTTP_METHOD_UNSUBSCRIBE,/*!< HTTP UNSUBSCRIBE Method */ + HTTP_METHOD_OPTIONS, /*!< HTTP OPTIONS Method */ + HTTP_METHOD_COPY, /*!< HTTP COPY Method */ + HTTP_METHOD_MOVE, /*!< HTTP MOVE Method */ + HTTP_METHOD_LOCK, /*!< HTTP LOCK Method */ + HTTP_METHOD_UNLOCK, /*!< HTTP UNLOCK Method */ + HTTP_METHOD_PROPFIND, /*!< HTTP PROPFIND Method */ + HTTP_METHOD_PROPPATCH, /*!< HTTP PROPPATCH Method */ + HTTP_METHOD_MKCOL, /*!< HTTP MKCOL Method */ + HTTP_METHOD_MAX, +} esp_http_client_method_t; + +/** + * @brief HTTP Authentication type + */ +typedef enum { + HTTP_AUTH_TYPE_NONE = 0, /*!< No authention */ + HTTP_AUTH_TYPE_BASIC, /*!< HTTP Basic authentication */ + HTTP_AUTH_TYPE_DIGEST, /*!< HTTP Disgest authentication */ +} esp_http_client_auth_type_t; + +/** + * @brief HTTP configuration + */ +typedef struct { + const char *url; /*!< HTTP URL, the information on the URL is most important, it overrides the other fields below, if any */ + const char *host; /*!< Domain or IP as string */ + int port; /*!< Port to connect, default depend on esp_http_client_transport_t (80 or 443) */ + const char *username; /*!< Using for Http authentication */ + const char *password; /*!< Using for Http authentication */ + esp_http_client_auth_type_t auth_type; /*!< Http authentication type, see `esp_http_client_auth_type_t` */ + const char *path; /*!< HTTP Path, if not set, default is `/` */ + const char *query; /*!< HTTP query */ + const char *cert_pem; /*!< SSL server certification, PEM format as string, if the client requires to verify server */ + size_t cert_len; /*!< Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem */ + const char *client_cert_pem; /*!< SSL client certification, PEM format as string, if the server requires to verify client */ + size_t client_cert_len; /*!< Length of the buffer pointed to by client_cert_pem. May be 0 for null-terminated pem */ + const char *client_key_pem; /*!< SSL client key, PEM format as string, if the server requires to verify client */ + size_t client_key_len; /*!< Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem */ + const char *user_agent; /*!< The User Agent string to send with HTTP requests */ + esp_http_client_method_t method; /*!< HTTP Method */ + int timeout_ms; /*!< Network timeout in milliseconds */ + bool disable_auto_redirect; /*!< Disable HTTP automatic redirects */ + int max_redirection_count; /*!< Max number of redirections on receiving HTTP redirect status code, using default value if zero*/ + int max_authorization_retries; /*!< Max connection retries on receiving HTTP unauthorized status code, using default value if zero. Disables authorization retry if -1*/ + http_event_handle_cb event_handler; /*!< HTTP Event Handle */ + esp_http_client_transport_t transport_type; /*!< HTTP transport type, see `esp_http_client_transport_t` */ + int buffer_size; /*!< HTTP receive buffer size */ + int buffer_size_tx; /*!< HTTP transmit buffer size */ + void *user_data; /*!< HTTP user_data context */ + bool is_async; /*!< Set asynchronous mode, only supported with HTTPS for now */ + bool use_global_ca_store; /*!< Use a global ca_store for all the connections in which this bool is set. */ + bool skip_cert_common_name_check; /*!< Skip any validation of server certificate CN field */ + bool keep_alive_enable; /*!< Enable keep-alive timeout */ + int keep_alive_idle; /*!< Keep-alive idle time. Default is 5 (second) */ + int keep_alive_interval; /*!< Keep-alive interval time. Default is 5 (second) */ + int keep_alive_count; /*!< Keep-alive packet retry send count. Default is 3 counts */ + struct ifreq *if_name; /*!< The name of interface for data to go through. Use the default interface without setting */ +} esp_http_client_config_t; + +/** + * Enum for the HTTP status codes. + */ +typedef enum { + /* 2xx - Success */ + HttpStatus_Ok = 200, + + /* 3xx - Redirection */ + HttpStatus_MultipleChoices = 300, + HttpStatus_MovedPermanently = 301, + HttpStatus_Found = 302, + HttpStatus_TemporaryRedirect = 307, + + /* 4xx - Client Error */ + HttpStatus_Unauthorized = 401, + HttpStatus_Forbidden = 403, + HttpStatus_NotFound = 404, + + /* 5xx - Server Error */ + HttpStatus_InternalError = 500 +} HttpStatus_Code; + +#define ESP_ERR_HTTP_BASE (0x7000) /*!< Starting number of HTTP error codes */ +#define ESP_ERR_HTTP_MAX_REDIRECT (ESP_ERR_HTTP_BASE + 1) /*!< The error exceeds the number of HTTP redirects */ +#define ESP_ERR_HTTP_CONNECT (ESP_ERR_HTTP_BASE + 2) /*!< Error open the HTTP connection */ +#define ESP_ERR_HTTP_WRITE_DATA (ESP_ERR_HTTP_BASE + 3) /*!< Error write HTTP data */ +#define ESP_ERR_HTTP_FETCH_HEADER (ESP_ERR_HTTP_BASE + 4) /*!< Error read HTTP header from server */ +#define ESP_ERR_HTTP_INVALID_TRANSPORT (ESP_ERR_HTTP_BASE + 5) /*!< There are no transport support for the input scheme */ +#define ESP_ERR_HTTP_CONNECTING (ESP_ERR_HTTP_BASE + 6) /*!< HTTP connection hasn't been established yet */ +#define ESP_ERR_HTTP_EAGAIN (ESP_ERR_HTTP_BASE + 7) /*!< Mapping of errno EAGAIN to esp_err_t */ + +/** + * @brief Start a HTTP session + * This function must be the first function to call, + * and it returns a esp_http_client_handle_t that you must use as input to other functions in the interface. + * This call MUST have a corresponding call to esp_http_client_cleanup when the operation is complete. + * + * @param[in] config The configurations, see `http_client_config_t` + * + * @return + * - `esp_http_client_handle_t` + * - NULL if any errors + */ +esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config); + +/** + * @brief Invoke this function after `esp_http_client_init` and all the options calls are made, and will perform the + * transfer as described in the options. It must be called with the same esp_http_client_handle_t as input as the esp_http_client_init call returned. + * esp_http_client_perform performs the entire request in either blocking or non-blocking manner. By default, the API performs request in a blocking manner and returns when done, + * or if it failed, and in non-blocking manner, it returns if EAGAIN/EWOULDBLOCK or EINPROGRESS is encountered, or if it failed. And in case of non-blocking request, + * the user may call this API multiple times unless request & response is complete or there is a failure. To enable non-blocking esp_http_client_perform(), `is_async` member of esp_http_client_config_t + * must be set while making a call to esp_http_client_init() API. + * You can do any amount of calls to esp_http_client_perform while using the same esp_http_client_handle_t. The underlying connection may be kept open if the server allows it. + * If you intend to transfer more than one file, you are even encouraged to do so. + * esp_http_client will then attempt to re-use the same connection for the following transfers, thus making the operations faster, less CPU intense and using less network resources. + * Just note that you will have to use `esp_http_client_set_**` between the invokes to set options for the following esp_http_client_perform. + * + * @note You must never call this function simultaneously from two places using the same client handle. + * Let the function return first before invoking it another time. + * If you want parallel transfers, you must use several esp_http_client_handle_t. + * This function include `esp_http_client_open` -> `esp_http_client_write` -> `esp_http_client_fetch_headers` -> `esp_http_client_read` (and option) `esp_http_client_close`. + * + * @param client The esp_http_client handle + * + * @return + * - ESP_OK on successful + * - ESP_FAIL on error + */ +esp_err_t esp_http_client_perform(esp_http_client_handle_t client); + +/** + * @brief Set URL for client, when performing this behavior, the options in the URL will replace the old ones + * + * @param[in] client The esp_http_client handle + * @param[in] url The url + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url); + +/** + * @brief Set post data, this function must be called before `esp_http_client_perform`. + * Note: The data parameter passed to this function is a pointer and this function will not copy the data + * + * @param[in] client The esp_http_client handle + * @param[in] data post data pointer + * @param[in] len post length + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int len); + +/** + * @brief Get current post field information + * + * @param[in] client The client + * @param[out] data Point to post data pointer + * + * @return Size of post data + */ +int esp_http_client_get_post_field(esp_http_client_handle_t client, char **data); + +/** + * @brief Set http request header, this function must be called after esp_http_client_init and before any + * perform function + * + * @param[in] client The esp_http_client handle + * @param[in] key The header key + * @param[in] value The header value + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value); + +/** + * @brief Get http request header. + * The value parameter will be set to NULL if there is no header which is same as + * the key specified, otherwise the address of header value will be assigned to value parameter. + * This function must be called after `esp_http_client_init`. + * + * @param[in] client The esp_http_client handle + * @param[in] key The header key + * @param[out] value The header value + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_get_header(esp_http_client_handle_t client, const char *key, char **value); + +/** + * @brief Get http request username. + * The address of username buffer will be assigned to value parameter. + * This function must be called after `esp_http_client_init`. + * + * @param[in] client The esp_http_client handle + * @param[out] value The username value + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_get_username(esp_http_client_handle_t client, char **value); + +/** + * @brief Set http request username. + * The value of username parameter will be assigned to username buffer. + * If the username parameter is NULL then username buffer will be freed. + * + * @param[in] client The esp_http_client handle + * @param[in] username The username value + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_set_username(esp_http_client_handle_t client, const char *username); + +/** + * @brief Get http request password. + * The address of password buffer will be assigned to value parameter. + * This function must be called after `esp_http_client_init`. + * + * @param[in] client The esp_http_client handle + * @param[out] value The password value + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_get_password(esp_http_client_handle_t client, char **value); + +/** + * @brief Set http request password. + * The value of password parameter will be assigned to password buffer. + * If the password parameter is NULL then password buffer will be freed. + * + * @param[in] client The esp_http_client handle + * @param[in] password The password value + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_set_password(esp_http_client_handle_t client, char *password); + +/** + * @brief Set http request auth_type. + * + * @param[in] client The esp_http_client handle + * @param[in] auth_type The esp_http_client auth type + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_set_authtype(esp_http_client_handle_t client, esp_http_client_auth_type_t auth_type); + +/** + * @brief Set http request method + * + * @param[in] client The esp_http_client handle + * @param[in] method The method + * + * @return + * - ESP_OK + * - ESP_ERR_INVALID_ARG + */ +esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, esp_http_client_method_t method); + +/** + * @brief Delete http request header + * + * @param[in] client The esp_http_client handle + * @param[in] key The key + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_delete_header(esp_http_client_handle_t client, const char *key); + +/** + * @brief This function will be open the connection, write all header strings and return + * + * @param[in] client The esp_http_client handle + * @param[in] write_len HTTP Content length need to write to the server + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_open(esp_http_client_handle_t client, int write_len); + +/** + * @brief This function will write data to the HTTP connection previously opened by esp_http_client_open() + * + * @param[in] client The esp_http_client handle + * @param buffer The buffer + * @param[in] len This value must not be larger than the write_len parameter provided to esp_http_client_open() + * + * @return + * - (-1) if any errors + * - Length of data written + */ +int esp_http_client_write(esp_http_client_handle_t client, const char *buffer, int len); + +/** + * @brief This function need to call after esp_http_client_open, it will read from http stream, process all receive headers + * + * @param[in] client The esp_http_client handle + * + * @return + * - (0) if stream doesn't contain content-length header, or chunked encoding (checked by `esp_http_client_is_chunked` response) + * - (-1: ESP_FAIL) if any errors + * - Download data length defined by content-length header + */ +int esp_http_client_fetch_headers(esp_http_client_handle_t client); + + +/** + * @brief Check response data is chunked + * + * @param[in] client The esp_http_client handle + * + * @return true or false + */ +bool esp_http_client_is_chunked_response(esp_http_client_handle_t client); + +/** + * @brief Read data from http stream + * + * @param[in] client The esp_http_client handle + * @param buffer The buffer + * @param[in] len The length + * + * @return + * - (-1) if any errors + * - Length of data was read + */ +int esp_http_client_read(esp_http_client_handle_t client, char *buffer, int len); + + +/** + * @brief Get http response status code, the valid value if this function invoke after `esp_http_client_perform` + * + * @param[in] client The esp_http_client handle + * + * @return Status code + */ +int esp_http_client_get_status_code(esp_http_client_handle_t client); + +/** + * @brief Get http response content length (from header Content-Length) + * the valid value if this function invoke after `esp_http_client_perform` + * + * @param[in] client The esp_http_client handle + * + * @return + * - (-1) Chunked transfer + * - Content-Length value as bytes + */ +int esp_http_client_get_content_length(esp_http_client_handle_t client); + +/** + * @brief Close http connection, still kept all http request resources + * + * @param[in] client The esp_http_client handle + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_close(esp_http_client_handle_t client); + +/** + * @brief This function must be the last function to call for an session. + * It is the opposite of the esp_http_client_init function and must be called with the same handle as input that a esp_http_client_init call returned. + * This might close all connections this handle has used and possibly has kept open until now. + * Don't call this function if you intend to transfer more files, re-using handles is a key to good performance with esp_http_client. + * + * @param[in] client The esp_http_client handle + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client); + +/** + * @brief Get transport type + * + * @param[in] client The esp_http_client handle + * + * @return + * - HTTP_TRANSPORT_UNKNOWN + * - HTTP_TRANSPORT_OVER_TCP + * - HTTP_TRANSPORT_OVER_SSL + */ +esp_http_client_transport_t esp_http_client_get_transport_type(esp_http_client_handle_t client); + +/** + * @brief Set redirection URL. + * When received the 30x code from the server, the client stores the redirect URL provided by the server. + * This function will set the current URL to redirect to enable client to execute the redirection request. + * + * @param[in] client The esp_http_client handle + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_http_client_set_redirection(esp_http_client_handle_t client); + +/** + * @brief On receiving HTTP Status code 401, this API can be invoked to add authorization + * information. + * + * @note There is a possibility of receiving body message with redirection status codes, thus make sure + * to flush off body data after calling this API. + * + * @param[in] client The esp_http_client handle + */ +void esp_http_client_add_auth(esp_http_client_handle_t client); + +/** + * @brief Checks if entire data in the response has been read without any error. + * + * @param[in] client The esp_http_client handle + * + * @return + * - true + * - false + */ +bool esp_http_client_is_complete_data_received(esp_http_client_handle_t client); + +/** + * @brief Helper API to read larger data chunks + * This is a helper API which internally calls `esp_http_client_read` multiple times till the end of data is reached or till the buffer gets full. + * + * @param[in] client The esp_http_client handle + * @param buffer The buffer + * @param[in] len The buffer length + * + * @return + * - Length of data was read + */ + +int esp_http_client_read_response(esp_http_client_handle_t client, char *buffer, int len); + +/** + * @brief Process all remaining response data + * This uses an internal buffer to repeatedly receive, parse, and discard response data until complete data is processed. + * As no additional user-supplied buffer is required, this may be preferrable to `esp_http_client_read_response` in situations where the content of the response may be ignored. + * + * @param[in] client The esp_http_client handle + * @param len Length of data discarded + * + * @return + * - ESP_OK If successful, len will have discarded length + * - ESP_FAIL If failed to read response + * - ESP_ERR_INVALID_ARG If the client is NULL + */ +esp_err_t esp_http_client_flush_response(esp_http_client_handle_t client, int *len); + +/** + * @brief Get URL from client + * + * @param[in] client The esp_http_client handle + * @param[inout] url The buffer to store URL + * @param[in] len The buffer length + * + * @return + * - ESP_OK + * - ESP_FAIL + */ + +esp_err_t esp_http_client_get_url(esp_http_client_handle_t client, char *url, const int len); + +/** + * @brief Get Chunk-Length from client + * + * @param[in] client The esp_http_client handle + * @param[out] len Variable to store length + * + * @return + * - ESP_OK If successful, len will have length of current chunk + * - ESP_FAIL If the server is not a chunked server + * - ESP_ERR_INVALID_ARG If the client or len are NULL + */ +esp_err_t esp_http_client_get_chunk_length(esp_http_client_handle_t client, int *len); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/esp32c3/include/esp_http_server/include/esp_http_server.h b/tools/sdk/esp32c3/include/esp_http_server/include/esp_http_server.h new file mode 100644 index 00000000..445d0c0c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_http_server/include/esp_http_server.h @@ -0,0 +1,1665 @@ +// Copyright 2018 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. + +#ifndef _ESP_HTTP_SERVER_H_ +#define _ESP_HTTP_SERVER_H_ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* +note: esp_https_server.h includes a customized copy of this +initializer that should be kept in sync +*/ +#define HTTPD_DEFAULT_CONFIG() { \ + .task_priority = tskIDLE_PRIORITY+5, \ + .stack_size = 4096, \ + .core_id = tskNO_AFFINITY, \ + .server_port = 80, \ + .ctrl_port = 32768, \ + .max_open_sockets = 7, \ + .max_uri_handlers = 8, \ + .max_resp_headers = 8, \ + .backlog_conn = 5, \ + .lru_purge_enable = false, \ + .recv_wait_timeout = 5, \ + .send_wait_timeout = 5, \ + .global_user_ctx = NULL, \ + .global_user_ctx_free_fn = NULL, \ + .global_transport_ctx = NULL, \ + .global_transport_ctx_free_fn = NULL, \ + .open_fn = NULL, \ + .close_fn = NULL, \ + .uri_match_fn = NULL \ +} + +#define ESP_ERR_HTTPD_BASE (0xb000) /*!< Starting number of HTTPD error codes */ +#define ESP_ERR_HTTPD_HANDLERS_FULL (ESP_ERR_HTTPD_BASE + 1) /*!< All slots for registering URI handlers have been consumed */ +#define ESP_ERR_HTTPD_HANDLER_EXISTS (ESP_ERR_HTTPD_BASE + 2) /*!< URI handler with same method and target URI already registered */ +#define ESP_ERR_HTTPD_INVALID_REQ (ESP_ERR_HTTPD_BASE + 3) /*!< Invalid request pointer */ +#define ESP_ERR_HTTPD_RESULT_TRUNC (ESP_ERR_HTTPD_BASE + 4) /*!< Result string truncated */ +#define ESP_ERR_HTTPD_RESP_HDR (ESP_ERR_HTTPD_BASE + 5) /*!< Response header field larger than supported */ +#define ESP_ERR_HTTPD_RESP_SEND (ESP_ERR_HTTPD_BASE + 6) /*!< Error occured while sending response packet */ +#define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */ +#define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */ + +/* Symbol to be used as length parameter in httpd_resp_send APIs + * for setting buffer length to string length */ +#define HTTPD_RESP_USE_STRLEN -1 + +/* ************** Group: Initialization ************** */ +/** @name Initialization + * APIs related to the Initialization of the web server + * @{ + */ + +/** + * @brief HTTP Server Instance Handle + * + * Every instance of the server will have a unique handle. + */ +typedef void* httpd_handle_t; + +/** + * @brief HTTP Method Type wrapper over "enum http_method" + * available in "http_parser" library + */ +typedef enum http_method httpd_method_t; + +/** + * @brief Prototype for freeing context data (if any) + * @param[in] ctx object to free + */ +typedef void (*httpd_free_ctx_fn_t)(void *ctx); + +/** + * @brief Function prototype for opening a session. + * + * Called immediately after the socket was opened to set up the send/recv functions and + * other parameters of the socket. + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @return + * - ESP_OK : On success + * - Any value other than ESP_OK will signal the server to close the socket immediately + */ +typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd); + +/** + * @brief Function prototype for closing a session. + * + * @note It's possible that the socket descriptor is invalid at this point, the function + * is called for all terminated sessions. Ensure proper handling of return codes. + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + */ +typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd); + +/** + * @brief Function prototype for URI matching. + * + * @param[in] reference_uri URI/template with respect to which the other URI is matched + * @param[in] uri_to_match URI/template being matched to the reference URI/template + * @param[in] match_upto For specifying the actual length of `uri_to_match` up to + * which the matching algorithm is to be applied (The maximum + * value is `strlen(uri_to_match)`, independent of the length + * of `reference_uri`) + * @return true on match + */ +typedef bool (*httpd_uri_match_func_t)(const char *reference_uri, + const char *uri_to_match, + size_t match_upto); + +/** + * @brief HTTP Server Configuration Structure + * + * @note Use HTTPD_DEFAULT_CONFIG() to initialize the configuration + * to a default value and then modify only those fields that are + * specifically determined by the use case. + */ +typedef struct httpd_config { + unsigned task_priority; /*!< Priority of FreeRTOS task which runs the server */ + size_t stack_size; /*!< The maximum stack size allowed for the server task */ + BaseType_t core_id; /*!< The core the HTTP server task will run on */ + + /** + * TCP Port number for receiving and transmitting HTTP traffic + */ + uint16_t server_port; + + /** + * UDP Port number for asynchronously exchanging control signals + * between various components of the server + */ + uint16_t ctrl_port; + + uint16_t max_open_sockets; /*!< Max number of sockets/clients connected at any time*/ + uint16_t max_uri_handlers; /*!< Maximum allowed uri handlers */ + uint16_t max_resp_headers; /*!< Maximum allowed additional headers in HTTP response */ + uint16_t backlog_conn; /*!< Number of backlog connections */ + bool lru_purge_enable; /*!< Purge "Least Recently Used" connection */ + uint16_t recv_wait_timeout; /*!< Timeout for recv function (in seconds)*/ + uint16_t send_wait_timeout; /*!< Timeout for send function (in seconds)*/ + + /** + * Global user context. + * + * This field can be used to store arbitrary user data within the server context. + * The value can be retrieved using the server handle, available e.g. in the httpd_req_t struct. + * + * When shutting down, the server frees up the user context by + * calling free() on the global_user_ctx field. If you wish to use a custom + * function for freeing the global user context, please specify that here. + */ + void * global_user_ctx; + + /** + * Free function for global user context + */ + httpd_free_ctx_fn_t global_user_ctx_free_fn; + + /** + * Global transport context. + * + * Similar to global_user_ctx, but used for session encoding or encryption (e.g. to hold the SSL context). + * It will be freed using free(), unless global_transport_ctx_free_fn is specified. + */ + void * global_transport_ctx; + + /** + * Free function for global transport context + */ + httpd_free_ctx_fn_t global_transport_ctx_free_fn; + + /** + * Custom session opening callback. + * + * Called on a new session socket just after accept(), but before reading any data. + * + * This is an opportunity to set up e.g. SSL encryption using global_transport_ctx + * and the send/recv/pending session overrides. + * + * If a context needs to be maintained between these functions, store it in the session using + * httpd_sess_set_transport_ctx() and retrieve it later with httpd_sess_get_transport_ctx() + * + * Returning a value other than ESP_OK will immediately close the new socket. + */ + httpd_open_func_t open_fn; + + /** + * Custom session closing callback. + * + * Called when a session is deleted, before freeing user and transport contexts and before + * closing the socket. This is a place for custom de-init code common to all sockets. + * + * Set the user or transport context to NULL if it was freed here, so the server does not + * try to free it again. + * + * This function is run for all terminated sessions, including sessions where the socket + * was closed by the network stack - that is, the file descriptor may not be valid anymore. + */ + httpd_close_func_t close_fn; + + /** + * URI matcher function. + * + * Called when searching for a matching URI: + * 1) whose request handler is to be executed right + * after an HTTP request is successfully parsed + * 2) in order to prevent duplication while registering + * a new URI handler using `httpd_register_uri_handler()` + * + * Available options are: + * 1) NULL : Internally do basic matching using `strncmp()` + * 2) `httpd_uri_match_wildcard()` : URI wildcard matcher + * + * Users can implement their own matching functions (See description + * of the `httpd_uri_match_func_t` function prototype) + */ + httpd_uri_match_func_t uri_match_fn; +} httpd_config_t; + +/** + * @brief Starts the web server + * + * Create an instance of HTTP server and allocate memory/resources for it + * depending upon the specified configuration. + * + * Example usage: + * @code{c} + * + * //Function for starting the webserver + * httpd_handle_t start_webserver(void) + * { + * // Generate default configuration + * httpd_config_t config = HTTPD_DEFAULT_CONFIG(); + * + * // Empty handle to http_server + * httpd_handle_t server = NULL; + * + * // Start the httpd server + * if (httpd_start(&server, &config) == ESP_OK) { + * // Register URI handlers + * httpd_register_uri_handler(server, &uri_get); + * httpd_register_uri_handler(server, &uri_post); + * } + * // If server failed to start, handle will be NULL + * return server; + * } + * + * @endcode + * + * @param[in] config Configuration for new instance of the server + * @param[out] handle Handle to newly created instance of the server. NULL on error + * @return + * - ESP_OK : Instance created successfully + * - ESP_ERR_INVALID_ARG : Null argument(s) + * - ESP_ERR_HTTPD_ALLOC_MEM : Failed to allocate memory for instance + * - ESP_ERR_HTTPD_TASK : Failed to launch server task + */ +esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config); + +/** + * @brief Stops the web server + * + * Deallocates memory/resources used by an HTTP server instance and + * deletes it. Once deleted the handle can no longer be used for accessing + * the instance. + * + * Example usage: + * @code{c} + * + * // Function for stopping the webserver + * void stop_webserver(httpd_handle_t server) + * { + * // Ensure handle is non NULL + * if (server != NULL) { + * // Stop the httpd server + * httpd_stop(server); + * } + * } + * + * @endcode + * + * @param[in] handle Handle to server returned by httpd_start + * @return + * - ESP_OK : Server stopped successfully + * - ESP_ERR_INVALID_ARG : Handle argument is Null + */ +esp_err_t httpd_stop(httpd_handle_t handle); + +/** End of Group Initialization + * @} + */ + +/* ************** Group: URI Handlers ************** */ +/** @name URI Handlers + * APIs related to the URI handlers + * @{ + */ + +/* Max supported HTTP request header length */ +#define HTTPD_MAX_REQ_HDR_LEN CONFIG_HTTPD_MAX_REQ_HDR_LEN + +/* Max supported HTTP request URI length */ +#define HTTPD_MAX_URI_LEN CONFIG_HTTPD_MAX_URI_LEN + +/** + * @brief HTTP Request Data Structure + */ +typedef struct httpd_req { + httpd_handle_t handle; /*!< Handle to server instance */ + int method; /*!< The type of HTTP request, -1 if unsupported method */ + const char uri[HTTPD_MAX_URI_LEN + 1]; /*!< The URI of this request (1 byte extra for null termination) */ + size_t content_len; /*!< Length of the request body */ + void *aux; /*!< Internally used members */ + + /** + * User context pointer passed during URI registration. + */ + void *user_ctx; + + /** + * Session Context Pointer + * + * A session context. Contexts are maintained across 'sessions' for a + * given open TCP connection. One session could have multiple request + * responses. The web server will ensure that the context persists + * across all these request and responses. + * + * By default, this is NULL. URI Handlers can set this to any meaningful + * value. + * + * If the underlying socket gets closed, and this pointer is non-NULL, + * the web server will free up the context by calling free(), unless + * free_ctx function is set. + */ + void *sess_ctx; + + /** + * Pointer to free context hook + * + * Function to free session context + * + * If the web server's socket closes, it frees up the session context by + * calling free() on the sess_ctx member. If you wish to use a custom + * function for freeing the session context, please specify that here. + */ + httpd_free_ctx_fn_t free_ctx; + + /** + * Flag indicating if Session Context changes should be ignored + * + * By default, if you change the sess_ctx in some URI handler, the http server + * will internally free the earlier context (if non NULL), after the URI handler + * returns. If you want to manage the allocation/reallocation/freeing of + * sess_ctx yourself, set this flag to true, so that the server will not + * perform any checks on it. The context will be cleared by the server + * (by calling free_ctx or free()) only if the socket gets closed. + */ + bool ignore_sess_ctx_changes; +} httpd_req_t; + +/** + * @brief Structure for URI handler + */ +typedef struct httpd_uri { + const char *uri; /*!< The URI to handle */ + httpd_method_t method; /*!< Method supported by the URI */ + + /** + * Handler to call for supported request method. This must + * return ESP_OK, or else the underlying socket will be closed. + */ + esp_err_t (*handler)(httpd_req_t *r); + + /** + * Pointer to user context data which will be available to handler + */ + void *user_ctx; + +#ifdef CONFIG_HTTPD_WS_SUPPORT + /** + * Flag for indicating a WebSocket endpoint. + * If this flag is true, then method must be HTTP_GET. Otherwise the handshake will not be handled. + */ + bool is_websocket; + + /** + * Flag indicating that control frames (PING, PONG, CLOSE) are also passed to the handler + * This is used if a custom processing of the control frames is needed + */ + bool handle_ws_control_frames; + + /** + * Pointer to subprotocol supported by URI + */ + const char *supported_subprotocol; +#endif +} httpd_uri_t; + +/** + * @brief Registers a URI handler + * + * @note URI handlers can be registered in real time as long as the + * server handle is valid. + * + * Example usage: + * @code{c} + * + * esp_err_t my_uri_handler(httpd_req_t* req) + * { + * // Recv , Process and Send + * .... + * .... + * .... + * + * // Fail condition + * if (....) { + * // Return fail to close session // + * return ESP_FAIL; + * } + * + * // On success + * return ESP_OK; + * } + * + * // URI handler structure + * httpd_uri_t my_uri { + * .uri = "/my_uri/path/xyz", + * .method = HTTPD_GET, + * .handler = my_uri_handler, + * .user_ctx = NULL + * }; + * + * // Register handler + * if (httpd_register_uri_handler(server_handle, &my_uri) != ESP_OK) { + * // If failed to register handler + * .... + * } + * + * @endcode + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri_handler pointer to handler that needs to be registered + * + * @return + * - ESP_OK : On successfully registering the handler + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_HANDLERS_FULL : If no slots left for new handler + * - ESP_ERR_HTTPD_HANDLER_EXISTS : If handler with same URI and + * method is already registered + */ +esp_err_t httpd_register_uri_handler(httpd_handle_t handle, + const httpd_uri_t *uri_handler); + +/** + * @brief Unregister a URI handler + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri URI string + * @param[in] method HTTP method + * + * @return + * - ESP_OK : On successfully deregistering the handler + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_FOUND : Handler with specified URI and method not found + */ +esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle, + const char *uri, httpd_method_t method); + +/** + * @brief Unregister all URI handlers with the specified uri string + * + * @param[in] handle handle to HTTPD server instance + * @param[in] uri uri string specifying all handlers that need + * to be deregisterd + * + * @return + * - ESP_OK : On successfully deregistering all such handlers + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_NOT_FOUND : No handler registered with specified uri string + */ +esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri); + +/** End of URI Handlers + * @} + */ + +/* ************** Group: HTTP Error ************** */ +/** @name HTTP Error + * Prototype for HTTP errors and error handling functions + * @{ + */ + +/** + * @brief Error codes sent as HTTP response in case of errors + * encountered during processing of an HTTP request + */ +typedef enum { + /* For any unexpected errors during parsing, like unexpected + * state transitions, or unhandled errors. + */ + HTTPD_500_INTERNAL_SERVER_ERROR = 0, + + /* For methods not supported by http_parser. Presently + * http_parser halts parsing when such methods are + * encountered and so the server responds with 400 Bad + * Request error instead. + */ + HTTPD_501_METHOD_NOT_IMPLEMENTED, + + /* When HTTP version is not 1.1 */ + HTTPD_505_VERSION_NOT_SUPPORTED, + + /* Returned when http_parser halts parsing due to incorrect + * syntax of request, unsupported method in request URI or + * due to chunked encoding / upgrade field present in headers + */ + HTTPD_400_BAD_REQUEST, + + /* This response means the client must authenticate itself + * to get the requested response. + */ + HTTPD_401_UNAUTHORIZED, + + /* The client does not have access rights to the content, + * so the server is refusing to give the requested resource. + * Unlike 401, the client's identity is known to the server. + */ + HTTPD_403_FORBIDDEN, + + /* When requested URI is not found */ + HTTPD_404_NOT_FOUND, + + /* When URI found, but method has no handler registered */ + HTTPD_405_METHOD_NOT_ALLOWED, + + /* Intended for recv timeout. Presently it's being sent + * for other recv errors as well. Client should expect the + * server to immediately close the connection after + * responding with this. + */ + HTTPD_408_REQ_TIMEOUT, + + /* Intended for responding to chunked encoding, which is + * not supported currently. Though unhandled http_parser + * callback for chunked request returns "400 Bad Request" + */ + HTTPD_411_LENGTH_REQUIRED, + + /* URI length greater than CONFIG_HTTPD_MAX_URI_LEN */ + HTTPD_414_URI_TOO_LONG, + + /* Headers section larger than CONFIG_HTTPD_MAX_REQ_HDR_LEN */ + HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE, + + /* Used internally for retrieving the total count of errors */ + HTTPD_ERR_CODE_MAX +} httpd_err_code_t; + +/** + * @brief Function prototype for HTTP error handling. + * + * This function is executed upon HTTP errors generated during + * internal processing of an HTTP request. This is used to override + * the default behavior on error, which is to send HTTP error response + * and close the underlying socket. + * + * @note + * - If implemented, the server will not automatically send out HTTP + * error response codes, therefore, httpd_resp_send_err() must be + * invoked inside this function if user wishes to generate HTTP + * error responses. + * - When invoked, the validity of `uri`, `method`, `content_len` + * and `user_ctx` fields of the httpd_req_t parameter is not + * guaranteed as the HTTP request may be partially received/parsed. + * - The function must return ESP_OK if underlying socket needs to + * be kept open. Any other value will ensure that the socket is + * closed. The return value is ignored when error is of type + * `HTTPD_500_INTERNAL_SERVER_ERROR` and the socket closed anyway. + * + * @param[in] req HTTP request for which the error needs to be handled + * @param[in] error Error type + * + * @return + * - ESP_OK : error handled successful + * - ESP_FAIL : failure indicates that the underlying socket needs to be closed + */ +typedef esp_err_t (*httpd_err_handler_func_t)(httpd_req_t *req, + httpd_err_code_t error); + +/** + * @brief Function for registering HTTP error handlers + * + * This function maps a handler function to any supported error code + * given by `httpd_err_code_t`. See prototype `httpd_err_handler_func_t` + * above for details. + * + * @param[in] handle HTTP server handle + * @param[in] error Error type + * @param[in] handler_fn User implemented handler function + * (Pass NULL to unset any previously set handler) + * + * @return + * - ESP_OK : handler registered successfully + * - ESP_ERR_INVALID_ARG : invalid error code or server handle + */ +esp_err_t httpd_register_err_handler(httpd_handle_t handle, + httpd_err_code_t error, + httpd_err_handler_func_t handler_fn); + +/** End of HTTP Error + * @} + */ + +/* ************** Group: TX/RX ************** */ +/** @name TX / RX + * Prototype for HTTPDs low-level send/recv functions + * @{ + */ + +#define HTTPD_SOCK_ERR_FAIL -1 +#define HTTPD_SOCK_ERR_INVALID -2 +#define HTTPD_SOCK_ERR_TIMEOUT -3 + +/** + * @brief Prototype for HTTPDs low-level send function + * + * @note User specified send function must handle errors internally, + * depending upon the set value of errno, and return specific + * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as + * return value of httpd_send() function + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @param[in] buf buffer with bytes to send + * @param[in] buf_len data size + * @param[in] flags flags for the send() function + * @return + * - Bytes : The number of bytes sent successfully + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() + */ +typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags); + +/** + * @brief Prototype for HTTPDs low-level recv function + * + * @note User specified recv function must handle errors internally, + * depending upon the set value of errno, and return specific + * HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as + * return value of httpd_req_recv() function + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @param[in] buf buffer with bytes to send + * @param[in] buf_len data size + * @param[in] flags flags for the send() function + * @return + * - Bytes : The number of bytes received successfully + * - 0 : Buffer length parameter is zero / connection closed by peer + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() + */ +typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags); + +/** + * @brief Prototype for HTTPDs low-level "get pending bytes" function + * + * @note User specified pending function must handle errors internally, + * depending upon the set value of errno, and return specific + * HTTPD_SOCK_ERR_ codes, which will be handled accordingly in + * the server task. + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @return + * - Bytes : The number of bytes waiting to be received + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket pending() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket pending() + */ +typedef int (*httpd_pending_func_t)(httpd_handle_t hd, int sockfd); + +/** End of TX / RX + * @} + */ + +/* ************** Group: Request/Response ************** */ +/** @name Request / Response + * APIs related to the data send/receive by URI handlers. + * These APIs are supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * @{ + */ + +/** + * @brief Override web server's receive function (by session FD) + * + * This function overrides the web server's receive function. This same function is + * used to read HTTP request packets. + * + * @note This API is supposed to be called either from the context of + * - an http session APIs where sockfd is a valid parameter + * - a URI handler where sockfd is obtained using httpd_req_to_sockfd() + * + * @param[in] hd HTTPD instance handle + * @param[in] sockfd Session socket FD + * @param[in] recv_func The receive function to be set for this session + * + * @return + * - ESP_OK : On successfully registering override + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func); + +/** + * @brief Override web server's send function (by session FD) + * + * This function overrides the web server's send function. This same function is + * used to send out any response to any HTTP request. + * + * @note This API is supposed to be called either from the context of + * - an http session APIs where sockfd is a valid parameter + * - a URI handler where sockfd is obtained using httpd_req_to_sockfd() + * + * @param[in] hd HTTPD instance handle + * @param[in] sockfd Session socket FD + * @param[in] send_func The send function to be set for this session + * + * @return + * - ESP_OK : On successfully registering override + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func); + +/** + * @brief Override web server's pending function (by session FD) + * + * This function overrides the web server's pending function. This function is + * used to test for pending bytes in a socket. + * + * @note This API is supposed to be called either from the context of + * - an http session APIs where sockfd is a valid parameter + * - a URI handler where sockfd is obtained using httpd_req_to_sockfd() + * + * @param[in] hd HTTPD instance handle + * @param[in] sockfd Session socket FD + * @param[in] pending_func The receive function to be set for this session + * + * @return + * - ESP_OK : On successfully registering override + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func); + +/** + * @brief Get the Socket Descriptor from the HTTP request + * + * This API will return the socket descriptor of the session for + * which URI handler was executed on reception of HTTP request. + * This is useful when user wants to call functions that require + * session socket fd, from within a URI handler, ie. : + * httpd_sess_get_ctx(), + * httpd_sess_trigger_close(), + * httpd_sess_update_lru_counter(). + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * + * @param[in] r The request whose socket descriptor should be found + * + * @return + * - Socket descriptor : The socket descriptor for this request + * - -1 : Invalid/NULL request pointer + */ +int httpd_req_to_sockfd(httpd_req_t *r); + +/** + * @brief API to read content data from the HTTP request + * + * This API will read HTTP content data from the HTTP request into + * provided buffer. Use content_len provided in httpd_req_t structure + * to know the length of data to be fetched. If content_len is too + * large for the buffer then user may have to make multiple calls to + * this function, each time fetching 'buf_len' number of bytes, + * while the pointer to content data is incremented internally by + * the same number. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - If an error is returned, the URI handler must further return an error. + * This will ensure that the erroneous socket is closed and cleaned up by + * the web server. + * - Presently Chunked Encoding is not supported + * + * @param[in] r The request being responded to + * @param[in] buf Pointer to a buffer that the data will be read into + * @param[in] buf_len Length of the buffer + * + * @return + * - Bytes : Number of bytes read into the buffer successfully + * - 0 : Buffer length parameter is zero / connection closed by peer + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() + */ +int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len); + +/** + * @brief Search for a field in request headers and + * return the string length of it's value + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once httpd_resp_send() API is called all request headers + * are purged, so request headers need be copied into separate + * buffers if they are required later. + * + * @param[in] r The request being responded to + * @param[in] field The header field to be searched in the request + * + * @return + * - Length : If field is found in the request URL + * - Zero : Field not found / Invalid request / Null arguments + */ +size_t httpd_req_get_hdr_value_len(httpd_req_t *r, const char *field); + +/** + * @brief Get the value string of a field from the request headers + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once httpd_resp_send() API is called all request headers + * are purged, so request headers need be copied into separate + * buffers if they are required later. + * - If output size is greater than input, then the value is truncated, + * accompanied by truncation error as return value. + * - Use httpd_req_get_hdr_value_len() to know the right buffer length + * + * @param[in] r The request being responded to + * @param[in] field The field to be searched in the header + * @param[out] val Pointer to the buffer into which the value will be copied if the field is found + * @param[in] val_size Size of the user buffer "val" + * + * @return + * - ESP_OK : Field found in the request header and value string copied + * - ESP_ERR_NOT_FOUND : Key not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer + * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated + */ +esp_err_t httpd_req_get_hdr_value_str(httpd_req_t *r, const char *field, char *val, size_t val_size); + +/** + * @brief Get Query string length from the request URL + * + * @note This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid + * + * @param[in] r The request being responded to + * + * @return + * - Length : Query is found in the request URL + * - Zero : Query not found / Null arguments / Invalid request + */ +size_t httpd_req_get_url_query_len(httpd_req_t *r); + +/** + * @brief Get Query string from the request URL + * + * @note + * - Presently, the user can fetch the full URL query string, but decoding + * will have to be performed by the user. Request headers can be read using + * httpd_req_get_hdr_value_str() to know the 'Content-Type' (eg. Content-Type: + * application/x-www-form-urlencoded) and then the appropriate decoding + * algorithm needs to be applied. + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid + * - If output size is greater than input, then the value is truncated, + * accompanied by truncation error as return value + * - Prior to calling this function, one can use httpd_req_get_url_query_len() + * to know the query string length beforehand and hence allocate the buffer + * of right size (usually query string length + 1 for null termination) + * for storing the query string + * + * @param[in] r The request being responded to + * @param[out] buf Pointer to the buffer into which the query string will be copied (if found) + * @param[in] buf_len Length of output buffer + * + * @return + * - ESP_OK : Query is found in the request URL and copied to buffer + * - ESP_ERR_NOT_FOUND : Query not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid HTTP request pointer + * - ESP_ERR_HTTPD_RESULT_TRUNC : Query string truncated + */ +esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len); + +/** + * @brief Helper function to get a URL query tag from a query + * string of the type param1=val1¶m2=val2 + * + * @note + * - The components of URL query string (keys and values) are not URLdecoded. + * The user must check for 'Content-Type' field in the request headers and + * then depending upon the specified encoding (URLencoded or otherwise) apply + * the appropriate decoding algorithm. + * - If actual value size is greater than val_size, then the value is truncated, + * accompanied by truncation error as return value. + * + * @param[in] qry Pointer to query string + * @param[in] key The key to be searched in the query string + * @param[out] val Pointer to the buffer into which the value will be copied if the key is found + * @param[in] val_size Size of the user buffer "val" + * + * @return + * - ESP_OK : Key is found in the URL query string and copied to buffer + * - ESP_ERR_NOT_FOUND : Key not found + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESULT_TRUNC : Value string truncated + */ +esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size); + +/** + * @brief Test if a URI matches the given wildcard template. + * + * Template may end with "?" to make the previous character optional (typically a slash), + * "*" for a wildcard match, and "?*" to make the previous character optional, and if present, + * allow anything to follow. + * + * Example: + * - * matches everything + * - /foo/? matches /foo and /foo/ + * - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo + * - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo + * + * The special characters "?" and "*" anywhere else in the template will be taken literally. + * + * @param[in] uri_template URI template (pattern) + * @param[in] uri_to_match URI to be matched + * @param[in] match_upto how many characters of the URI buffer to test + * (there may be trailing query string etc.) + * + * @return true if a match was found + */ +bool httpd_uri_match_wildcard(const char *uri_template, const char *uri_to_match, size_t match_upto); + +/** + * @brief API to send a complete HTTP response. + * + * This API will send the data as an HTTP response to the request. + * This assumes that you have the entire response ready in a single + * buffer. If you wish to send response in incremental chunks use + * httpd_resp_send_chunk() instead. + * + * If no status code and content-type were set, by default this + * will send 200 OK status code and content type as text/html. + * You may call the following functions before this API to configure + * the response headers : + * httpd_resp_set_status() - for setting the HTTP status string, + * httpd_resp_set_type() - for setting the Content Type, + * httpd_resp_set_hdr() - for appending any additional field + * value entries in the response header + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, the request has been responded to. + * - No additional data can then be sent for the request. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * @param[in] buf Buffer from where the content is to be fetched + * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request + */ +esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len); + +/** + * @brief API to send one HTTP chunk + * + * This API will send the data as an HTTP response to the + * request. This API will use chunked-encoding and send the response + * in the form of chunks. If you have the entire response contained in + * a single buffer, please use httpd_resp_send() instead. + * + * If no status code and content-type were set, by default this will + * send 200 OK status code and content type as text/html. You may + * call the following functions before this API to configure the + * response headers + * httpd_resp_set_status() - for setting the HTTP status string, + * httpd_resp_set_type() - for setting the Content Type, + * httpd_resp_set_hdr() - for appending any additional field + * value entries in the response header + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - When you are finished sending all your chunks, you must call + * this function with buf_len as 0. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if they + * are required later. + * + * @param[in] r The request being responded to + * @param[in] buf Pointer to a buffer that stores the data + * @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen() + * + * @return + * - ESP_OK : On successfully sending the response packet chunk + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len); + +/** + * @brief API to send a complete string as HTTP response. + * + * This API simply calls http_resp_send with buffer length + * set to string length assuming the buffer contains a null + * terminated string + * + * @param[in] r The request being responded to + * @param[in] str String to be sent as response body + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request + */ +static inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) { + return httpd_resp_send(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN); +} + +/** + * @brief API to send a string as an HTTP response chunk. + * + * This API simply calls http_resp_send_chunk with buffer length + * set to string length assuming the buffer contains a null + * terminated string + * + * @param[in] r The request being responded to + * @param[in] str String to be sent as response body (NULL to finish response packet) + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null request pointer + * - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request + */ +static inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) { + return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : HTTPD_RESP_USE_STRLEN); +} + +/* Some commonly used status codes */ +#define HTTPD_200 "200 OK" /*!< HTTP Response 200 */ +#define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */ +#define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */ +#define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */ +#define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */ +#define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */ +#define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */ + +/** + * @brief API to set the HTTP status code + * + * This API sets the status of the HTTP response to the value specified. + * By default, the '200 OK' response is sent as the response. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - This API only sets the status to this value. The status isn't + * sent out until any of the send APIs is executed. + * - Make sure that the lifetime of the status string is valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] status The HTTP status code of this response + * + * @return + * - ESP_OK : On success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status); + +/* Some commonly used content types */ +#define HTTPD_TYPE_JSON "application/json" /*!< HTTP Content type JSON */ +#define HTTPD_TYPE_TEXT "text/html" /*!< HTTP Content type text/HTML */ +#define HTTPD_TYPE_OCTET "application/octet-stream" /*!< HTTP Content type octext-stream */ + +/** + * @brief API to set the HTTP content type + * + * This API sets the 'Content Type' field of the response. + * The default content type is 'text/html'. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - This API only sets the content type to this value. The type + * isn't sent out until any of the send APIs is executed. + * - Make sure that the lifetime of the type string is valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] type The Content Type of the response + * + * @return + * - ESP_OK : On success + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type); + +/** + * @brief API to append any additional headers + * + * This API sets any additional header fields that need to be sent in the response. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - The header isn't sent out until any of the send APIs is executed. + * - The maximum allowed number of additional headers is limited to + * value of max_resp_headers in config structure. + * - Make sure that the lifetime of the field value strings are valid till + * send function is called. + * + * @param[in] r The request being responded to + * @param[in] field The field name of the HTTP header + * @param[in] value The value of this HTTP header + * + * @return + * - ESP_OK : On successfully appending new header + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_HDR : Total additional headers exceed max allowed + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value); + +/** + * @brief For sending out error code in response to HTTP request. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * - If you wish to send additional data in the body of the + * response, please use the lower-level functions directly. + * + * @param[in] req Pointer to the HTTP request for which the response needs to be sent + * @param[in] error Error type to send + * @param[in] msg Error message string (pass NULL for default message) + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg); + +/** + * @brief Helper function for HTTP 404 + * + * Send HTTP 404 message. If you wish to send additional data in the body of the + * response, please use the lower-level functions directly. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) { + return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL); +} + +/** + * @brief Helper function for HTTP 408 + * + * Send HTTP 408 message. If you wish to send additional data in the body of the + * response, please use the lower-level functions directly. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +static inline esp_err_t httpd_resp_send_408(httpd_req_t *r) { + return httpd_resp_send_err(r, HTTPD_408_REQ_TIMEOUT, NULL); +} + +/** + * @brief Helper function for HTTP 500 + * + * Send HTTP 500 message. If you wish to send additional data in the body of the + * response, please use the lower-level functions directly. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Once this API is called, all request headers are purged, so + * request headers need be copied into separate buffers if + * they are required later. + * + * @param[in] r The request being responded to + * + * @return + * - ESP_OK : On successfully sending the response packet + * - ESP_ERR_INVALID_ARG : Null arguments + * - ESP_ERR_HTTPD_RESP_SEND : Error in raw send + * - ESP_ERR_HTTPD_INVALID_REQ : Invalid request pointer + */ +static inline esp_err_t httpd_resp_send_500(httpd_req_t *r) { + return httpd_resp_send_err(r, HTTPD_500_INTERNAL_SERVER_ERROR, NULL); +} + +/** + * @brief Raw HTTP send + * + * Call this API if you wish to construct your custom response packet. + * When using this, all essential header, eg. HTTP version, Status Code, + * Content Type and Length, Encoding, etc. will have to be constructed + * manually, and HTTP delimeters (CRLF) will need to be placed correctly + * for separating sub-sections of the HTTP response packet. + * + * If the send override function is set, this API will end up + * calling that function eventually to send data out. + * + * @note + * - This API is supposed to be called only from the context of + * a URI handler where httpd_req_t* request pointer is valid. + * - Unless the response has the correct HTTP structure (which the + * user must now ensure) it is not guaranteed that it will be + * recognized by the client. For most cases, you wouldn't have + * to call this API, but you would rather use either of : + * httpd_resp_send(), + * httpd_resp_send_chunk() + * + * @param[in] r The request being responded to + * @param[in] buf Buffer from where the fully constructed packet is to be read + * @param[in] buf_len Length of the buffer + * + * @return + * - Bytes : Number of bytes that were sent successfully + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() + */ +int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len); + +/** + * A low level API to send data on a given socket + * + * @note This API is not recommended to be used in any request handler. + * Use this only for advanced use cases, wherein some asynchronous + * data is to be sent over a socket. + * + * This internally calls the default send function, or the function registered by + * httpd_sess_set_send_override(). + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @param[in] buf buffer with bytes to send + * @param[in] buf_len data size + * @param[in] flags flags for the send() function + * @return + * - Bytes : The number of bytes sent successfully + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket send() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket send() + */ +int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags); + +/** + * A low level API to receive data from a given socket + * + * @note This API is not recommended to be used in any request handler. + * Use this only for advanced use cases, wherein some asynchronous + * communication is required. + * + * This internally calls the default recv function, or the function registered by + * httpd_sess_set_recv_override(). + * + * @param[in] hd server instance + * @param[in] sockfd session socket file descriptor + * @param[in] buf buffer with bytes to send + * @param[in] buf_len data size + * @param[in] flags flags for the send() function + * @return + * - Bytes : The number of bytes received successfully + * - 0 : Buffer length parameter is zero / connection closed by peer + * - HTTPD_SOCK_ERR_INVALID : Invalid arguments + * - HTTPD_SOCK_ERR_TIMEOUT : Timeout/interrupted while calling socket recv() + * - HTTPD_SOCK_ERR_FAIL : Unrecoverable error while calling socket recv() + */ +int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags); + +/** End of Request / Response + * @} + */ + +/* ************** Group: Session ************** */ +/** @name Session + * Functions for controlling sessions and accessing context data + * @{ + */ + +/** + * @brief Get session context from socket descriptor + * + * Typically if a session context is created, it is available to URI handlers + * through the httpd_req_t structure. But, there are cases where the web + * server's send/receive functions may require the context (for example, for + * accessing keying information etc). Since the send/receive function only have + * the socket descriptor at their disposal, this API provides them with a way to + * retrieve the session context. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor for which the context should be extracted. + * + * @return + * - void* : Pointer to the context associated with this session + * - NULL : Empty context / Invalid handle / Invalid socket fd + */ +void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd); + +/** + * @brief Set session context by socket descriptor + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor for which the context should be extracted. + * @param[in] ctx Context object to assign to the session + * @param[in] free_fn Function that should be called to free the context + */ +void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn); + +/** + * @brief Get session 'transport' context by socket descriptor + * @see httpd_sess_get_ctx() + * + * This context is used by the send/receive functions, for example to manage SSL context. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor for which the context should be extracted. + * @return + * - void* : Pointer to the transport context associated with this session + * - NULL : Empty context / Invalid handle / Invalid socket fd + */ +void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd); + +/** + * @brief Set session 'transport' context by socket descriptor + * @see httpd_sess_set_ctx() + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor for which the context should be extracted. + * @param[in] ctx Transport context object to assign to the session + * @param[in] free_fn Function that should be called to free the transport context + */ +void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn); + +/** + * @brief Get HTTPD global user context (it was set in the server config struct) + * + * @param[in] handle Handle to server returned by httpd_start + * @return global user context + */ +void *httpd_get_global_user_ctx(httpd_handle_t handle); + +/** + * @brief Get HTTPD global transport context (it was set in the server config struct) + * + * @param[in] handle Handle to server returned by httpd_start + * @return global transport context + */ +void *httpd_get_global_transport_ctx(httpd_handle_t handle); + +/** + * @brief Trigger an httpd session close externally + * + * @note Calling this API is only required in special circumstances wherein + * some application requires to close an httpd client session asynchronously. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor of the session to be closed + * + * @return + * - ESP_OK : On successfully initiating closure + * - ESP_FAIL : Failure to queue work + * - ESP_ERR_NOT_FOUND : Socket fd not found + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd); + +/** + * @brief Update LRU counter for a given socket + * + * LRU Counters are internally associated with each session to monitor + * how recently a session exchanged traffic. When LRU purge is enabled, + * if a client is requesting for connection but maximum number of + * sockets/sessions is reached, then the session having the earliest + * LRU counter is closed automatically. + * + * Updating the LRU counter manually prevents the socket from being purged + * due to the Least Recently Used (LRU) logic, even though it might not + * have received traffic for some time. This is useful when all open + * sockets/session are frequently exchanging traffic but the user specifically + * wants one of the sessions to be kept open, irrespective of when it last + * exchanged a packet. + * + * @note Calling this API is only necessary if the LRU Purge Enable option + * is enabled. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] sockfd The socket descriptor of the session for which LRU counter + * is to be updated + * + * @return + * - ESP_OK : Socket found and LRU counter updated + * - ESP_ERR_NOT_FOUND : Socket not found + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd); + +/** + * @brief Returns list of current socket descriptors of active sessions + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in,out] fds In: Size of provided client_fds array + * Out: Number of valid client fds returned in client_fds, + * @param[out] client_fds Array of client fds + * + * @note Size of provided array has to be equal or greater then maximum number of opened + * sockets, configured upon initialization with max_open_sockets field in + * httpd_config_t structure. + * + * @return + * - ESP_OK : Successfully retrieved session list + * - ESP_ERR_INVALID_ARG : Wrong arguments or list is longer than provided array + */ +esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds); + +/** End of Session + * @} + */ + +/* ************** Group: Work Queue ************** */ +/** @name Work Queue + * APIs related to the HTTPD Work Queue + * @{ + */ + +/** + * @brief Prototype of the HTTPD work function + * Please refer to httpd_queue_work() for more details. + * @param[in] arg The arguments for this work function + */ +typedef void (*httpd_work_fn_t)(void *arg); + +/** + * @brief Queue execution of a function in HTTPD's context + * + * This API queues a work function for asynchronous execution + * + * @note Some protocols require that the web server generate some asynchronous data + * and send it to the persistently opened connection. This facility is for use + * by such protocols. + * + * @param[in] handle Handle to server returned by httpd_start + * @param[in] work Pointer to the function to be executed in the HTTPD's context + * @param[in] arg Pointer to the arguments that should be passed to this function + * + * @return + * - ESP_OK : On successfully queueing the work + * - ESP_FAIL : Failure in ctrl socket + * - ESP_ERR_INVALID_ARG : Null arguments + */ +esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg); + +/** End of Group Work Queue + * @} + */ + +/* ************** Group: WebSocket ************** */ +/** @name WebSocket + * Functions and structs for WebSocket server + * @{ + */ +#ifdef CONFIG_HTTPD_WS_SUPPORT +/** + * @brief Enum for WebSocket packet types (Opcode in the header) + * @note Please refer to RFC6455 Section 5.4 for more details + */ +typedef enum { + HTTPD_WS_TYPE_CONTINUE = 0x0, + HTTPD_WS_TYPE_TEXT = 0x1, + HTTPD_WS_TYPE_BINARY = 0x2, + HTTPD_WS_TYPE_CLOSE = 0x8, + HTTPD_WS_TYPE_PING = 0x9, + HTTPD_WS_TYPE_PONG = 0xA +} httpd_ws_type_t; + +/** + * @brief Enum for client info description + */ +typedef enum { + HTTPD_WS_CLIENT_INVALID = 0x0, + HTTPD_WS_CLIENT_HTTP = 0x1, + HTTPD_WS_CLIENT_WEBSOCKET = 0x2, +} httpd_ws_client_info_t; + +/** + * @brief WebSocket frame format + */ +typedef struct httpd_ws_frame { + bool final; /*!< Final frame: + For received frames this field indicates whether the `FIN` flag was set. + For frames to be transmitted, this field is only used if the `fragmented` + option is set as well. If `fragmented` is false, the `FIN` flag is set + by default, marking the ws_frame as a complete/unfragmented message + (esp_http_server doesn't automatically fragment messages) */ + bool fragmented; /*!< Indication that the frame allocated for transmission is a message fragment, + so the `FIN` flag is set manually according to the `final` option. + This flag is never set for received messages */ + httpd_ws_type_t type; /*!< WebSocket frame type */ + uint8_t *payload; /*!< Pre-allocated data buffer */ + size_t len; /*!< Length of the WebSocket data */ +} httpd_ws_frame_t; + +/** + * @brief Receive and parse a WebSocket frame + * + * @note Calling httpd_ws_recv_frame() with max_len as 0 will give actual frame size in pkt->len. + * The user can dynamically allocate space for pkt->payload as per this length and call httpd_ws_recv_frame() again to get the actual data. + * Please refer to the corresponding example for usage. + * + * @param[in] req Current request + * @param[out] pkt WebSocket packet + * @param[in] max_len Maximum length for receive + * @return + * - ESP_OK : On successful + * - ESP_FAIL : Socket errors occurs + * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand + * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket) + */ +esp_err_t httpd_ws_recv_frame(httpd_req_t *req, httpd_ws_frame_t *pkt, size_t max_len); + +/** + * @brief Construct and send a WebSocket frame + * @param[in] req Current request + * @param[in] pkt WebSocket frame + * @return + * - ESP_OK : On successful + * - ESP_FAIL : When socket errors occurs + * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand + * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket) + */ +esp_err_t httpd_ws_send_frame(httpd_req_t *req, httpd_ws_frame_t *pkt); + +/** + * @brief Low level send of a WebSocket frame out of the scope of current request + * using internally configured httpd send function + * + * This API should rarely be called directly, with an exception of asynchronous send using httpd_queue_work. + * + * @param[in] hd Server instance data + * @param[in] fd Socket descriptor for sending data + * @param[in] frame WebSocket frame + * @return + * - ESP_OK : On successful + * - ESP_FAIL : When socket errors occurs + * - ESP_ERR_INVALID_STATE : Handshake was already done beforehand + * - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket) + */ +esp_err_t httpd_ws_send_frame_async(httpd_handle_t hd, int fd, httpd_ws_frame_t *frame); + +/** + * @brief Checks the supplied socket descriptor if it belongs to any active client + * of this server instance and if the websoket protocol is active + * + * @param[in] hd Server instance data + * @param[in] fd Socket descriptor + * @return + * - HTTPD_WS_CLIENT_INVALID : This fd is not a client of this httpd + * - HTTPD_WS_CLIENT_HTTP : This fd is an active client, protocol is not WS + * - HTTPD_WS_CLIENT_WEBSOCKET : This fd is an active client, protocol is WS + */ +httpd_ws_client_info_t httpd_ws_get_fd_info(httpd_handle_t hd, int fd); + +#endif /* CONFIG_HTTPD_WS_SUPPORT */ +/** End of WebSocket related stuff + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* ! _ESP_HTTP_SERVER_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_http_server/include/http_server.h b/tools/sdk/esp32c3/include/esp_http_server/include/http_server.h new file mode 100644 index 00000000..56f73c5b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_http_server/include/http_server.h @@ -0,0 +1,2 @@ +#warning http_server.h has been renamed to esp_http_server.h, please update include directives +#include "esp_http_server.h" diff --git a/tools/sdk/esp32c3/include/esp_https_ota/include/esp_https_ota.h b/tools/sdk/esp32c3/include/esp_https_ota/include/esp_https_ota.h new file mode 100644 index 00000000..2a987ca6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_https_ota/include/esp_https_ota.h @@ -0,0 +1,206 @@ +// Copyright 2017-2018 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void *esp_https_ota_handle_t; +typedef esp_err_t(*http_client_init_cb_t)(esp_http_client_handle_t); + +/** + * @brief ESP HTTPS OTA configuration + */ +typedef struct { + const esp_http_client_config_t *http_config; /*!< ESP HTTP client configuration */ + http_client_init_cb_t http_client_init_cb; /*!< Callback after ESP HTTP client is initialised */ + bool bulk_flash_erase; /*!< Erase entire flash partition during initialization. By default flash partition is erased during write operation and in chunk of 4K sector size */ + bool partial_http_download; /*!< Enable Firmware image to be downloaded over multiple HTTP requests */ + int max_http_request_size; /*!< Maximum request size for partial HTTP download */ +} esp_https_ota_config_t; + +#define ESP_ERR_HTTPS_OTA_BASE (0x9000) +#define ESP_ERR_HTTPS_OTA_IN_PROGRESS (ESP_ERR_HTTPS_OTA_BASE + 1) /* OTA operation in progress */ + +/** + * @brief HTTPS OTA Firmware upgrade. + * + * This function allocates HTTPS OTA Firmware upgrade context, establishes HTTPS connection, + * reads image data from HTTP stream and writes it to OTA partition and + * finishes HTTPS OTA Firmware upgrade operation. + * This API supports URL redirection, but if CA cert of URLs differ then it + * should be appended to `cert_pem` member of `config`. + * + * @param[in] config pointer to esp_http_client_config_t structure. + * + * @note This API handles the entire OTA operation, so if this API is being used + * then no other APIs from `esp_https_ota` component should be called. + * If more information and control is needed during the HTTPS OTA process, + * then one can use `esp_https_ota_begin` and subsequent APIs. If this API returns + * successfully, esp_restart() must be called to boot from the new firmware image. + * + * @return + * - ESP_OK: OTA data updated, next reboot will use specified partition. + * - ESP_FAIL: For generic failure. + * - ESP_ERR_INVALID_ARG: Invalid argument + * - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image + * - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - For other return codes, refer OTA documentation in esp-idf's app_update component. + */ +esp_err_t esp_https_ota(const esp_http_client_config_t *config); + +/** + * @brief Start HTTPS OTA Firmware upgrade + * + * This function initializes ESP HTTPS OTA context and establishes HTTPS connection. + * This function must be invoked first. If this function returns successfully, then `esp_https_ota_perform` should be + * called to continue with the OTA process and there should be a call to `esp_https_ota_finish` on + * completion of OTA operation or on failure in subsequent operations. + * This API supports URL redirection, but if CA cert of URLs differ then it + * should be appended to `cert_pem` member of `http_config`, which is a part of `ota_config`. + * In case of error, this API explicitly sets `handle` to NULL. + * + * @param[in] ota_config pointer to esp_https_ota_config_t structure + * @param[out] handle pointer to an allocated data of type `esp_https_ota_handle_t` + * which will be initialised in this function + * + * @note This API is blocking, so setting `is_async` member of `http_config` structure will + * result in an error. + * + * @return + * - ESP_OK: HTTPS OTA Firmware upgrade context initialised and HTTPS connection established + * - ESP_FAIL: For generic failure. + * - ESP_ERR_INVALID_ARG: Invalid argument (missing/incorrect config, certificate, etc.) + * - For other return codes, refer documentation in app_update component and esp_http_client + * component in esp-idf. + */ +esp_err_t esp_https_ota_begin(esp_https_ota_config_t *ota_config, esp_https_ota_handle_t *handle); + +/** + * @brief Read image data from HTTP stream and write it to OTA partition + * + * This function reads image data from HTTP stream and writes it to OTA partition. This function + * must be called only if esp_https_ota_begin() returns successfully. + * This function must be called in a loop since it returns after every HTTP read operation thus + * giving you the flexibility to stop OTA operation midway. + * + * @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure + * + * @return + * - ESP_ERR_HTTPS_OTA_IN_PROGRESS: OTA update is in progress, call this API again to continue. + * - ESP_OK: OTA update was successful + * - ESP_FAIL: OTA update failed + * - ESP_ERR_INVALID_ARG: Invalid argument + * - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image + * - ESP_ERR_NO_MEM: Cannot allocate memory for OTA operation. + * - ESP_ERR_FLASH_OP_TIMEOUT or ESP_ERR_FLASH_OP_FAIL: Flash write failed. + * - For other return codes, refer OTA documentation in esp-idf's app_update component. + */ +esp_err_t esp_https_ota_perform(esp_https_ota_handle_t https_ota_handle); + +/** + * @brief Checks if complete data was received or not + * + * @note This API can be called just before esp_https_ota_finish() to validate if the complete image was indeed received. + * + * @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure + * + * @return + * - false + * - true + */ +bool esp_https_ota_is_complete_data_received(esp_https_ota_handle_t https_ota_handle); + +/** + * @brief Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection + * + * This function closes the HTTP connection and frees the ESP HTTPS OTA context. + * This function switches the boot partition to the OTA partition containing the + * new firmware image. + * + * @note If this API returns successfully, esp_restart() must be called to + * boot from the new firmware image + * esp_https_ota_finish should not be called after calling esp_https_ota_abort + * + * @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure + * + * @return + * - ESP_OK: Clean-up successful + * - ESP_ERR_INVALID_STATE + * - ESP_ERR_INVALID_ARG: Invalid argument + * - ESP_ERR_OTA_VALIDATE_FAILED: Invalid app image + */ +esp_err_t esp_https_ota_finish(esp_https_ota_handle_t https_ota_handle); + + +/** + * @brief Clean-up HTTPS OTA Firmware upgrade and close HTTPS connection + * + * This function closes the HTTP connection and frees the ESP HTTPS OTA context. + * + * @note esp_https_ota_abort should not be called after calling esp_https_ota_finish + * + * @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure + * + * @return + * - ESP_OK: Clean-up successful + * - ESP_ERR_INVALID_STATE: Invalid ESP HTTPS OTA state + * - ESP_FAIL: OTA not started + * - ESP_ERR_NOT_FOUND: OTA handle not found + * - ESP_ERR_INVALID_ARG: Invalid argument + */ +esp_err_t esp_https_ota_abort(esp_https_ota_handle_t https_ota_handle); + + +/** + * @brief Reads app description from image header. The app description provides information + * like the "Firmware version" of the image. + * + * @note This API can be called only after esp_https_ota_begin() and before esp_https_ota_perform(). + * Calling this API is not mandatory. + * + * @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure + * @param[out] new_app_info pointer to an allocated esp_app_desc_t structure + * + * @return + * - ESP_ERR_INVALID_ARG: Invalid arguments + * - ESP_FAIL: Failed to read image descriptor + * - ESP_OK: Successfully read image descriptor + */ +esp_err_t esp_https_ota_get_img_desc(esp_https_ota_handle_t https_ota_handle, esp_app_desc_t *new_app_info); + + +/** +* @brief This function returns OTA image data read so far. +* +* @note This API should be called only if `esp_https_ota_perform()` has been called atleast once or +* if `esp_https_ota_get_img_desc` has been called before. +* +* @param[in] https_ota_handle pointer to esp_https_ota_handle_t structure +* +* @return +* - -1 On failure +* - total bytes read so far +*/ +int esp_https_ota_get_image_len_read(esp_https_ota_handle_t https_ota_handle); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_https_server/include/esp_https_server.h b/tools/sdk/esp32c3/include/esp_https_server/include/esp_https_server.h new file mode 100644 index 00000000..968e74c6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_https_server/include/esp_https_server.h @@ -0,0 +1,143 @@ +// Copyright 2018 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. + +#ifndef _ESP_HTTPS_SERVER_H_ +#define _ESP_HTTPS_SERVER_H_ + +#include +#include "esp_err.h" +#include "esp_http_server.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + HTTPD_SSL_TRANSPORT_SECURE, // SSL Enabled + HTTPD_SSL_TRANSPORT_INSECURE // SSL disabled +} httpd_ssl_transport_mode_t; + +/** + * HTTPS server config struct + * + * Please use HTTPD_SSL_CONFIG_DEFAULT() to initialize it. + */ +struct httpd_ssl_config { + /** + * Underlying HTTPD server config + * + * Parameters like task stack size and priority can be adjusted here. + */ + httpd_config_t httpd; + + /** CA certificate (here it is treated as server cert) + * Todo: Fix this change in release/v5.0 as it would be a breaking change + * i.e. Rename the nomenclature of variables holding different certs in https_server component as well as example + * 1)The cacert variable should hold the CA which is used to authenticate clients (should inherit current role of client_verify_cert_pem var) + * 2)There should be another variable servercert which whould hold servers own certificate (should inherit current role of cacert var) */ + const uint8_t *cacert_pem; + + /** CA certificate byte length */ + size_t cacert_len; + + /** Client verify authority certificate (CA used to sign clients, or client cert itself */ + const uint8_t *client_verify_cert_pem; + + /** Client verify authority cert len */ + size_t client_verify_cert_len; + + /** Private key */ + const uint8_t *prvtkey_pem; + + /** Private key byte length */ + size_t prvtkey_len; + + /** Transport Mode (default secure) */ + httpd_ssl_transport_mode_t transport_mode; + + /** Port used when transport mode is secure (default 443) */ + uint16_t port_secure; + + /** Port used when transport mode is insecure (default 80) */ + uint16_t port_insecure; +}; + +typedef struct httpd_ssl_config httpd_ssl_config_t; + +/** + * Default config struct init + * + * (http_server default config had to be copied for customization) + * + * Notes: + * - port is set when starting the server, according to 'transport_mode' + * - one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4 + * - SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS + * - Stack size may need adjustments depending on the user application + */ +#define HTTPD_SSL_CONFIG_DEFAULT() { \ + .httpd = { \ + .task_priority = tskIDLE_PRIORITY+5, \ + .stack_size = 10240, \ + .core_id = tskNO_AFFINITY, \ + .server_port = 0, \ + .ctrl_port = 32768, \ + .max_open_sockets = 4, \ + .max_uri_handlers = 8, \ + .max_resp_headers = 8, \ + .backlog_conn = 5, \ + .lru_purge_enable = true, \ + .recv_wait_timeout = 5, \ + .send_wait_timeout = 5, \ + .global_user_ctx = NULL, \ + .global_user_ctx_free_fn = NULL, \ + .global_transport_ctx = NULL, \ + .global_transport_ctx_free_fn = NULL, \ + .open_fn = NULL, \ + .close_fn = NULL, \ + .uri_match_fn = NULL \ + }, \ + .cacert_pem = NULL, \ + .cacert_len = 0, \ + .client_verify_cert_pem = NULL, \ + .client_verify_cert_len = 0, \ + .prvtkey_pem = NULL, \ + .prvtkey_len = 0, \ + .transport_mode = HTTPD_SSL_TRANSPORT_SECURE, \ + .port_secure = 443, \ + .port_insecure = 80, \ +} + +/** + * Create a SSL capable HTTP server (secure mode may be disabled in config) + * + * @param[in,out] config - server config, must not be const. Does not have to stay valid after + * calling this function. + * @param[out] handle - storage for the server handle, must be a valid pointer + * @return success + */ +esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config); + +/** + * Stop the server. Blocks until the server is shut down. + * + * @param[in] handle + */ +void httpd_ssl_stop(httpd_handle_t handle); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_HTTPS_SERVER_H_ diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/esp_cpu.h b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_cpu.h new file mode 100644 index 00000000..e1536e97 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_cpu.h @@ -0,0 +1,109 @@ +// Copyright 2010-2016 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. + +#ifndef _ESP_CPU_H +#define _ESP_CPU_H + +#include +#include +#include + +#include "hal/cpu_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_WATCHPOINT_LOAD 0x40000000 +#define ESP_WATCHPOINT_STORE 0x80000000 +#define ESP_WATCHPOINT_ACCESS 0xC0000000 + +typedef uint32_t esp_cpu_ccount_t; + +/** @brief Read current stack pointer address + * + */ +static inline void *esp_cpu_get_sp(void) +{ + return cpu_hal_get_sp(); +} + +/** + * @brief Stall CPU using RTC controller + * @param cpu_id ID of the CPU to stall (0 = PRO, 1 = APP) + */ +void esp_cpu_stall(int cpu_id); + +/** + * @brief Un-stall CPU using RTC controller + * @param cpu_id ID of the CPU to un-stall (0 = PRO, 1 = APP) + */ +void esp_cpu_unstall(int cpu_id); + +/** + * @brief Reset CPU using RTC controller + * @param cpu_id ID of the CPU to reset (0 = PRO, 1 = APP) + */ +void esp_cpu_reset(int cpu_id); + +/** + * @brief Returns true if a JTAG debugger is attached to CPU + * OCD (on chip debug) port. + * + * @note If "Make exception and panic handlers JTAG/OCD aware" + * is disabled, this function always returns false. + */ +bool esp_cpu_in_ocd_debug_mode(void); + +static inline esp_cpu_ccount_t esp_cpu_get_ccount(void) +{ + return cpu_hal_get_cycle_count(); +} + +static inline void esp_cpu_set_ccount(esp_cpu_ccount_t val) +{ + cpu_hal_set_cycle_count(val); +} + +/** + * @brief Set a watchpoint to break/panic when a certain memory range is accessed. + * + * @param no Watchpoint number. On the ESP32, this can be 0 or 1. + * @param adr Base address to watch + * @param size Size of the region, starting at the base address, to watch. Must + * be one of 2^n, with n in [0..6]. + * @param flags One of ESP_WATCHPOINT_* flags + * + * @return ESP_ERR_INVALID_ARG on invalid arg, ESP_OK otherwise + * + * @warning The ESP32 watchpoint hardware watches a region of bytes by effectively + * masking away the lower n bits for a region with size 2^n. If adr does + * not have zero for these lower n bits, you may not be watching the + * region you intended. + */ +esp_err_t esp_cpu_set_watchpoint(int no, void *adr, int size, int flags); + +/** + * @brief Clear a watchpoint + * + * @param no Watchpoint to clear + * + */ +void esp_cpu_clear_watchpoint(int no); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_CPU_H diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/esp_crc.h b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_crc.h new file mode 100644 index 00000000..6294a7b6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_crc.h @@ -0,0 +1,105 @@ +// Copyright 2015-2019 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. +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +// This header is only a wrapper on ROM CRC API +#include "esp_rom_crc.h" + +/** +* @brief CRC32 value in little endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC32 value +*/ +static inline uint32_t esp_crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc32_le(crc, buf, len); +} + +/** +* @brief CRC32 value in big endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC32 value +*/ +static inline uint32_t esp_crc32_be(uint32_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc32_be(crc, buf, len); +} + +/** +* @brief CRC16 value in little endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC16 value +*/ +static inline uint16_t esp_crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc16_le(crc, buf, len); +} + +/** +* @brief CRC16 value in big endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC16 value +*/ +static inline uint16_t esp_crc16_be(uint16_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc16_be(crc, buf, len); +} + +/** +* @brief CRC8 value in little endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC8 value +*/ +static inline uint8_t esp_crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc8_le(crc, buf, len); +} + +/** +* @brief CRC8 value in big endian. +* +* @param crc: Initial CRC value (result of last calculation or 0 for the first time) +* @param buf: Data buffer that used to calculate the CRC value +* @param len: Length of the data buffer +* @return CRC8 value +*/ +static inline uint8_t esp_crc8_be(uint8_t crc, uint8_t const *buf, uint32_t len) +{ + return esp_rom_crc8_be(crc, buf, len); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/esp_fault.h b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_fault.h new file mode 100644 index 00000000..fe9de334 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_fault.h @@ -0,0 +1,99 @@ +// Copyright 2020 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 "sdkconfig.h" +#include "soc/rtc_cntl_reg.h" +#include "esp_rom_sys.h" + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Assert a condition is true, in a way that should be resistant to fault injection for + * single fault attacks. + * + * - Expands CONDITION multiple times (condition must have no side effects) + * - Compiler is told all registers are invalid before evaluating CONDITION each time, to avoid a fault + * causing a misread of a register used in all three evaluations of CONDITION. + * - If CONDITION is ever false, a system reset is triggered. + * + * @note Place this macro after a "normal" check of CONDITION that will fail with a normal error + * message. This is the fallback in case a fault injection attack skips or corrupts the result of + * that check. (Although ensure that an attacker can't use fault injection to skip past the "normal" + * error message, to avoid this check entirely.) + * + * @note This macro increases binary size and is slow and should be used sparingly. + * + * @note This macro does not guarantee fault injection resistance. In particular CONDITION must be + * chosen carefully - a fault injection attack which sets CONDITION to true will not be detected by + * this macro. Care must also be taken that an attacker can't use a fault to completely bypass calling + * whatever function tests ESP_FAULT_ASSERT. + * + * @note This is difficult to debug as a failure triggers an instant software reset, and UART output + * is often truncated (as FIFO is not flushed). Define the ESP_FAULT_ASSERT_DEBUG macro to debug any + * failures of this macro due to software bugs. + * + * @param CONDITION A condition which will evaluate true unless an attacker used fault injection to skip or corrupt some other critical system calculation. + * + */ +#define ESP_FAULT_ASSERT(CONDITION) do { \ + asm volatile ("" ::: "memory"); \ + if(!(CONDITION)) _ESP_FAULT_RESET(); \ + asm volatile ("" ::: "memory"); \ + if(!(CONDITION)) _ESP_FAULT_RESET(); \ + asm volatile ("" ::: "memory"); \ + if(!(CONDITION)) _ESP_FAULT_RESET(); \ +} while(0) + +#ifndef CONFIG_IDF_TARGET_ARCH_RISCV +#define _ESP_FAULT_ILLEGAL_INSTRUCTION asm volatile("ill.n; ill.n; ill.n; ill.n; ill.n; ill.n; ill.n;") +#else +#define _ESP_FAULT_ILLEGAL_INSTRUCTION asm volatile("unimp; unimp; unimp; unimp; unimp;") +#endif + +// Uncomment this macro to get debug output if ESP_FAULT_ASSERT() fails +// +// Note that uncommenting this macro reduces the anti-FI effectiveness +// +//#define ESP_FAULT_ASSERT_DEBUG + +/* Internal macro, purpose is to trigger a system reset if an inconsistency due to fault injection + is detected. + + Illegal instruction opcodes are there as a fallback to crash the CPU in case it doesn't + reset as expected. +*/ +#ifndef ESP_FAULT_ASSERT_DEBUG + +#define _ESP_FAULT_RESET() do { \ + REG_WRITE(RTC_CNTL_OPTIONS0_REG, RTC_CNTL_SW_SYS_RST); \ + _ESP_FAULT_ILLEGAL_INSTRUCTION; \ + } while(0) + +#else // ESP_FAULT_ASSERT_DEBUG + +#warning "Enabling ESP_FAULT_ASSERT_DEBUG makes ESP_FAULT_ASSERT() less effective" + +#define _ESP_FAULT_RESET() do { \ + esp_rom_printf("ESP_FAULT_ASSERT %s:%d\n", __FILE__, __LINE__); \ + _ESP_FAULT_ILLEGAL_INSTRUCTION; \ + } while(0) + +#endif // ESP_FAULT_ASSERT_DEBUG + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/esp_interface.h b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_interface.h new file mode 100644 index 00000000..950c05bb --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/esp_interface.h @@ -0,0 +1,37 @@ +// Copyright 2015-2016 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. + + +#ifndef __ESP_INTERFACE_H__ +#define __ESP_INTERFACE_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ESP_IF_WIFI_STA = 0, /**< ESP32 station interface */ + ESP_IF_WIFI_AP, /**< ESP32 soft-AP interface */ + ESP_IF_ETH, /**< ESP32 ethernet interface */ + ESP_IF_MAX +} esp_interface_t; + +#ifdef __cplusplus +} +#endif + + +#endif /* __ESP_INTERFACE_TYPES_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc/clk_ctrl_os.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/clk_ctrl_os.h new file mode 100644 index 00000000..f4d769b8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/clk_ctrl_os.h @@ -0,0 +1,50 @@ +// Copyright 2020 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 "soc/rtc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief This function is used to enable the digital 8m rtc clock, + * to support the peripherals. + * + * @note If this function is called a number of times, the `periph_rtc_dig_clk8m_disable` + * function needs to be called same times to disable. + * + * @return true: success for enable the rtc 8M clock, false: rtc 8M clock enable failed + */ +bool periph_rtc_dig_clk8m_enable(void); + +/** + * @brief This function is used to disable the rtc digital clock, which should be called + * with the `periph_rtc_dig_clk8m_enable` pairedly + * + * @note If this function is called a number of times, the `periph_rtc_dig_clk8m_disable` + * function needs to be called same times to disable. + */ +void periph_rtc_dig_clk8m_disable(void); + +/** + * @brief This function is used to get the real clock frequency value of the rtc clock + * + * @return The real clock value + */ +uint32_t periph_rtc_dig_clk8m_get_freq(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc/compare_set.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/compare_set.h new file mode 100644 index 00000000..5a11ab16 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/compare_set.h @@ -0,0 +1,74 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include +#include +#include "soc/cpu.h" +#include "soc/soc_memory_layout.h" + +#if __XTENSA__ +#include "xtensa/xtruntime.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +static inline void __attribute__((always_inline)) compare_and_set_native(volatile uint32_t *addr, uint32_t compare, uint32_t *set) +{ +#if (XCHAL_HAVE_S32C1I > 0) + __asm__ __volatile__ ( + "WSR %2,SCOMPARE1 \n" + "S32C1I %0, %1, 0 \n" + :"=r"(*set) + :"r"(addr), "r"(compare), "0"(*set) + ); +#else + uint32_t old_value; + +#ifdef __XTENSA__ + // No S32C1I, so do this by disabling and re-enabling interrupts (slower) + uint32_t intlevel; + __asm__ __volatile__ ("rsil %0, " XTSTR(XCHAL_EXCM_LEVEL) "\n" + : "=r"(intlevel)); +#else + unsigned old_mstatus = RV_CLEAR_CSR(mstatus, MSTATUS_MIE); +#endif + + old_value = *addr; + if (old_value == compare) { + *addr = *set; + } + +#ifdef __XTENSA__ + __asm__ __volatile__ ("memw \n" + "wsr %0, ps\n" + :: "r"(intlevel)); + +#else + RV_SET_CSR(mstatus, old_mstatus & MSTATUS_MIE); +#endif + + *set = old_value; +#endif +} + + +void compare_and_set_extram(volatile uint32_t *addr, uint32_t compare, uint32_t *set); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc/cpu.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/cpu.h new file mode 100644 index 00000000..0e4d1688 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/cpu.h @@ -0,0 +1,66 @@ +// Copyright 2010-2016 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. + +#ifndef _SOC_CPU_H +#define _SOC_CPU_H + +#include +#include +#include + +#include "esp_cpu.h" + +#if __XTENSA__ +#include "xt_instr_macros.h" +// [refactor-todo] not actually needed in this header now, +// but kept for compatibility +#include "xtensa/corebits.h" +#include "xtensa/config/core.h" + +#include "xtensa/config/specreg.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Read current stack pointer address. + * Superseded by esp_cpu_get_sp in esp_cpu.h. + */ +static inline __attribute__((deprecated)) void *get_sp(void) +{ + return esp_cpu_get_sp(); +} + +static inline uint32_t esp_cpu_process_stack_pc(uint32_t pc) +{ + if (pc & 0x80000000) { + //Top two bits of a0 (return address) specify window increment. Overwrite to map to address space. + pc = (pc & 0x3fffffff) | 0x40000000; + } + //Minus 3 to get PC of previous instruction (i.e. instruction executed before return address) + return pc - 3; +} + +/** + * @brief Configure CPU to disable access to invalid memory regions + * + */ +void esp_cpu_configure_region_protection(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc/rtc_wdt.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/rtc_wdt.h new file mode 100644 index 00000000..7d13e6a4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/rtc_wdt.h @@ -0,0 +1,198 @@ +// Copyright 2018 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. + +/* Recommendation of using API RTC_WDT. +1) Setting and enabling rtc_wdt: +@code + rtc_wdt_protect_off(); + rtc_wdt_disable(); + rtc_wdt_set_length_of_reset_signal(RTC_WDT_SYS_RESET_SIG, RTC_WDT_LENGTH_3_2us); + rtc_wdt_set_stage(RTC_WDT_STAGE0, RTC_WDT_STAGE_ACTION_RESET_SYSTEM); //RTC_WDT_STAGE_ACTION_RESET_SYSTEM or RTC_WDT_STAGE_ACTION_RESET_RTC + rtc_wdt_set_time(RTC_WDT_STAGE0, 7000); // timeout rtd_wdt 7000ms. + rtc_wdt_enable(); + rtc_wdt_protect_on(); + @endcode + +* If you use this option RTC_WDT_STAGE_ACTION_RESET_SYSTEM then after reset you can see these messages. +They can help to understand where the CPUs were when the WDT was triggered. + W (30) boot: PRO CPU has been reset by WDT. + W (30) boot: WDT reset info: PRO CPU PC=0x400xxxxx + ... function where it happened + + W (31) boot: WDT reset info: APP CPU PC=0x400xxxxx + ... function where it happened + +* If you use this option RTC_WDT_STAGE_ACTION_RESET_RTC then you will see message (rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)) +without description where were CPUs when it happened. + +2) Reset counter of rtc_wdt: +@code + rtc_wdt_feed(); +@endcode + +3) Disable rtc_wdt: +@code + rtc_wdt_disable(); +@endcode + */ + +#pragma once +#include +#include +#include "soc/rtc_periph.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/// List of stage of rtc watchdog. WDT has 4 stage. +typedef enum { + RTC_WDT_STAGE0 = 0, /*!< Stage 0 */ + RTC_WDT_STAGE1 = 1, /*!< Stage 1 */ + RTC_WDT_STAGE2 = 2, /*!< Stage 2 */ + RTC_WDT_STAGE3 = 3 /*!< Stage 3 */ +} rtc_wdt_stage_t; + +/// List of action. When the time of stage expires this action will be triggered. +typedef enum { + RTC_WDT_STAGE_ACTION_OFF = RTC_WDT_STG_SEL_OFF, /*!< Disabled. This stage will have no effects on the system. */ + RTC_WDT_STAGE_ACTION_INTERRUPT = RTC_WDT_STG_SEL_INT, /*!< Trigger an interrupt. When the stage expires an interrupt is triggered. */ + RTC_WDT_STAGE_ACTION_RESET_CPU = RTC_WDT_STG_SEL_RESET_CPU, /*!< Reset a CPU core. */ + RTC_WDT_STAGE_ACTION_RESET_SYSTEM = RTC_WDT_STG_SEL_RESET_SYSTEM, /*!< Reset the main system includes the CPU and all peripherals. The RTC is an exception to this, and it will not be reset. */ + RTC_WDT_STAGE_ACTION_RESET_RTC = RTC_WDT_STG_SEL_RESET_RTC /*!< Reset the main system and the RTC. */ +} rtc_wdt_stage_action_t; + +/// Type of reset signal +typedef enum { + RTC_WDT_SYS_RESET_SIG = 0, /*!< System reset signal length selection */ + RTC_WDT_CPU_RESET_SIG = 1 /*!< CPU reset signal length selection */ +} rtc_wdt_reset_sig_t; + +/// Length of reset signal +typedef enum { + RTC_WDT_LENGTH_100ns = 0, /*!< 100 ns */ + RTC_WDT_LENGTH_200ns = 1, /*!< 200 ns */ + RTC_WDT_LENGTH_300ns = 2, /*!< 300 ns */ + RTC_WDT_LENGTH_400ns = 3, /*!< 400 ns */ + RTC_WDT_LENGTH_500ns = 4, /*!< 500 ns */ + RTC_WDT_LENGTH_800ns = 5, /*!< 800 ns */ + RTC_WDT_LENGTH_1_6us = 6, /*!< 1.6 us */ + RTC_WDT_LENGTH_3_2us = 7 /*!< 3.2 us */ +} rtc_wdt_length_sig_t; + +/** + * @brief Get status of protect of rtc_wdt. + * + * @return + * - True if the protect of RTC_WDT is set + */ +bool rtc_wdt_get_protect_status(void); + +/** + * @brief Set protect of rtc_wdt. + */ +void rtc_wdt_protect_on(void); + +/** + * @brief Reset protect of rtc_wdt. + */ +void rtc_wdt_protect_off(void); + +/** + * @brief Enable rtc_wdt. + */ +void rtc_wdt_enable(void); + +/** + * @brief Enable the flash boot protection procedure for WDT. + * + * Do not recommend to use it in the app. + * This function was added to be compatibility with the old bootloaders. + * This mode is disabled in bootloader or using rtc_wdt_disable() function. + */ +void rtc_wdt_flashboot_mode_enable(void); + +/** + * @brief Disable rtc_wdt. + */ +void rtc_wdt_disable(void); + +/** + * @brief Reset counter rtc_wdt. + * + * It returns to stage 0 and its expiry counter restarts from 0. + */ +void rtc_wdt_feed(void); + +/** + * @brief Set time for required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[in] timeout_ms Timeout for this stage. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage has invalid value + */ +esp_err_t rtc_wdt_set_time(rtc_wdt_stage_t stage, unsigned int timeout_ms); + +/** + * @brief Get the timeout set for the required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[out] timeout_ms Timeout set for this stage. (not elapsed time). + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage has invalid value + */ +esp_err_t rtc_wdt_get_timeout(rtc_wdt_stage_t stage, unsigned int* timeout_ms); + +/** + * @brief Set an action for required stage. + * + * @param[in] stage Stage of rtc_wdt. + * @param[in] stage_sel Action for this stage. When the time of stage expires this action will be triggered. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If stage or stage_sel have invalid value + */ +esp_err_t rtc_wdt_set_stage(rtc_wdt_stage_t stage, rtc_wdt_stage_action_t stage_sel); + +/** + * @brief Set a length of reset signal. + * + * @param[in] reset_src Type of reset signal. + * @param[in] reset_signal_length A length of reset signal. + * + * @return + * - ESP_OK In case of success + * - ESP_ERR_INVALID_ARG If reset_src or reset_signal_length have invalid value + */ +esp_err_t rtc_wdt_set_length_of_reset_signal(rtc_wdt_reset_sig_t reset_src, rtc_wdt_length_sig_t reset_signal_length); + +/** + * @brief Return true if rtc_wdt is enabled. + * + * @return + * - True rtc_wdt is enabled + */ +bool rtc_wdt_is_on(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc/spinlock.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/spinlock.h new file mode 100644 index 00000000..5370642a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc/spinlock.h @@ -0,0 +1,164 @@ +// Copyright 2015-2019 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. +#pragma once + +#include +#include +#include "sdkconfig.h" +#include "soc/cpu.h" +#include "hal/cpu_hal.h" +#include "soc/soc_memory_layout.h" +#include "soc/compare_set.h" + +#if __XTENSA__ +#include "xtensa/xtruntime.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef CONFIG_SPIRAM_WORKAROUND_NEED_VOLATILE_SPINLOCK +#define NEED_VOLATILE_MUX volatile +#else +#define NEED_VOLATILE_MUX +#endif + +#define SPINLOCK_FREE 0xB33FFFFF +#define SPINLOCK_WAIT_FOREVER (-1) +#define SPINLOCK_NO_WAIT 0 +#define SPINLOCK_INITIALIZER {.owner = SPINLOCK_FREE,.count = 0} +#define CORE_ID_REGVAL_XOR_SWAP (0xCDCD ^ 0xABAB) + +typedef struct { + NEED_VOLATILE_MUX uint32_t owner; + NEED_VOLATILE_MUX uint32_t count; +}spinlock_t; + +/** + * @brief Initialize a lock to its default state - unlocked + * @param lock - spinlock object to initialize + */ +static inline void __attribute__((always_inline)) spinlock_initialize(spinlock_t *lock) +{ + assert(lock); +#if !CONFIG_FREERTOS_UNICORE + lock->owner = SPINLOCK_FREE; + lock->count = 0; +#endif +} + +/** + * @brief Top level spinlock acquire function, spins until get the lock + * @param lock - target spinlock object + * @param timeout - cycles to wait, passing SPINLOCK_WAIT_FOREVER blocs indefinitely + */ +static inline bool __attribute__((always_inline)) spinlock_acquire(spinlock_t *lock, int32_t timeout) +{ +#if !CONFIG_FREERTOS_UNICORE && !BOOTLOADER_BUILD + uint32_t result; + uint32_t irq_status; + uint32_t ccount_start; + uint32_t core_id, other_core_id; + + assert(lock); + irq_status = XTOS_SET_INTLEVEL(XCHAL_EXCM_LEVEL); + + if(timeout != SPINLOCK_WAIT_FOREVER){ + RSR(CCOUNT, ccount_start); + } + + /*spin until we own a core */ + RSR(PRID, core_id); + + /* Note: coreID is the full 32 bit core ID (CORE_ID_REGVAL_PRO/CORE_ID_REGVAL_APP) */ + + other_core_id = CORE_ID_REGVAL_XOR_SWAP ^ core_id; + do { + + /* lock->owner should be one of SPINLOCK_FREE, CORE_ID_REGVAL_PRO, + * CORE_ID_REGVAL_APP: + * - If SPINLOCK_FREE, we want to atomically set to 'core_id'. + * - If "our" core_id, we can drop through immediately. + * - If "other_core_id", we spin here. + */ + result = core_id; + +#if defined(CONFIG_ESP32_SPIRAM_SUPPORT) + if (esp_ptr_external_ram(lock)) { + compare_and_set_extram(&lock->owner, SPINLOCK_FREE, &result); + } else { +#endif + compare_and_set_native(&lock->owner, SPINLOCK_FREE, &result); +#if defined(CONFIG_ESP32_SPIRAM_SUPPORT) + } +#endif + if(result != other_core_id) { + break; + } + + if (timeout != SPINLOCK_WAIT_FOREVER) { + uint32_t ccount_now; + ccount_now = cpu_hal_get_cycle_count(); + if (ccount_now - ccount_start > (unsigned)timeout) { + XTOS_RESTORE_INTLEVEL(irq_status); + return false; + } + } + }while(1); + + /* any other value implies memory corruption or uninitialized mux */ + assert(result == core_id || result == SPINLOCK_FREE); + assert((result == SPINLOCK_FREE) == (lock->count == 0)); /* we're first to lock iff count is zero */ + assert(lock->count < 0xFF); /* Bad count value implies memory corruption */ + + lock->count++; + XTOS_RESTORE_INTLEVEL(irq_status); + return true; + +#else // !CONFIG_FREERTOS_UNICORE + return true; +#endif +} + +/** + * @brief Top level spinlock unlock function, unlocks a previously locked spinlock + * @param lock - target, locked before, spinlock object + */ +static inline void __attribute__((always_inline)) spinlock_release(spinlock_t *lock) +{ +#if !CONFIG_FREERTOS_UNICORE && !BOOTLOADER_BUILD + uint32_t irq_status; + uint32_t core_id; + + assert(lock); + irq_status = XTOS_SET_INTLEVEL(XCHAL_EXCM_LEVEL); + + RSR(PRID, core_id); + assert(core_id == lock->owner); // This is a mutex we didn't lock, or it's corrupt + lock->count--; + + if(!lock->count) { + lock->owner = SPINLOCK_FREE; + } else { + assert(lock->count < 0x100); // Indicates memory corruption + } + + XTOS_RESTORE_INTLEVEL(irq_status); +#endif +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/include/soc_log.h b/tools/sdk/esp32c3/include/esp_hw_support/include/soc_log.h new file mode 100644 index 00000000..894f0962 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/include/soc_log.h @@ -0,0 +1,51 @@ +// Copyright 2016-2017 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. + +#pragma once +#include "esp_rom_sys.h" + +/** + * @file soc_log.h + * @brief SOC library logging functions + * + * To make SOC library compatible with environments which don't use ESP-IDF, + * this header file provides wrappers for logging functions. + */ + +#ifdef ESP_PLATFORM +#include "esp_log.h" +#define SOC_LOGE(tag, fmt, ...) ESP_EARLY_LOGE(tag, fmt, ##__VA_ARGS__) +#define SOC_LOGW(tag, fmt, ...) ESP_EARLY_LOGW(tag, fmt, ##__VA_ARGS__) +#define SOC_LOGI(tag, fmt, ...) ESP_EARLY_LOGI(tag, fmt, ##__VA_ARGS__) +#define SOC_LOGD(tag, fmt, ...) ESP_EARLY_LOGD(tag, fmt, ##__VA_ARGS__) +#define SOC_LOGV(tag, fmt, ...) ESP_EARLY_LOGV(tag, fmt, ##__VA_ARGS__) + +#else +#include "sdkconfig.h" +#ifdef CONFIG_IDF_TARGET_ESP32 +#include "esp32/rom/ets_sys.h" // will be removed in idf v5.0 +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/rom/ets_sys.h" +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/rom/ets_sys.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#endif + +#define SOC_LOGE(tag, fmt, ...) esp_rom_printf("%s(err): " fmt, tag, ##__VA_ARGS__) +#define SOC_LOGW(tag, fmt, ...) esp_rom_printf("%s(warn): " fmt, tag, ##__VA_ARGS__) +#define SOC_LOGI(tag, fmt, ...) esp_rom_printf("%s(info): " fmt, tag, ##__VA_ARGS__) +#define SOC_LOGD(tag, fmt, ...) esp_rom_printf("%s(dbg): " fmt, tag, ##__VA_ARGS__) +#define SOC_LOGV(tag, fmt, ...) esp_rom_printf("%s: " fmt, tag, ##__VA_ARGS__) +#endif //ESP_PLATFORM diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_brownout.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_brownout.h new file mode 100644 index 00000000..5fac2c91 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_brownout.h @@ -0,0 +1,30 @@ +// Copyright 2020 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. + +#pragma once + +/** + * @file i2c_brownout.h + * @brief Register definitions for brownout detector + * + * This file lists register fields of the brownout detector, located on an internal configuration + * bus. These definitions are used via macros defined in i2c_rtc_clk.h. + */ + +#define I2C_BOD 0x61 +#define I2C_BOD_HOSTID 1 + +#define I2C_BOD_THRESHOLD 0x5 +#define I2C_BOD_THRESHOLD_MSB 2 +#define I2C_BOD_THRESHOLD_LSB 0 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_rtc_clk.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_rtc_clk.h new file mode 100644 index 00000000..0bbe0ee1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/i2c_rtc_clk.h @@ -0,0 +1,48 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include "regi2c_ctrl.h" + +/* Analog function control register */ +#define ANA_CONFIG_REG 0x6000E044 +#define ANA_CONFIG_S (8) +#define ANA_CONFIG_M (0x3FF) +/* Clear to enable APLL */ +#define I2C_APLL_M (BIT(14)) +/* Clear to enable BBPLL */ +#define I2C_BBPLL_M (BIT(17)) + +/* ROM functions which read/write internal control bus */ +uint8_t rom_i2c_readReg(uint8_t block, uint8_t host_id, uint8_t reg_add); +uint8_t rom_i2c_readReg_Mask(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t msb, uint8_t lsb); +void rom_i2c_writeReg(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t data); +void rom_i2c_writeReg_Mask(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t msb, uint8_t lsb, uint8_t data); + +/* Convenience macros for the above functions, these use register definitions + * from i2c_apll.h/i2c_bbpll.h header files. + */ +#define I2C_WRITEREG_MASK_RTC(block, reg_add, indata) \ + rom_i2c_writeReg_Mask(block, block##_HOSTID, reg_add, reg_add##_MSB, reg_add##_LSB, indata) + +#define I2C_READREG_MASK_RTC(block, reg_add) \ + rom_i2c_readReg_Mask(block, block##_HOSTID, reg_add, reg_add##_MSB, reg_add##_LSB) + +#define I2C_WRITEREG_RTC(block, reg_add, indata) \ + rom_i2c_writeReg(block, block##_HOSTID, reg_add, indata) + +#define I2C_READREG_RTC(block, reg_add) \ + rom_i2c_readReg(block, block##_HOSTID, reg_add) diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bbpll.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bbpll.h new file mode 100644 index 00000000..842f7029 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bbpll.h @@ -0,0 +1,183 @@ +// Copyright 2020 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. + +#pragma once + +/** + * @file regi2c_bbpll.h + * @brief Register definitions for digital PLL (BBPLL) + * + * This file lists register fields of BBPLL, located on an internal configuration + * bus. These definitions are used via macros defined in regi2c_ctrl.h, by + * rtc_clk_cpu_freq_set function in rtc_clk.c. + */ + +#define I2C_BBPLL 0x66 +#define I2C_BBPLL_HOSTID 0 + +#define I2C_BBPLL_IR_CAL_DELAY 0 +#define I2C_BBPLL_IR_CAL_DELAY_MSB 3 +#define I2C_BBPLL_IR_CAL_DELAY_LSB 0 + +#define I2C_BBPLL_IR_CAL_CK_DIV 0 +#define I2C_BBPLL_IR_CAL_CK_DIV_MSB 7 +#define I2C_BBPLL_IR_CAL_CK_DIV_LSB 4 + +#define I2C_BBPLL_IR_CAL_EXT_CAP 1 +#define I2C_BBPLL_IR_CAL_EXT_CAP_MSB 3 +#define I2C_BBPLL_IR_CAL_EXT_CAP_LSB 0 + +#define I2C_BBPLL_IR_CAL_ENX_CAP 1 +#define I2C_BBPLL_IR_CAL_ENX_CAP_MSB 4 +#define I2C_BBPLL_IR_CAL_ENX_CAP_LSB 4 + +#define I2C_BBPLL_IR_CAL_RSTB 1 +#define I2C_BBPLL_IR_CAL_RSTB_MSB 5 +#define I2C_BBPLL_IR_CAL_RSTB_LSB 5 + +#define I2C_BBPLL_IR_CAL_START 1 +#define I2C_BBPLL_IR_CAL_START_MSB 6 +#define I2C_BBPLL_IR_CAL_START_LSB 6 + +#define I2C_BBPLL_IR_CAL_UNSTOP 1 +#define I2C_BBPLL_IR_CAL_UNSTOP_MSB 7 +#define I2C_BBPLL_IR_CAL_UNSTOP_LSB 7 + +#define I2C_BBPLL_OC_REF_DIV 2 +#define I2C_BBPLL_OC_REF_DIV_MSB 3 +#define I2C_BBPLL_OC_REF_DIV_LSB 0 + +#define I2C_BBPLL_OC_DCHGP 2 +#define I2C_BBPLL_OC_DCHGP_MSB 6 +#define I2C_BBPLL_OC_DCHGP_LSB 4 + +#define I2C_BBPLL_OC_ENB_FCAL 2 +#define I2C_BBPLL_OC_ENB_FCAL_MSB 7 +#define I2C_BBPLL_OC_ENB_FCAL_LSB 7 + +#define I2C_BBPLL_OC_DIV_7_0 3 +#define I2C_BBPLL_OC_DIV_7_0_MSB 7 +#define I2C_BBPLL_OC_DIV_7_0_LSB 0 + +#define I2C_BBPLL_RSTB_DIV_ADC 4 +#define I2C_BBPLL_RSTB_DIV_ADC_MSB 0 +#define I2C_BBPLL_RSTB_DIV_ADC_LSB 0 + +#define I2C_BBPLL_MODE_HF 4 +#define I2C_BBPLL_MODE_HF_MSB 1 +#define I2C_BBPLL_MODE_HF_LSB 1 + +#define I2C_BBPLL_DIV_ADC 4 +#define I2C_BBPLL_DIV_ADC_MSB 3 +#define I2C_BBPLL_DIV_ADC_LSB 2 + +#define I2C_BBPLL_DIV_DAC 4 +#define I2C_BBPLL_DIV_DAC_MSB 4 +#define I2C_BBPLL_DIV_DAC_LSB 4 + +#define I2C_BBPLL_DIV_CPU 4 +#define I2C_BBPLL_DIV_CPU_MSB 5 +#define I2C_BBPLL_DIV_CPU_LSB 5 + +#define I2C_BBPLL_OC_ENB_VCON 4 +#define I2C_BBPLL_OC_ENB_VCON_MSB 6 +#define I2C_BBPLL_OC_ENB_VCON_LSB 6 + +#define I2C_BBPLL_OC_TSCHGP 4 +#define I2C_BBPLL_OC_TSCHGP_MSB 7 +#define I2C_BBPLL_OC_TSCHGP_LSB 7 + +#define I2C_BBPLL_OC_DR1 5 +#define I2C_BBPLL_OC_DR1_MSB 2 +#define I2C_BBPLL_OC_DR1_LSB 0 + +#define I2C_BBPLL_OC_DR3 5 +#define I2C_BBPLL_OC_DR3_MSB 6 +#define I2C_BBPLL_OC_DR3_LSB 4 + +#define I2C_BBPLL_EN_USB 5 +#define I2C_BBPLL_EN_USB_MSB 7 +#define I2C_BBPLL_EN_USB_LSB 7 + +#define I2C_BBPLL_OC_DCUR 6 +#define I2C_BBPLL_OC_DCUR_MSB 2 +#define I2C_BBPLL_OC_DCUR_LSB 0 + +#define I2C_BBPLL_INC_CUR 6 +#define I2C_BBPLL_INC_CUR_MSB 3 +#define I2C_BBPLL_INC_CUR_LSB 3 + +#define I2C_BBPLL_OC_DHREF_SEL 6 +#define I2C_BBPLL_OC_DHREF_SEL_MSB 5 +#define I2C_BBPLL_OC_DHREF_SEL_LSB 4 + +#define I2C_BBPLL_OC_DLREF_SEL 6 +#define I2C_BBPLL_OC_DLREF_SEL_MSB 7 +#define I2C_BBPLL_OC_DLREF_SEL_LSB 6 + +#define I2C_BBPLL_OR_CAL_CAP 8 +#define I2C_BBPLL_OR_CAL_CAP_MSB 3 +#define I2C_BBPLL_OR_CAL_CAP_LSB 0 + +#define I2C_BBPLL_OR_CAL_UDF 8 +#define I2C_BBPLL_OR_CAL_UDF_MSB 4 +#define I2C_BBPLL_OR_CAL_UDF_LSB 4 + +#define I2C_BBPLL_OR_CAL_OVF 8 +#define I2C_BBPLL_OR_CAL_OVF_MSB 5 +#define I2C_BBPLL_OR_CAL_OVF_LSB 5 + +#define I2C_BBPLL_OR_CAL_END 8 +#define I2C_BBPLL_OR_CAL_END_MSB 6 +#define I2C_BBPLL_OR_CAL_END_LSB 6 + +#define I2C_BBPLL_OR_LOCK 8 +#define I2C_BBPLL_OR_LOCK_MSB 7 +#define I2C_BBPLL_OR_LOCK_LSB 7 + +#define I2C_BBPLL_OC_VCO_DBIAS 9 +#define I2C_BBPLL_OC_VCO_DBIAS_MSB 1 +#define I2C_BBPLL_OC_VCO_DBIAS_LSB 0 + +#define I2C_BBPLL_BBADC_DELAY2 9 +#define I2C_BBPLL_BBADC_DELAY2_MSB 3 +#define I2C_BBPLL_BBADC_DELAY2_LSB 2 + +#define I2C_BBPLL_BBADC_DVDD 9 +#define I2C_BBPLL_BBADC_DVDD_MSB 5 +#define I2C_BBPLL_BBADC_DVDD_LSB 4 + +#define I2C_BBPLL_BBADC_DREF 9 +#define I2C_BBPLL_BBADC_DREF_MSB 7 +#define I2C_BBPLL_BBADC_DREF_LSB 6 + +#define I2C_BBPLL_BBADC_DCUR 10 +#define I2C_BBPLL_BBADC_DCUR_MSB 1 +#define I2C_BBPLL_BBADC_DCUR_LSB 0 + +#define I2C_BBPLL_BBADC_INPUT_SHORT 10 +#define I2C_BBPLL_BBADC_INPUT_SHORT_MSB 2 +#define I2C_BBPLL_BBADC_INPUT_SHORT_LSB 2 + +#define I2C_BBPLL_ENT_PLL 10 +#define I2C_BBPLL_ENT_PLL_MSB 3 +#define I2C_BBPLL_ENT_PLL_LSB 3 + +#define I2C_BBPLL_DTEST 10 +#define I2C_BBPLL_DTEST_MSB 5 +#define I2C_BBPLL_DTEST_LSB 4 + +#define I2C_BBPLL_ENT_ADC 10 +#define I2C_BBPLL_ENT_ADC_MSB 7 +#define I2C_BBPLL_ENT_ADC_LSB 6 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bias.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bias.h new file mode 100644 index 00000000..f459a344 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_bias.h @@ -0,0 +1,30 @@ +// Copyright 2015-2020 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. + +#pragma once + +/** + * @file regi2c_bias.h + * @brief Register definitions for bias + * + * This file lists register fields of BIAS. These definitions are used via macros defined in regi2c_ctrl.h, by + * bootloader_hardware_init function in bootloader_esp32c3.c. + */ + +#define I2C_BIAS 0X6A +#define I2C_BIAS_HOSTID 0 + +#define I2C_BIAS_DREG_1P1_PVT 1 +#define I2C_BIAS_DREG_1P1_PVT_MSB 3 +#define I2C_BIAS_DREG_1P1_PVT_LSB 0 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_brownout.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_brownout.h new file mode 100644 index 00000000..d8175134 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_brownout.h @@ -0,0 +1,30 @@ +// Copyright 2020 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. + +#pragma once + +/** + * @file regi2c_brownout.h + * @brief Register definitions for brownout detector + * + * This file lists register fields of the brownout detector, located on an internal configuration + * bus. These definitions are used via macros defined in regi2c_ctrl.h. + */ + +#define I2C_BOD 0x61 +#define I2C_BOD_HOSTID 0 + +#define I2C_BOD_THRESHOLD 0x5 +#define I2C_BOD_THRESHOLD_MSB 2 +#define I2C_BOD_THRESHOLD_LSB 0 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_dig_reg.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_dig_reg.h new file mode 100644 index 00000000..2510f43a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_dig_reg.h @@ -0,0 +1,68 @@ +// Copyright 2015-2020 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. + +#pragma once + +/** + * @file regi2c_dig_reg.h + * @brief Register definitions for digital to get rtc voltage & digital voltage + * by setting rtc_dbias_Wak & dig_dbias_wak or by analog self-calibration. + */ + +#define I2C_DIG_REG 0x6D +#define I2C_DIG_REG_HOSTID 0 + +#define I2C_DIG_REG_EXT_RTC_DREG 4 +#define I2C_DIG_REG_EXT_RTC_DREG_MSB 4 +#define I2C_DIG_REG_EXT_RTC_DREG_LSB 0 + +#define I2C_DIG_REG_ENX_RTC_DREG 4 +#define I2C_DIG_REG_ENX_RTC_DREG_MSB 7 +#define I2C_DIG_REG_ENX_RTC_DREG_LSB 7 + +#define I2C_DIG_REG_EXT_RTC_DREG_SLEEP 5 +#define I2C_DIG_REG_EXT_RTC_DREG_SLEEP_MSB 4 +#define I2C_DIG_REG_EXT_RTC_DREG_SLEEP_LSB 0 + +#define I2C_DIG_REG_ENX_RTC_DREG_SLEEP 5 +#define I2C_DIG_REG_ENX_RTC_DREG_SLEEP_MSB 7 +#define I2C_DIG_REG_ENX_RTC_DREG_SLEEP_LSB 7 + +#define I2C_DIG_REG_EXT_DIG_DREG 6 +#define I2C_DIG_REG_EXT_DIG_DREG_MSB 4 +#define I2C_DIG_REG_EXT_DIG_DREG_LSB 0 + +#define I2C_DIG_REG_ENX_DIG_DREG 6 +#define I2C_DIG_REG_ENX_DIG_DREG_MSB 7 +#define I2C_DIG_REG_ENX_DIG_DREG_LSB 7 + +#define I2C_DIG_REG_EXT_DIG_DREG_SLEEP 7 +#define I2C_DIG_REG_EXT_DIG_DREG_SLEEP_MSB 4 +#define I2C_DIG_REG_EXT_DIG_DREG_SLEEP_LSB 0 + +#define I2C_DIG_REG_ENX_DIG_DREG_SLEEP 7 +#define I2C_DIG_REG_ENX_DIG_DREG_SLEEP_MSB 7 +#define I2C_DIG_REG_ENX_DIG_DREG_SLEEP_LSB 7 + +#define I2C_DIG_REG_OR_EN_CONT_CAL 9 +#define I2C_DIG_REG_OR_EN_CONT_CAL_MSB 7 +#define I2C_DIG_REG_OR_EN_CONT_CAL_LSB 7 + +#define I2C_DIG_REG_XPD_RTC_REG 13 +#define I2C_DIG_REG_XPD_RTC_REG_MSB 2 +#define I2C_DIG_REG_XPD_RTC_REG_LSB 2 + +#define I2C_DIG_REG_XPD_DIG_REG 13 +#define I2C_DIG_REG_XPD_DIG_REG_MSB 3 +#define I2C_DIG_REG_XPD_DIG_REG_LSB 3 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_lp_bias.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_lp_bias.h new file mode 100644 index 00000000..0dae7710 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_lp_bias.h @@ -0,0 +1,63 @@ +// Copyright 2015-2020 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. + +#pragma once + +/** + * @file regi2c_lp_bias.h + * @brief Register definitions for analog to calibrate o_code for getting a more precise voltage. + * + * This file lists register fields of low power dbais, located on an internal configuration + * bus. These definitions are used via macros defined in regi2c_ctrl.h, by + * rtc_init function in rtc_init.c. + */ + +#define I2C_ULP 0x61 +#define I2C_ULP_HOSTID 0 + +#define I2C_ULP_IR_RESETB 0 +#define I2C_ULP_IR_RESETB_MSB 0 +#define I2C_ULP_IR_RESETB_LSB 0 + +#define I2C_ULP_IR_FORCE_XPD_CK 0 +#define I2C_ULP_IR_FORCE_XPD_CK_MSB 2 +#define I2C_ULP_IR_FORCE_XPD_CK_LSB 2 + +#define I2C_ULP_IR_FORCE_XPD_IPH 0 +#define I2C_ULP_IR_FORCE_XPD_IPH_MSB 4 +#define I2C_ULP_IR_FORCE_XPD_IPH_LSB 4 + +#define I2C_ULP_IR_DISABLE_WATCHDOG_CK 0 +#define I2C_ULP_IR_DISABLE_WATCHDOG_CK_MSB 6 +#define I2C_ULP_IR_DISABLE_WATCHDOG_CK_LSB 6 + +#define I2C_ULP_O_DONE_FLAG 3 +#define I2C_ULP_O_DONE_FLAG_MSB 0 +#define I2C_ULP_O_DONE_FLAG_LSB 0 + +#define I2C_ULP_BG_O_DONE_FLAG 3 +#define I2C_ULP_BG_O_DONE_FLAG_MSB 3 +#define I2C_ULP_BG_O_DONE_FLAG_LSB 3 + +#define I2C_ULP_OCODE 4 +#define I2C_ULP_OCODE_MSB 7 +#define I2C_ULP_OCODE_LSB 0 + +#define I2C_ULP_IR_FORCE_CODE 5 +#define I2C_ULP_IR_FORCE_CODE_MSB 6 +#define I2C_ULP_IR_FORCE_CODE_LSB 6 + +#define I2C_ULP_EXT_CODE 6 +#define I2C_ULP_EXT_CODE_MSB 7 +#define I2C_ULP_EXT_CODE_LSB 0 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_saradc.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_saradc.h new file mode 100644 index 00000000..e9def958 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/private_include/regi2c_saradc.h @@ -0,0 +1,87 @@ +// Copyright 2019-2020 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. + +#pragma once + +/** + * @file regi2c_saradc.h + * @brief Register definitions for analog to calibrate initial code for getting a more precise voltage of SAR ADC. + * + * This file lists register fields of SAR, located on an internal configuration + * bus. These definitions are used via macros defined in regi2c_ctrl.h, by + * function in adc_ll.h. + */ + +#define I2C_SAR_ADC 0X69 +#define I2C_SAR_ADC_HOSTID 0 + +#define ADC_SAR1_ENCAL_GND_ADDR 0x7 +#define ADC_SAR1_ENCAL_GND_ADDR_MSB 5 +#define ADC_SAR1_ENCAL_GND_ADDR_LSB 5 + +#define ADC_SAR2_ENCAL_GND_ADDR 0x7 +#define ADC_SAR2_ENCAL_GND_ADDR_MSB 7 +#define ADC_SAR2_ENCAL_GND_ADDR_LSB 7 + +#define ADC_SAR1_INITIAL_CODE_HIGH_ADDR 0x1 +#define ADC_SAR1_INITIAL_CODE_HIGH_ADDR_MSB 0x3 +#define ADC_SAR1_INITIAL_CODE_HIGH_ADDR_LSB 0x0 + +#define ADC_SAR1_INITIAL_CODE_LOW_ADDR 0x0 +#define ADC_SAR1_INITIAL_CODE_LOW_ADDR_MSB 0x7 +#define ADC_SAR1_INITIAL_CODE_LOW_ADDR_LSB 0x0 + +#define ADC_SAR2_INITIAL_CODE_HIGH_ADDR 0x4 +#define ADC_SAR2_INITIAL_CODE_HIGH_ADDR_MSB 0x3 +#define ADC_SAR2_INITIAL_CODE_HIGH_ADDR_LSB 0x0 + +#define ADC_SAR2_INITIAL_CODE_LOW_ADDR 0x3 +#define ADC_SAR2_INITIAL_CODE_LOW_ADDR_MSB 0x7 +#define ADC_SAR2_INITIAL_CODE_LOW_ADDR_LSB 0x0 + +#define ADC_SAR1_DREF_ADDR 0x2 +#define ADC_SAR1_DREF_ADDR_MSB 0x6 +#define ADC_SAR1_DREF_ADDR_LSB 0x4 + +#define ADC_SAR2_DREF_ADDR 0x5 +#define ADC_SAR2_DREF_ADDR_MSB 0x6 +#define ADC_SAR2_DREF_ADDR_LSB 0x4 + +#define ADC_SAR1_SAMPLE_CYCLE_ADDR 0x2 +#define ADC_SAR1_SAMPLE_CYCLE_ADDR_MSB 0x2 +#define ADC_SAR1_SAMPLE_CYCLE_ADDR_LSB 0x0 + +#define ADC_SARADC_DTEST_RTC_ADDR 0x7 +#define ADC_SARADC_DTEST_RTC_ADDR_MSB 1 +#define ADC_SARADC_DTEST_RTC_ADDR_LSB 0 + +#define ADC_SARADC_ENT_TSENS_ADDR 0x7 +#define ADC_SARADC_ENT_TSENS_ADDR_MSB 2 +#define ADC_SARADC_ENT_TSENS_ADDR_LSB 2 + +#define ADC_SARADC_ENT_RTC_ADDR 0x7 +#define ADC_SARADC_ENT_RTC_ADDR_MSB 3 +#define ADC_SARADC_ENT_RTC_ADDR_LSB 3 + +#define ADC_SARADC1_ENCAL_REF_ADDR 0x7 +#define ADC_SARADC1_ENCAL_REF_ADDR_MSB 4 +#define ADC_SARADC1_ENCAL_REF_ADDR_LSB 4 + +#define ADC_SARADC2_ENCAL_REF_ADDR 0x7 +#define ADC_SARADC2_ENCAL_REF_ADDR_MSB 6 +#define ADC_SARADC2_ENCAL_REF_ADDR_LSB 6 + +#define I2C_SARADC_TSENS_DAC 0x6 +#define I2C_SARADC_TSENS_DAC_MSB 3 +#define I2C_SARADC_TSENS_DAC_LSB 0 diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/regi2c_ctrl.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/regi2c_ctrl.h new file mode 100644 index 00000000..dbca47e0 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/regi2c_ctrl.h @@ -0,0 +1,84 @@ +// Copyright 2020 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. + +// Copyright 2015-2020 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. + +#pragma once + +#include +#include "regi2c_bbpll.h" +#include "regi2c_lp_bias.h" +#include "regi2c_dig_reg.h" +#include "regi2c_bias.h" +#include "regi2c_saradc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Analog function control register */ +#define I2C_MST_ANA_CONF0_REG 0x6000E040 +#define I2C_MST_BBPLL_STOP_FORCE_HIGH (BIT(2)) +#define I2C_MST_BBPLL_STOP_FORCE_LOW (BIT(3)) + +#define ANA_CONFIG_REG 0x6000E044 +#define ANA_CONFIG_S (8) +#define ANA_CONFIG_M (0x3FF) + +#define ANA_I2C_SAR_FORCE_PD BIT(18) +#define ANA_I2C_BBPLL_M BIT(17) /* Clear to enable BBPLL */ +#define ANA_I2C_APLL_M BIT(14) /* Clear to enable APLL */ + + +#define ANA_CONFIG2_REG 0x6000E048 +#define ANA_CONFIG2_M BIT(18) + +#define ANA_I2C_SAR_FORCE_PU BIT(16) + +/* ROM functions which read/write internal control bus */ +uint8_t rom_i2c_readReg(uint8_t block, uint8_t host_id, uint8_t reg_add); +uint8_t rom_i2c_readReg_Mask(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t msb, uint8_t lsb); +void rom_i2c_writeReg(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t data); +void rom_i2c_writeReg_Mask(uint8_t block, uint8_t host_id, uint8_t reg_add, uint8_t msb, uint8_t lsb, uint8_t data); + +/* Convenience macros for the above functions, these use register definitions + * from regi2c_bbpll.h/regi2c_dig_reg.h/regi2c_lp_bias.h/regi2c_bias.h header files. + */ +#define REGI2C_WRITE_MASK(block, reg_add, indata) \ + rom_i2c_writeReg_Mask(block, block##_HOSTID, reg_add, reg_add##_MSB, reg_add##_LSB, indata) + +#define REGI2C_READ_MASK(block, reg_add) \ + rom_i2c_readReg_Mask(block, block##_HOSTID, reg_add, reg_add##_MSB, reg_add##_LSB) + +#define REGI2C_WRITE(block, reg_add, indata) \ + rom_i2c_writeReg(block, block##_HOSTID, reg_add, indata) + +#define REGI2C_READ(block, reg_add) \ + rom_i2c_readReg(block, block##_HOSTID, reg_add) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/rtc_clk_common.h b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/rtc_clk_common.h new file mode 100644 index 00000000..c3e8a86e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_hw_support/port/esp32c3/rtc_clk_common.h @@ -0,0 +1,57 @@ +// Copyright 2020 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. + +#pragma once + +#define MHZ (1000000) + +#define DPORT_CPUPERIOD_SEL_80 0 +#define DPORT_CPUPERIOD_SEL_160 1 + +#define DPORT_SOC_CLK_SEL_XTAL 0 +#define DPORT_SOC_CLK_SEL_PLL 1 +#define DPORT_SOC_CLK_SEL_8M 2 + +#define RTC_FAST_CLK_FREQ_8M 8500000 + +#ifdef __cplusplus +extern "C" { +#endif + +void rtc_clk_cpu_freq_to_xtal(int freq, int div); + +/* Values of RTC_XTAL_FREQ_REG and RTC_APB_FREQ_REG are stored as two copies in + * lower and upper 16-bit halves. These are the routines to work with such a + * representation. + */ +static inline bool clk_val_is_valid(uint32_t val) +{ + return (val & 0xffff) == ((val >> 16) & 0xffff) && + val != 0 && + val != UINT32_MAX; +} + +static inline uint32_t reg_val_to_clk_val(uint32_t val) +{ + return val & UINT16_MAX; +} + +static inline uint32_t clk_val_to_reg_val(uint32_t val) +{ + return (val & UINT16_MAX) | ((val & UINT16_MAX) << 16); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_ipc/include/esp_ipc.h b/tools/sdk/esp32c3/include/esp_ipc/include/esp_ipc.h new file mode 100644 index 00000000..477b3d0a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_ipc/include/esp_ipc.h @@ -0,0 +1,93 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_IPC_H__ +#define __ESP_IPC_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif +/** @cond */ +typedef void (*esp_ipc_func_t)(void* arg); +/** @endcond */ +/* + * Inter-processor call APIs + * + * FreeRTOS provides several APIs which can be used to communicate between + * different tasks, including tasks running on different CPUs. + * This module provides additional APIs to run some code on the other CPU. + * + * These APIs can only be used when FreeRTOS scheduler is running. + */ + +/** + * @brief Execute a function on the given CPU + * + * Run a given function on a particular CPU. The given function must accept a + * void* argument and return void. The given function is run in the context of + * the IPC task of the CPU specified by the cpu_id parameter. The calling task + * will be blocked until the IPC task begins executing the given function. If + * another IPC call is ongoing, the calling task will block until the other IPC + * call completes. The stack size allocated for the IPC task can be configured + * in the "Inter-Processor Call (IPC) task stack size" setting in menuconfig. + * Increase this setting if the given function requires more stack than default. + * + * @note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. + * + * @param[in] cpu_id CPU where the given function should be executed (0 or 1) + * @param[in] func Pointer to a function of type void func(void* arg) to be executed + * @param[in] arg Arbitrary argument of type void* to be passed into the function + * + * @return + * - ESP_ERR_INVALID_ARG if cpu_id is invalid + * - ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running + * - ESP_OK otherwise + */ +esp_err_t esp_ipc_call(uint32_t cpu_id, esp_ipc_func_t func, void* arg); + + +/** + * @brief Execute a function on the given CPU and blocks until it completes + * + * Run a given function on a particular CPU. The given function must accept a + * void* argument and return void. The given function is run in the context of + * the IPC task of the CPU specified by the cpu_id parameter. The calling task + * will be blocked until the IPC task completes execution of the given function. + * If another IPC call is ongoing, the calling task will block until the other + * IPC call completes. The stack size allocated for the IPC task can be + * configured in the "Inter-Processor Call (IPC) task stack size" setting in + * menuconfig. Increase this setting if the given function requires more stack + * than default. + * + * @note In single-core mode, returns ESP_ERR_INVALID_ARG for cpu_id 1. + * + * @param[in] cpu_id CPU where the given function should be executed (0 or 1) + * @param[in] func Pointer to a function of type void func(void* arg) to be executed + * @param[in] arg Arbitrary argument of type void* to be passed into the function + * + * @return + * - ESP_ERR_INVALID_ARG if cpu_id is invalid + * - ESP_ERR_INVALID_STATE if the FreeRTOS scheduler is not running + * - ESP_OK otherwise + */ +esp_err_t esp_ipc_call_blocking(uint32_t cpu_id, esp_ipc_func_t func, void* arg); + + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_IPC_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_littlefs/include/esp_littlefs.h b/tools/sdk/esp32c3/include/esp_littlefs/include/esp_littlefs.h new file mode 100644 index 00000000..dbb10287 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/include/esp_littlefs.h @@ -0,0 +1,118 @@ +#ifndef ESP_LITTLEFS_H__ +#define ESP_LITTLEFS_H__ + +#include +#include +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "esp_err.h" +#include +#include +#include +#include +#include +#include +#include +#include "sdkconfig.h" + +#include "littlefs/lfs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Last Modified Time + * + * Use 't' for LITTLEFS_ATTR_MTIME to match example: + * https://github.com/ARMmbed/littlefs/issues/23#issuecomment-482293539 + * And to match other external tools such as: + * https://github.com/earlephilhower/mklittlefs + */ +#define LITTLEFS_ATTR_MTIME ((uint8_t) 't') + +/** + *Configuration structure for esp_vfs_littlefs_register. + */ +typedef struct { + const char *base_path; /**< Mounting point. */ + const char *partition_label; /**< Label of partition to use. */ + uint8_t format_if_mount_failed:1; /**< Format the file system if it fails to mount. */ + uint8_t dont_mount:1; /**< Don't attempt to mount or format. Overrides format_if_mount_failed */ +} esp_vfs_littlefs_conf_t; + +/** + * Register and mount littlefs to VFS with given path prefix. + * + * @param conf Pointer to esp_vfs_littlefs_conf_t configuration structure + * + * @return + * - ESP_OK if success + * - ESP_ERR_NO_MEM if objects could not be allocated + * - ESP_ERR_INVALID_STATE if already mounted or partition is encrypted + * - ESP_ERR_NOT_FOUND if partition for littlefs was not found + * - ESP_FAIL if mount or format fails + */ +esp_err_t esp_vfs_littlefs_register(const esp_vfs_littlefs_conf_t * conf); + +/** + * Unregister and unmount littlefs from VFS + * + * @param partition_label Label of the partition to unregister. + * + * @return + * - ESP_OK if successful + * - ESP_ERR_INVALID_STATE already unregistered + */ +esp_err_t esp_vfs_littlefs_unregister(const char* partition_label); + +/** + * Check if littlefs is mounted + * + * @param partition_label Label of the partition to check. + * + * @return + * - true if mounted + * - false if not mounted + */ +bool esp_littlefs_mounted(const char* partition_label); + +/** + * Format the littlefs partition + * + * @param partition_label Label of the partition to format. + * @return + * - ESP_OK if successful + * - ESP_FAIL on error + */ +esp_err_t esp_littlefs_format(const char* partition_label); + +/** + * Get information for littlefs + * + * @param partition_label Optional, label of the partition to get info for. + * @param[out] total_bytes Size of the file system + * @param[out] used_bytes Current used bytes in the file system + * + * @return + * - ESP_OK if success + * - ESP_ERR_INVALID_STATE if not mounted + */ +esp_err_t esp_littlefs_info(const char* partition_label, size_t *total_bytes, size_t *used_bytes); + +#if CONFIG_LITTLEFS_HUMAN_READABLE +/** + * @brief converts an enumerated lfs error into a string. + * @param lfs_errno The enumerated littlefs error. + */ +const char * esp_littlefs_errno(enum lfs_error lfs_errno); +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_filebd.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_filebd.h new file mode 100644 index 00000000..0d56434a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_filebd.h @@ -0,0 +1,73 @@ +/* + * Block device emulated in a file + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_FILEBD_H +#define LFS_FILEBD_H + +#include "lfs.h" +#include "lfs_util.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// Block device specific tracing +#ifdef LFS_FILEBD_YES_TRACE +#define LFS_FILEBD_TRACE(...) LFS_TRACE(__VA_ARGS__) +#else +#define LFS_FILEBD_TRACE(...) +#endif + +// filebd config (optional) +struct lfs_filebd_config { + // 8-bit erase value to use for simulating erases. -1 does not simulate + // erases, which can speed up testing by avoiding all the extra block-device + // operations to store the erase value. + int32_t erase_value; +}; + +// filebd state +typedef struct lfs_filebd { + int fd; + const struct lfs_filebd_config *cfg; +} lfs_filebd_t; + + +// Create a file block device using the geometry in lfs_config +int lfs_filebd_create(const struct lfs_config *cfg, const char *path); +int lfs_filebd_createcfg(const struct lfs_config *cfg, const char *path, + const struct lfs_filebd_config *bdcfg); + +// Clean up memory associated with block device +int lfs_filebd_destroy(const struct lfs_config *cfg); + +// Read a block +int lfs_filebd_read(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, void *buffer, lfs_size_t size); + +// Program a block +// +// The block must have previously been erased. +int lfs_filebd_prog(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, const void *buffer, lfs_size_t size); + +// Erase a block +// +// A block must be erased before being programmed. The +// state of an erased block is undefined. +int lfs_filebd_erase(const struct lfs_config *cfg, lfs_block_t block); + +// Sync the block device +int lfs_filebd_sync(const struct lfs_config *cfg); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_rambd.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_rambd.h new file mode 100644 index 00000000..56a45ce9 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_rambd.h @@ -0,0 +1,75 @@ +/* + * Block device emulated in RAM + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_RAMBD_H +#define LFS_RAMBD_H + +#include "lfs.h" +#include "lfs_util.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// Block device specific tracing +#ifdef LFS_RAMBD_YES_TRACE +#define LFS_RAMBD_TRACE(...) LFS_TRACE(__VA_ARGS__) +#else +#define LFS_RAMBD_TRACE(...) +#endif + +// rambd config (optional) +struct lfs_rambd_config { + // 8-bit erase value to simulate erasing with. -1 indicates no erase + // occurs, which is still a valid block device + int32_t erase_value; + + // Optional statically allocated buffer for the block device. + void *buffer; +}; + +// rambd state +typedef struct lfs_rambd { + uint8_t *buffer; + const struct lfs_rambd_config *cfg; +} lfs_rambd_t; + + +// Create a RAM block device using the geometry in lfs_config +int lfs_rambd_create(const struct lfs_config *cfg); +int lfs_rambd_createcfg(const struct lfs_config *cfg, + const struct lfs_rambd_config *bdcfg); + +// Clean up memory associated with block device +int lfs_rambd_destroy(const struct lfs_config *cfg); + +// Read a block +int lfs_rambd_read(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, void *buffer, lfs_size_t size); + +// Program a block +// +// The block must have previously been erased. +int lfs_rambd_prog(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, const void *buffer, lfs_size_t size); + +// Erase a block +// +// A block must be erased before being programmed. The +// state of an erased block is undefined. +int lfs_rambd_erase(const struct lfs_config *cfg, lfs_block_t block); + +// Sync the block device +int lfs_rambd_sync(const struct lfs_config *cfg); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_testbd.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_testbd.h new file mode 100644 index 00000000..b1fb2e92 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/bd/lfs_testbd.h @@ -0,0 +1,141 @@ +/* + * Testing block device, wraps filebd and rambd while providing a bunch + * of hooks for testing littlefs in various conditions. + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_TESTBD_H +#define LFS_TESTBD_H + +#include "lfs.h" +#include "lfs_util.h" +#include "bd/lfs_rambd.h" +#include "bd/lfs_filebd.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// Block device specific tracing +#ifdef LFS_TESTBD_YES_TRACE +#define LFS_TESTBD_TRACE(...) LFS_TRACE(__VA_ARGS__) +#else +#define LFS_TESTBD_TRACE(...) +#endif + +// Mode determining how "bad blocks" behave during testing. This simulates +// some real-world circumstances such as progs not sticking (prog-noop), +// a readonly disk (erase-noop), and ECC failures (read-error). +// +// Not that read-noop is not allowed. Read _must_ return a consistent (but +// may be arbitrary) value on every read. +enum lfs_testbd_badblock_behavior { + LFS_TESTBD_BADBLOCK_PROGERROR, + LFS_TESTBD_BADBLOCK_ERASEERROR, + LFS_TESTBD_BADBLOCK_READERROR, + LFS_TESTBD_BADBLOCK_PROGNOOP, + LFS_TESTBD_BADBLOCK_ERASENOOP, +}; + +// Type for measuring wear +typedef uint32_t lfs_testbd_wear_t; +typedef int32_t lfs_testbd_swear_t; + +// testbd config, this is required for testing +struct lfs_testbd_config { + // 8-bit erase value to use for simulating erases. -1 does not simulate + // erases, which can speed up testing by avoiding all the extra block-device + // operations to store the erase value. + int32_t erase_value; + + // Number of erase cycles before a block becomes "bad". The exact behavior + // of bad blocks is controlled by the badblock_mode. + uint32_t erase_cycles; + + // The mode determining how bad blocks fail + uint8_t badblock_behavior; + + // Number of write operations (erase/prog) before forcefully killing + // the program with exit. Simulates power-loss. 0 disables. + uint32_t power_cycles; + + // Optional buffer for RAM block device. + void *buffer; + + // Optional buffer for wear + void *wear_buffer; +}; + +// testbd state +typedef struct lfs_testbd { + union { + struct { + lfs_filebd_t bd; + struct lfs_filebd_config cfg; + } file; + struct { + lfs_rambd_t bd; + struct lfs_rambd_config cfg; + } ram; + } u; + + bool persist; + uint32_t power_cycles; + lfs_testbd_wear_t *wear; + + const struct lfs_testbd_config *cfg; +} lfs_testbd_t; + + +/// Block device API /// + +// Create a test block device using the geometry in lfs_config +// +// Note that filebd is used if a path is provided, if path is NULL +// testbd will use rambd which can be much faster. +int lfs_testbd_create(const struct lfs_config *cfg, const char *path); +int lfs_testbd_createcfg(const struct lfs_config *cfg, const char *path, + const struct lfs_testbd_config *bdcfg); + +// Clean up memory associated with block device +int lfs_testbd_destroy(const struct lfs_config *cfg); + +// Read a block +int lfs_testbd_read(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, void *buffer, lfs_size_t size); + +// Program a block +// +// The block must have previously been erased. +int lfs_testbd_prog(const struct lfs_config *cfg, lfs_block_t block, + lfs_off_t off, const void *buffer, lfs_size_t size); + +// Erase a block +// +// A block must be erased before being programmed. The +// state of an erased block is undefined. +int lfs_testbd_erase(const struct lfs_config *cfg, lfs_block_t block); + +// Sync the block device +int lfs_testbd_sync(const struct lfs_config *cfg); + + +/// Additional extended API for driving test features /// + +// Get simulated wear on a given block +lfs_testbd_swear_t lfs_testbd_getwear(const struct lfs_config *cfg, + lfs_block_t block); + +// Manually set simulated wear on a given block +int lfs_testbd_setwear(const struct lfs_config *cfg, + lfs_block_t block, lfs_testbd_wear_t wear); + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs.h new file mode 100644 index 00000000..35bbbabf --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs.h @@ -0,0 +1,655 @@ +/* + * The little filesystem + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_H +#define LFS_H + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + + +/// Version info /// + +// Software library version +// Major (top-nibble), incremented on backwards incompatible changes +// Minor (bottom-nibble), incremented on feature additions +#define LFS_VERSION 0x00020002 +#define LFS_VERSION_MAJOR (0xffff & (LFS_VERSION >> 16)) +#define LFS_VERSION_MINOR (0xffff & (LFS_VERSION >> 0)) + +// Version of On-disk data structures +// Major (top-nibble), incremented on backwards incompatible changes +// Minor (bottom-nibble), incremented on feature additions +#define LFS_DISK_VERSION 0x00020000 +#define LFS_DISK_VERSION_MAJOR (0xffff & (LFS_DISK_VERSION >> 16)) +#define LFS_DISK_VERSION_MINOR (0xffff & (LFS_DISK_VERSION >> 0)) + + +/// Definitions /// + +// Type definitions +typedef uint32_t lfs_size_t; +typedef uint32_t lfs_off_t; + +typedef int32_t lfs_ssize_t; +typedef int32_t lfs_soff_t; + +typedef uint32_t lfs_block_t; + +// Maximum name size in bytes, may be redefined to reduce the size of the +// info struct. Limited to <= 1022. Stored in superblock and must be +// respected by other littlefs drivers. +#ifndef LFS_NAME_MAX +#define LFS_NAME_MAX 255 +#endif + +// Maximum size of a file in bytes, may be redefined to limit to support other +// drivers. Limited on disk to <= 4294967296. However, above 2147483647 the +// functions lfs_file_seek, lfs_file_size, and lfs_file_tell will return +// incorrect values due to using signed integers. Stored in superblock and +// must be respected by other littlefs drivers. +#ifndef LFS_FILE_MAX +#define LFS_FILE_MAX 2147483647 +#endif + +// Maximum size of custom attributes in bytes, may be redefined, but there is +// no real benefit to using a smaller LFS_ATTR_MAX. Limited to <= 1022. +#ifndef LFS_ATTR_MAX +#define LFS_ATTR_MAX 1022 +#endif + +// Possible error codes, these are negative to allow +// valid positive return values +enum lfs_error { + LFS_ERR_OK = 0, // No error + LFS_ERR_IO = -5, // Error during device operation + LFS_ERR_CORRUPT = -84, // Corrupted + LFS_ERR_NOENT = -2, // No directory entry + LFS_ERR_EXIST = -17, // Entry already exists + LFS_ERR_NOTDIR = -20, // Entry is not a dir + LFS_ERR_ISDIR = -21, // Entry is a dir + LFS_ERR_NOTEMPTY = -39, // Dir is not empty + LFS_ERR_BADF = -9, // Bad file number + LFS_ERR_FBIG = -27, // File too large + LFS_ERR_INVAL = -22, // Invalid parameter + LFS_ERR_NOSPC = -28, // No space left on device + LFS_ERR_NOMEM = -12, // No more memory available + LFS_ERR_NOATTR = -61, // No data/attr available + LFS_ERR_NAMETOOLONG = -36, // File name too long +}; + +// File types +enum lfs_type { + // file types + LFS_TYPE_REG = 0x001, + LFS_TYPE_DIR = 0x002, + + // internally used types + LFS_TYPE_SPLICE = 0x400, + LFS_TYPE_NAME = 0x000, + LFS_TYPE_STRUCT = 0x200, + LFS_TYPE_USERATTR = 0x300, + LFS_TYPE_FROM = 0x100, + LFS_TYPE_TAIL = 0x600, + LFS_TYPE_GLOBALS = 0x700, + LFS_TYPE_CRC = 0x500, + + // internally used type specializations + LFS_TYPE_CREATE = 0x401, + LFS_TYPE_DELETE = 0x4ff, + LFS_TYPE_SUPERBLOCK = 0x0ff, + LFS_TYPE_DIRSTRUCT = 0x200, + LFS_TYPE_CTZSTRUCT = 0x202, + LFS_TYPE_INLINESTRUCT = 0x201, + LFS_TYPE_SOFTTAIL = 0x600, + LFS_TYPE_HARDTAIL = 0x601, + LFS_TYPE_MOVESTATE = 0x7ff, + + // internal chip sources + LFS_FROM_NOOP = 0x000, + LFS_FROM_MOVE = 0x101, + LFS_FROM_USERATTRS = 0x102, +}; + +// File open flags +enum lfs_open_flags { + // open flags + LFS_O_RDONLY = 1, // Open a file as read only + LFS_O_WRONLY = 2, // Open a file as write only + LFS_O_RDWR = 3, // Open a file as read and write + LFS_O_CREAT = 0x0100, // Create a file if it does not exist + LFS_O_EXCL = 0x0200, // Fail if a file already exists + LFS_O_TRUNC = 0x0400, // Truncate the existing file to zero size + LFS_O_APPEND = 0x0800, // Move to end of file on every write + + // internally used flags + LFS_F_DIRTY = 0x010000, // File does not match storage + LFS_F_WRITING = 0x020000, // File has been written since last flush + LFS_F_READING = 0x040000, // File has been read since last flush + LFS_F_ERRED = 0x080000, // An error occured during write + LFS_F_INLINE = 0x100000, // Currently inlined in directory entry + LFS_F_OPENED = 0x200000, // File has been opened +}; + +// File seek flags +enum lfs_whence_flags { + LFS_SEEK_SET = 0, // Seek relative to an absolute position + LFS_SEEK_CUR = 1, // Seek relative to the current file position + LFS_SEEK_END = 2, // Seek relative to the end of the file +}; + + +// Configuration provided during initialization of the littlefs +struct lfs_config { + // Opaque user provided context that can be used to pass + // information to the block device operations + void *context; + + // Read a region in a block. Negative error codes are propogated + // to the user. + int (*read)(const struct lfs_config *c, lfs_block_t block, + lfs_off_t off, void *buffer, lfs_size_t size); + + // Program a region in a block. The block must have previously + // been erased. Negative error codes are propogated to the user. + // May return LFS_ERR_CORRUPT if the block should be considered bad. + int (*prog)(const struct lfs_config *c, lfs_block_t block, + lfs_off_t off, const void *buffer, lfs_size_t size); + + // Erase a block. A block must be erased before being programmed. + // The state of an erased block is undefined. Negative error codes + // are propogated to the user. + // May return LFS_ERR_CORRUPT if the block should be considered bad. + int (*erase)(const struct lfs_config *c, lfs_block_t block); + + // Sync the state of the underlying block device. Negative error codes + // are propogated to the user. + int (*sync)(const struct lfs_config *c); + + // Minimum size of a block read. All read operations will be a + // multiple of this value. + lfs_size_t read_size; + + // Minimum size of a block program. All program operations will be a + // multiple of this value. + lfs_size_t prog_size; + + // Size of an erasable block. This does not impact ram consumption and + // may be larger than the physical erase size. However, non-inlined files + // take up at minimum one block. Must be a multiple of the read + // and program sizes. + lfs_size_t block_size; + + // Number of erasable blocks on the device. + lfs_size_t block_count; + + // Number of erase cycles before littlefs evicts metadata logs and moves + // the metadata to another block. Suggested values are in the + // range 100-1000, with large values having better performance at the cost + // of less consistent wear distribution. + // + // Set to -1 to disable block-level wear-leveling. + int32_t block_cycles; + + // Size of block caches. Each cache buffers a portion of a block in RAM. + // The littlefs needs a read cache, a program cache, and one additional + // cache per file. Larger caches can improve performance by storing more + // data and reducing the number of disk accesses. Must be a multiple of + // the read and program sizes, and a factor of the block size. + lfs_size_t cache_size; + + // Size of the lookahead buffer in bytes. A larger lookahead buffer + // increases the number of blocks found during an allocation pass. The + // lookahead buffer is stored as a compact bitmap, so each byte of RAM + // can track 8 blocks. Must be a multiple of 8. + lfs_size_t lookahead_size; + + // Optional statically allocated read buffer. Must be cache_size. + // By default lfs_malloc is used to allocate this buffer. + void *read_buffer; + + // Optional statically allocated program buffer. Must be cache_size. + // By default lfs_malloc is used to allocate this buffer. + void *prog_buffer; + + // Optional statically allocated lookahead buffer. Must be lookahead_size + // and aligned to a 32-bit boundary. By default lfs_malloc is used to + // allocate this buffer. + void *lookahead_buffer; + + // Optional upper limit on length of file names in bytes. No downside for + // larger names except the size of the info struct which is controlled by + // the LFS_NAME_MAX define. Defaults to LFS_NAME_MAX when zero. Stored in + // superblock and must be respected by other littlefs drivers. + lfs_size_t name_max; + + // Optional upper limit on files in bytes. No downside for larger files + // but must be <= LFS_FILE_MAX. Defaults to LFS_FILE_MAX when zero. Stored + // in superblock and must be respected by other littlefs drivers. + lfs_size_t file_max; + + // Optional upper limit on custom attributes in bytes. No downside for + // larger attributes size but must be <= LFS_ATTR_MAX. Defaults to + // LFS_ATTR_MAX when zero. + lfs_size_t attr_max; +}; + +// File info structure +struct lfs_info { + // Type of the file, either LFS_TYPE_REG or LFS_TYPE_DIR + uint8_t type; + + // Size of the file, only valid for REG files. Limited to 32-bits. + lfs_size_t size; + + // Name of the file stored as a null-terminated string. Limited to + // LFS_NAME_MAX+1, which can be changed by redefining LFS_NAME_MAX to + // reduce RAM. LFS_NAME_MAX is stored in superblock and must be + // respected by other littlefs drivers. + char name[LFS_NAME_MAX+1]; +}; + +// Custom attribute structure, used to describe custom attributes +// committed atomically during file writes. +struct lfs_attr { + // 8-bit type of attribute, provided by user and used to + // identify the attribute + uint8_t type; + + // Pointer to buffer containing the attribute + void *buffer; + + // Size of attribute in bytes, limited to LFS_ATTR_MAX + lfs_size_t size; +}; + +// Optional configuration provided during lfs_file_opencfg +struct lfs_file_config { + // Optional statically allocated file buffer. Must be cache_size. + // By default lfs_malloc is used to allocate this buffer. + void *buffer; + + // Optional list of custom attributes related to the file. If the file + // is opened with read access, these attributes will be read from disk + // during the open call. If the file is opened with write access, the + // attributes will be written to disk every file sync or close. This + // write occurs atomically with update to the file's contents. + // + // Custom attributes are uniquely identified by an 8-bit type and limited + // to LFS_ATTR_MAX bytes. When read, if the stored attribute is smaller + // than the buffer, it will be padded with zeros. If the stored attribute + // is larger, then it will be silently truncated. If the attribute is not + // found, it will be created implicitly. + struct lfs_attr *attrs; + + // Number of custom attributes in the list + lfs_size_t attr_count; +}; + + +/// internal littlefs data structures /// +typedef struct lfs_cache { + lfs_block_t block; + lfs_off_t off; + lfs_size_t size; + uint8_t *buffer; +} lfs_cache_t; + +typedef struct lfs_mdir { + lfs_block_t pair[2]; + uint32_t rev; + lfs_off_t off; + uint32_t etag; + uint16_t count; + bool erased; + bool split; + lfs_block_t tail[2]; +} lfs_mdir_t; + +// littlefs directory type +typedef struct lfs_dir { + struct lfs_dir *next; + uint16_t id; + uint8_t type; + lfs_mdir_t m; + + lfs_off_t pos; + lfs_block_t head[2]; +} lfs_dir_t; + +// littlefs file type +typedef struct lfs_file { + struct lfs_file *next; + uint16_t id; + uint8_t type; + lfs_mdir_t m; + + struct lfs_ctz { + lfs_block_t head; + lfs_size_t size; + } ctz; + + uint32_t flags; + lfs_off_t pos; + lfs_block_t block; + lfs_off_t off; + lfs_cache_t cache; + + const struct lfs_file_config *cfg; +} lfs_file_t; + +typedef struct lfs_superblock { + uint32_t version; + lfs_size_t block_size; + lfs_size_t block_count; + lfs_size_t name_max; + lfs_size_t file_max; + lfs_size_t attr_max; +} lfs_superblock_t; + +typedef struct lfs_gstate { + uint32_t tag; + lfs_block_t pair[2]; +} lfs_gstate_t; + +// The littlefs filesystem type +typedef struct lfs { + lfs_cache_t rcache; + lfs_cache_t pcache; + + lfs_block_t root[2]; + struct lfs_mlist { + struct lfs_mlist *next; + uint16_t id; + uint8_t type; + lfs_mdir_t m; + } *mlist; + uint32_t seed; + + lfs_gstate_t gstate; + lfs_gstate_t gdisk; + lfs_gstate_t gdelta; + + struct lfs_free { + lfs_block_t off; + lfs_block_t size; + lfs_block_t i; + lfs_block_t ack; + uint32_t *buffer; + } free; + + const struct lfs_config *cfg; + lfs_size_t name_max; + lfs_size_t file_max; + lfs_size_t attr_max; + +#ifdef LFS_MIGRATE + struct lfs1 *lfs1; +#endif +} lfs_t; + + +/// Filesystem functions /// + +// Format a block device with the littlefs +// +// Requires a littlefs object and config struct. This clobbers the littlefs +// object, and does not leave the filesystem mounted. The config struct must +// be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_format(lfs_t *lfs, const struct lfs_config *config); + +// Mounts a littlefs +// +// Requires a littlefs object and config struct. Multiple filesystems +// may be mounted simultaneously with multiple littlefs objects. Both +// lfs and config must be allocated while mounted. The config struct must +// be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_mount(lfs_t *lfs, const struct lfs_config *config); + +// Unmounts a littlefs +// +// Does nothing besides releasing any allocated resources. +// Returns a negative error code on failure. +int lfs_unmount(lfs_t *lfs); + +/// General operations /// + +// Removes a file or directory +// +// If removing a directory, the directory must be empty. +// Returns a negative error code on failure. +int lfs_remove(lfs_t *lfs, const char *path); + +// Rename or move a file or directory +// +// If the destination exists, it must match the source in type. +// If the destination is a directory, the directory must be empty. +// +// Returns a negative error code on failure. +int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath); + +// Find info about a file or directory +// +// Fills out the info structure, based on the specified file or directory. +// Returns a negative error code on failure. +int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info); + +// Get a custom attribute +// +// Custom attributes are uniquely identified by an 8-bit type and limited +// to LFS_ATTR_MAX bytes. When read, if the stored attribute is smaller than +// the buffer, it will be padded with zeros. If the stored attribute is larger, +// then it will be silently truncated. If no attribute is found, the error +// LFS_ERR_NOATTR is returned and the buffer is filled with zeros. +// +// Returns the size of the attribute, or a negative error code on failure. +// Note, the returned size is the size of the attribute on disk, irrespective +// of the size of the buffer. This can be used to dynamically allocate a buffer +// or check for existance. +lfs_ssize_t lfs_getattr(lfs_t *lfs, const char *path, + uint8_t type, void *buffer, lfs_size_t size); + +// Set custom attributes +// +// Custom attributes are uniquely identified by an 8-bit type and limited +// to LFS_ATTR_MAX bytes. If an attribute is not found, it will be +// implicitly created. +// +// Returns a negative error code on failure. +int lfs_setattr(lfs_t *lfs, const char *path, + uint8_t type, const void *buffer, lfs_size_t size); + +// Removes a custom attribute +// +// If an attribute is not found, nothing happens. +// +// Returns a negative error code on failure. +int lfs_removeattr(lfs_t *lfs, const char *path, uint8_t type); + + +/// File operations /// + +// Open a file +// +// The mode that the file is opened in is determined by the flags, which +// are values from the enum lfs_open_flags that are bitwise-ored together. +// +// Returns a negative error code on failure. +int lfs_file_open(lfs_t *lfs, lfs_file_t *file, + const char *path, int flags); + +// Open a file with extra configuration +// +// The mode that the file is opened in is determined by the flags, which +// are values from the enum lfs_open_flags that are bitwise-ored together. +// +// The config struct provides additional config options per file as described +// above. The config struct must be allocated while the file is open, and the +// config struct must be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_file_opencfg(lfs_t *lfs, lfs_file_t *file, + const char *path, int flags, + const struct lfs_file_config *config); + +// Close a file +// +// Any pending writes are written out to storage as though +// sync had been called and releases any allocated resources. +// +// Returns a negative error code on failure. +int lfs_file_close(lfs_t *lfs, lfs_file_t *file); + +// Synchronize a file on storage +// +// Any pending writes are written out to storage. +// Returns a negative error code on failure. +int lfs_file_sync(lfs_t *lfs, lfs_file_t *file); + +// Read data from file +// +// Takes a buffer and size indicating where to store the read data. +// Returns the number of bytes read, or a negative error code on failure. +lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file, + void *buffer, lfs_size_t size); + +// Write data to file +// +// Takes a buffer and size indicating the data to write. The file will not +// actually be updated on the storage until either sync or close is called. +// +// Returns the number of bytes written, or a negative error code on failure. +lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file, + const void *buffer, lfs_size_t size); + +// Change the position of the file +// +// The change in position is determined by the offset and whence flag. +// Returns the new position of the file, or a negative error code on failure. +lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file, + lfs_soff_t off, int whence); + +// Truncates the size of the file to the specified size +// +// Returns a negative error code on failure. +int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size); + +// Return the position of the file +// +// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR) +// Returns the position of the file, or a negative error code on failure. +lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t *file); + +// Change the position of the file to the beginning of the file +// +// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_SET) +// Returns a negative error code on failure. +int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file); + +// Return the size of the file +// +// Similar to lfs_file_seek(lfs, file, 0, LFS_SEEK_END) +// Returns the size of the file, or a negative error code on failure. +lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file); + + +/// Directory operations /// + +// Create a directory +// +// Returns a negative error code on failure. +int lfs_mkdir(lfs_t *lfs, const char *path); + +// Open a directory +// +// Once open a directory can be used with read to iterate over files. +// Returns a negative error code on failure. +int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path); + +// Close a directory +// +// Releases any allocated resources. +// Returns a negative error code on failure. +int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir); + +// Read an entry in the directory +// +// Fills out the info structure, based on the specified file or directory. +// Returns a positive value on success, 0 at the end of directory, +// or a negative error code on failure. +int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info); + +// Change the position of the directory +// +// The new off must be a value previous returned from tell and specifies +// an absolute offset in the directory seek. +// +// Returns a negative error code on failure. +int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off); + +// Return the position of the directory +// +// The returned offset is only meant to be consumed by seek and may not make +// sense, but does indicate the current position in the directory iteration. +// +// Returns the position of the directory, or a negative error code on failure. +lfs_soff_t lfs_dir_tell(lfs_t *lfs, lfs_dir_t *dir); + +// Change the position of the directory to the beginning of the directory +// +// Returns a negative error code on failure. +int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir); + + +/// Filesystem-level filesystem operations + +// Finds the current size of the filesystem +// +// Note: Result is best effort. If files share COW structures, the returned +// size may be larger than the filesystem actually is. +// +// Returns the number of allocated blocks, or a negative error code on failure. +lfs_ssize_t lfs_fs_size(lfs_t *lfs); + +// Traverse through all blocks in use by the filesystem +// +// The provided callback will be called with each block address that is +// currently in use by the filesystem. This can be used to determine which +// blocks are in use or how much of the storage is available. +// +// Returns a negative error code on failure. +int lfs_fs_traverse(lfs_t *lfs, int (*cb)(void*, lfs_block_t), void *data); + +#ifdef LFS_MIGRATE +// Attempts to migrate a previous version of littlefs +// +// Behaves similarly to the lfs_format function. Attempts to mount +// the previous version of littlefs and update the filesystem so it can be +// mounted with the current version of littlefs. +// +// Requires a littlefs object and config struct. This clobbers the littlefs +// object, and does not leave the filesystem mounted. The config struct must +// be zeroed for defaults and backwards compatibility. +// +// Returns a negative error code on failure. +int lfs_migrate(lfs_t *lfs, const struct lfs_config *cfg); +#endif + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs_util.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs_util.h new file mode 100644 index 00000000..dbb4c5ba --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs/lfs_util.h @@ -0,0 +1,234 @@ +/* + * lfs utility functions + * + * Copyright (c) 2017, Arm Limited. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + */ +#ifndef LFS_UTIL_H +#define LFS_UTIL_H + +// Users can override lfs_util.h with their own configuration by defining +// LFS_CONFIG as a header file to include (-DLFS_CONFIG=lfs_config.h). +// +// If LFS_CONFIG is used, none of the default utils will be emitted and must be +// provided by the config file. To start, I would suggest copying lfs_util.h +// and modifying as needed. +#ifdef LFS_CONFIG +#define LFS_STRINGIZE(x) LFS_STRINGIZE2(x) +#define LFS_STRINGIZE2(x) #x +#include LFS_STRINGIZE(LFS_CONFIG) +#else + +// System includes +#include +#include +#include +#include + +#ifndef LFS_NO_MALLOC +#include +#endif +#ifndef LFS_NO_ASSERT +#include +#endif +#if !defined(LFS_NO_DEBUG) || \ + !defined(LFS_NO_WARN) || \ + !defined(LFS_NO_ERROR) || \ + defined(LFS_YES_TRACE) +#include +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + + +// Macros, may be replaced by system specific wrappers. Arguments to these +// macros must not have side-effects as the macros can be removed for a smaller +// code footprint + +// Logging functions +#ifdef LFS_YES_TRACE +#define LFS_TRACE_(fmt, ...) \ + printf("%s:%d:trace: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__) +#define LFS_TRACE(...) LFS_TRACE_(__VA_ARGS__, "") +#else +#define LFS_TRACE(...) +#endif + +#ifndef LFS_NO_DEBUG +#define LFS_DEBUG_(fmt, ...) \ + printf("%s:%d:debug: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__) +#define LFS_DEBUG(...) LFS_DEBUG_(__VA_ARGS__, "") +#else +#define LFS_DEBUG(...) +#endif + +#ifndef LFS_NO_WARN +#define LFS_WARN_(fmt, ...) \ + printf("%s:%d:warn: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__) +#define LFS_WARN(...) LFS_WARN_(__VA_ARGS__, "") +#else +#define LFS_WARN(...) +#endif + +#ifndef LFS_NO_ERROR +#define LFS_ERROR_(fmt, ...) \ + printf("%s:%d:error: " fmt "%s\n", __FILE__, __LINE__, __VA_ARGS__) +#define LFS_ERROR(...) LFS_ERROR_(__VA_ARGS__, "") +#else +#define LFS_ERROR(...) +#endif + +// Runtime assertions +#ifndef LFS_NO_ASSERT +#define LFS_ASSERT(test) assert(test) +#else +#define LFS_ASSERT(test) +#endif + + +// Builtin functions, these may be replaced by more efficient +// toolchain-specific implementations. LFS_NO_INTRINSICS falls back to a more +// expensive basic C implementation for debugging purposes + +// Min/max functions for unsigned 32-bit numbers +static inline uint32_t lfs_max(uint32_t a, uint32_t b) { + return (a > b) ? a : b; +} + +static inline uint32_t lfs_min(uint32_t a, uint32_t b) { + return (a < b) ? a : b; +} + +// Align to nearest multiple of a size +static inline uint32_t lfs_aligndown(uint32_t a, uint32_t alignment) { + return a - (a % alignment); +} + +static inline uint32_t lfs_alignup(uint32_t a, uint32_t alignment) { + return lfs_aligndown(a + alignment-1, alignment); +} + +// Find the smallest power of 2 greater than or equal to a +static inline uint32_t lfs_npw2(uint32_t a) { +#if !defined(LFS_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM)) + return 32 - __builtin_clz(a-1); +#else + uint32_t r = 0; + uint32_t s; + a -= 1; + s = (a > 0xffff) << 4; a >>= s; r |= s; + s = (a > 0xff ) << 3; a >>= s; r |= s; + s = (a > 0xf ) << 2; a >>= s; r |= s; + s = (a > 0x3 ) << 1; a >>= s; r |= s; + return (r | (a >> 1)) + 1; +#endif +} + +// Count the number of trailing binary zeros in a +// lfs_ctz(0) may be undefined +static inline uint32_t lfs_ctz(uint32_t a) { +#if !defined(LFS_NO_INTRINSICS) && defined(__GNUC__) + return __builtin_ctz(a); +#else + return lfs_npw2((a & -a) + 1) - 1; +#endif +} + +// Count the number of binary ones in a +static inline uint32_t lfs_popc(uint32_t a) { +#if !defined(LFS_NO_INTRINSICS) && (defined(__GNUC__) || defined(__CC_ARM)) + return __builtin_popcount(a); +#else + a = a - ((a >> 1) & 0x55555555); + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); + return (((a + (a >> 4)) & 0xf0f0f0f) * 0x1010101) >> 24; +#endif +} + +// Find the sequence comparison of a and b, this is the distance +// between a and b ignoring overflow +static inline int lfs_scmp(uint32_t a, uint32_t b) { + return (int)(unsigned)(a - b); +} + +// Convert between 32-bit little-endian and native order +static inline uint32_t lfs_fromle32(uint32_t a) { +#if !defined(LFS_NO_INTRINSICS) && ( \ + (defined( BYTE_ORDER ) && defined( ORDER_LITTLE_ENDIAN ) && BYTE_ORDER == ORDER_LITTLE_ENDIAN ) || \ + (defined(__BYTE_ORDER ) && defined(__ORDER_LITTLE_ENDIAN ) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN ) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) + return a; +#elif !defined(LFS_NO_INTRINSICS) && ( \ + (defined( BYTE_ORDER ) && defined( ORDER_BIG_ENDIAN ) && BYTE_ORDER == ORDER_BIG_ENDIAN ) || \ + (defined(__BYTE_ORDER ) && defined(__ORDER_BIG_ENDIAN ) && __BYTE_ORDER == __ORDER_BIG_ENDIAN ) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) + return __builtin_bswap32(a); +#else + return (((uint8_t*)&a)[0] << 0) | + (((uint8_t*)&a)[1] << 8) | + (((uint8_t*)&a)[2] << 16) | + (((uint8_t*)&a)[3] << 24); +#endif +} + +static inline uint32_t lfs_tole32(uint32_t a) { + return lfs_fromle32(a); +} + +// Convert between 32-bit big-endian and native order +static inline uint32_t lfs_frombe32(uint32_t a) { +#if !defined(LFS_NO_INTRINSICS) && ( \ + (defined( BYTE_ORDER ) && defined( ORDER_LITTLE_ENDIAN ) && BYTE_ORDER == ORDER_LITTLE_ENDIAN ) || \ + (defined(__BYTE_ORDER ) && defined(__ORDER_LITTLE_ENDIAN ) && __BYTE_ORDER == __ORDER_LITTLE_ENDIAN ) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) + return __builtin_bswap32(a); +#elif !defined(LFS_NO_INTRINSICS) && ( \ + (defined( BYTE_ORDER ) && defined( ORDER_BIG_ENDIAN ) && BYTE_ORDER == ORDER_BIG_ENDIAN ) || \ + (defined(__BYTE_ORDER ) && defined(__ORDER_BIG_ENDIAN ) && __BYTE_ORDER == __ORDER_BIG_ENDIAN ) || \ + (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) + return a; +#else + return (((uint8_t*)&a)[0] << 24) | + (((uint8_t*)&a)[1] << 16) | + (((uint8_t*)&a)[2] << 8) | + (((uint8_t*)&a)[3] << 0); +#endif +} + +static inline uint32_t lfs_tobe32(uint32_t a) { + return lfs_frombe32(a); +} + +// Calculate CRC-32 with polynomial = 0x04c11db7 +uint32_t lfs_crc(uint32_t crc, const void *buffer, size_t size); + +// Allocate memory, only used if buffers are not provided to littlefs +// Note, memory must be 64-bit aligned +static inline void *lfs_malloc(size_t size) { +#ifndef LFS_NO_MALLOC + return malloc(size); +#else + (void)size; + return NULL; +#endif +} + +// Deallocate memory, only used if buffers are not provided to littlefs +static inline void lfs_free(void *p) { +#ifndef LFS_NO_MALLOC + free(p); +#else + (void)p; +#endif +} + + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif +#endif diff --git a/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs_api.h b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs_api.h new file mode 100644 index 00000000..135b0597 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_littlefs/src/littlefs_api.h @@ -0,0 +1,106 @@ +#ifndef ESP_LITTLEFS_API_H__ +#define ESP_LITTLEFS_API_H__ + +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/semphr.h" +#include "esp_vfs.h" +#include "esp_partition.h" +#include "littlefs/lfs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief a file descriptor + * That's also a singly linked list used for keeping tracks of all opened file descriptor + * + * Shortcomings/potential issues of 32-bit hash (when CONFIG_LITTLEFS_USE_ONLY_HASH) listed here: + * * unlink - If a different file is open that generates a hash collision, it will report an + * error that it cannot unlink an open file. + * * rename - If a different file is open that generates a hash collision with + * src or dst, it will report an error that it cannot rename an open file. + * Potential consequences: + * 1. A file cannot be deleted while a collision-geneating file is open. + * Worst-case, if the other file is always open during the lifecycle + * of your app, it's collision file cannot be deleted, which in the + * worst-case could cause storage-capacity issues. + * 2. Same as (1), but for renames + */ +typedef struct _vfs_littlefs_file_t { + lfs_file_t file; + uint32_t hash; + struct _vfs_littlefs_file_t * next; /*!< Pointer to next file in Singly Linked List */ +#ifndef CONFIG_LITTLEFS_USE_ONLY_HASH + char * path; +#endif +} vfs_littlefs_file_t; + +/** + * @brief littlefs definition structure + */ +typedef struct { + lfs_t *fs; /*!< Handle to the underlying littlefs */ + SemaphoreHandle_t lock; /*!< FS lock */ + const esp_partition_t* partition; /*!< The partition on which littlefs is located */ + char base_path[ESP_VFS_PATH_MAX+1]; /*!< Mount point */ + + struct lfs_config cfg; /*!< littlefs Mount configuration */ + + vfs_littlefs_file_t *file; /*!< Singly Linked List of files */ + + vfs_littlefs_file_t **cache; /*!< A cache of pointers to the opened files */ + uint16_t cache_size; /*!< The cache allocated size (in pointers) */ + uint16_t fd_count; /*!< The count of opened file descriptor used to speed up computation */ +} esp_littlefs_t; + +/** + * @brief Read a region in a block. + * + * Negative error codes are propogated to the user. + * + * @return errorcode. 0 on success. + */ +int littlefs_api_read(const struct lfs_config *c, lfs_block_t block, + lfs_off_t off, void *buffer, lfs_size_t size); + +/** + * @brief Program a region in a block. + * + * The block must have previously been erased. + * Negative error codes are propogated to the user. + * May return LFS_ERR_CORRUPT if the block should be considered bad. + * + * @return errorcode. 0 on success. + */ +int littlefs_api_prog(const struct lfs_config *c, lfs_block_t block, + lfs_off_t off, const void *buffer, lfs_size_t size); + +/** + * @brief Erase a block. + * + * A block must be erased before being programmed. + * The state of an erased block is undefined. + * Negative error codes are propogated to the user. + * May return LFS_ERR_CORRUPT if the block should be considered bad. + * @return errorcode. 0 on success. + */ +int littlefs_api_erase(const struct lfs_config *c, lfs_block_t block); + +/** + * @brief Sync the state of the underlying block device. + * + * Negative error codes are propogated to the user. + * + * @return errorcode. 0 on success. + */ +int littlefs_api_sync(const struct lfs_config *c); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_local_ctrl/include/esp_local_ctrl.h b/tools/sdk/esp32c3/include/esp_local_ctrl/include/esp_local_ctrl.h new file mode 100644 index 00000000..9f4f89da --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_local_ctrl/include/esp_local_ctrl.h @@ -0,0 +1,339 @@ +// Copyright 2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * @brief Property description data structure, which is to be populated + * and passed to the `esp_local_ctrl_add_property()` function + * + * Once a property is added, its structure is available for read-only access + * inside `get_prop_values()` and `set_prop_values()` handlers. + */ +typedef struct esp_local_ctrl_prop { + /** + * Unique name of property + */ + char *name; + + /** + * Type of property. This may be set to application defined enums + */ + uint32_t type; + + /** + * Size of the property value, which: + * - if zero, the property can have values of variable size + * - if non-zero, the property can have values of fixed size only, + * therefore, checks are performed internally by esp_local_ctrl + * when setting the value of such a property + */ + size_t size; + + /** + * Flags set for this property. This could be a bit field. + * A flag may indicate property behavior, e.g. read-only / constant + */ + uint32_t flags; + + /** + * Pointer to some context data relevant for this property. This will + * be available for use inside the `get_prop_values` and `set_prop_values` + * handlers as a part of this property structure. When set, this is valid + * throughout the lifetime of a property, till either the property is + * removed or the esp_local_ctrl service is stopped. + */ + void *ctx; + + /** + * Function used by esp_local_ctrl to internally free the property + * context when `esp_local_ctrl_remove_property()` or + * `esp_local_ctrl_stop()` is called. + */ + void (*ctx_free_fn)(void *ctx); +} esp_local_ctrl_prop_t; + +/** + * @brief Property value data structure. This gets passed to the + * `get_prop_values()` and `set_prop_values()` handlers for + * the purpose of retrieving or setting the present value + * of a property. + */ +typedef struct esp_local_ctrl_prop_val { + /** + * Pointer to memory holding property value + */ + void *data; + + /** + * Size of property value + */ + size_t size; + + /** + * This may be set by the application in `get_prop_values()` handler + * to tell `esp_local_ctrl` to call this function on the data pointer + * above, for freeing its resources after sending the `get_prop_values` + * response. + */ + void (*free_fn)(void *data); +} esp_local_ctrl_prop_val_t; + +/** + * @brief Handlers for receiving and responding to local + * control commands for getting and setting properties. + */ +typedef struct esp_local_ctrl_handlers { + /** + * @brief Handler function to be implemented for retrieving current + * values of properties + * + * @note If any of the properties have fixed sizes, the size field of + * corresponding element in `prop_values` need to be set + * + * @param[in] props_count Total elements in the props array + * @param[in] props Array of properties, the current values for which + * have been requested by the client + * @param[out] prop_values Array of empty property values, the elements of + * which need to be populated with the current values + * of those properties specified by props argument + * @param[in] usr_ctx This provides value of the `usr_ctx` field of + * `esp_local_ctrl_handlers_t` structure + * + * @return Returning different error codes will convey the corresponding + * protocol level errors to the client : + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : InvalidArgument + * - ESP_ERR_INVALID_STATE : InvalidProto + * - All other error codes : InternalError + */ + esp_err_t (*get_prop_values)(size_t props_count, + const esp_local_ctrl_prop_t props[], + esp_local_ctrl_prop_val_t prop_values[], + void *usr_ctx); + + /** + * @brief Handler function to be implemented for changing values of properties + * + * @note If any of the properties have variable sizes, the size field + * of the corresponding element in `prop_values` must be checked + * explicitly before making any assumptions on the size. + * + * @param[in] props_count Total elements in the props array + * @param[in] props Array of properties, the values for which the + * client requests to change + * @param[in] prop_values Array of property values, the elements of which + * need to be used for updating those properties + * specified by props argument + * @param[in] usr_ctx This provides value of the `usr_ctx` field of + * `esp_local_ctrl_handlers_t` structure + * + * @return Returning different error codes will convey the corresponding + * protocol level errors to the client : + * - ESP_OK : Success + * - ESP_ERR_INVALID_ARG : InvalidArgument + * - ESP_ERR_INVALID_STATE : InvalidProto + * - All other error codes : InternalError + */ + esp_err_t (*set_prop_values)(size_t props_count, + const esp_local_ctrl_prop_t props[], + const esp_local_ctrl_prop_val_t prop_values[], + void *usr_ctx); + + /** + * Context pointer to be passed to above handler functions upon invocation. + * This is different from the property level context, as this is valid + * throughout the lifetime of the `esp_local_ctrl` service, and freed only + * when the service is stopped. + */ + void *usr_ctx; + + /** + * Pointer to function which will be internally invoked on `usr_ctx` for + * freeing the context resources when `esp_local_ctrl_stop()` is called. + */ + void (*usr_ctx_free_fn)(void *usr_ctx); +} esp_local_ctrl_handlers_t; + +/** + * @brief Transport mode (BLE / HTTPD) over which the service will be provided + * + * This is forward declaration of a private structure, implemented internally + * by `esp_local_ctrl`. + */ +typedef struct esp_local_ctrl_transport esp_local_ctrl_transport_t; + +/** + * @brief Function for obtaining BLE transport mode + */ +const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_ble(void); + +/** + * @brief Function for obtaining HTTPD transport mode + */ +const esp_local_ctrl_transport_t *esp_local_ctrl_get_transport_httpd(void); + +#define ESP_LOCAL_CTRL_TRANSPORT_BLE esp_local_ctrl_get_transport_ble() +#define ESP_LOCAL_CTRL_TRANSPORT_HTTPD esp_local_ctrl_get_transport_httpd() + +/** + * @brief Configuration for transport mode BLE + * + * This is a forward declaration for `protocomm_ble_config_t`. + * To use this, application must set CONFIG_BT_BLUEDROID_ENABLED + * and include `protocomm_ble.h`. + */ +typedef struct protocomm_ble_config esp_local_ctrl_transport_config_ble_t; + +/** + * @brief Configuration for transport mode HTTPD + * + * This is a forward declaration for `httpd_ssl_config_t`. + * To use this, application must set CONFIG_ESP_HTTPS_SERVER_ENABLE + * and include `esp_https_server.h` + */ +typedef struct httpd_ssl_config esp_local_ctrl_transport_config_httpd_t; + +/** + * @brief Transport mode (BLE / HTTPD) configuration + */ +typedef union { + /** + * This is same as `protocomm_ble_config_t`. See `protocomm_ble.h` for + * available configuration parameters. + */ + esp_local_ctrl_transport_config_ble_t *ble; + + /** + * This is same as `httpd_ssl_config_t`. See `esp_https_server.h` for + * available configuration parameters. + */ + esp_local_ctrl_transport_config_httpd_t *httpd; +} esp_local_ctrl_transport_config_t; + +/** + * @brief Configuration structure to pass to `esp_local_ctrl_start()` + */ +typedef struct esp_local_ctrl_config { + /** + * Transport layer over which service will be provided + */ + const esp_local_ctrl_transport_t *transport; + + /** + * Transport layer over which service will be provided + */ + esp_local_ctrl_transport_config_t transport_config; + + /** + * Register handlers for responding to get/set requests on properties + */ + esp_local_ctrl_handlers_t handlers; + + /** + * This limits the number of properties that are available at a time + */ + size_t max_properties; +} esp_local_ctrl_config_t; + +/** + * @brief Start local control service + * + * @param[in] config Pointer to configuration structure + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Failure + */ +esp_err_t esp_local_ctrl_start(const esp_local_ctrl_config_t *config); + +/** + * @brief Stop local control service + */ +esp_err_t esp_local_ctrl_stop(void); + +/** + * @brief Add a new property + * + * This adds a new property and allocates internal resources for it. + * The total number of properties that could be added is limited by + * configuration option `max_properties` + * + * @param[in] prop Property description structure + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Failure + */ +esp_err_t esp_local_ctrl_add_property(const esp_local_ctrl_prop_t *prop); + +/** + * @brief Remove a property + * + * This finds a property by name, and releases the internal resources + * which are associated with it. + * + * @param[in] name Name of the property to remove + * + * @return + * - ESP_OK : Success + * - ESP_ERR_NOT_FOUND : Failure + */ +esp_err_t esp_local_ctrl_remove_property(const char *name); + +/** + * @brief Get property description structure by name + * + * This API may be used to get a property's context structure + * `esp_local_ctrl_prop_t` when its name is known + * + * @param[in] name Name of the property to find + * + * @return + * - Pointer to property + * - NULL if not found + */ +const esp_local_ctrl_prop_t *esp_local_ctrl_get_property(const char *name); + +/** + * @brief Register protocomm handler for a custom endpoint + * + * This API can be called by the application to register a protocomm handler + * for an endpoint after the local control service has started. + * + * @note In case of BLE transport the names and uuids of all custom + * endpoints must be provided beforehand as a part of the `protocomm_ble_config_t` + * structure set in `esp_local_ctrl_config_t`, and passed to `esp_local_ctrl_start()`. + * + * @param[in] ep_name Name of the endpoint + * @param[in] handler Endpoint handler function + * @param[in] user_ctx User data + * + * @return + * - ESP_OK : Success + * - ESP_FAIL : Failure + */ +esp_err_t esp_local_ctrl_set_handler(const char *ep_name, + protocomm_req_handler_t handler, + void *user_ctx); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif.h new file mode 100644 index 00000000..20f46873 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif.h @@ -0,0 +1,868 @@ +// Copyright 2019 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. + +#ifndef _ESP_NETIF_H_ +#define _ESP_NETIF_H_ + +#include +#include "sdkconfig.h" +#include "esp_wifi_types.h" +#include "esp_netif_ip_addr.h" +#include "esp_netif_types.h" +#include "esp_netif_defaults.h" + +#if CONFIG_ETH_ENABLED +#include "esp_eth_netif_glue.h" +#endif + +// +// Note: tcpip_adapter legacy API has to be included by default to provide full compatibility +// for applications that used tcpip_adapter API without explicit inclusion of tcpip_adapter.h +// +#if CONFIG_ESP_NETIF_TCPIP_ADAPTER_COMPATIBLE_LAYER +#define _ESP_NETIF_SUPPRESS_LEGACY_WARNING_ +#include "tcpip_adapter.h" +#undef _ESP_NETIF_SUPPRESS_LEGACY_WARNING_ +#endif // CONFIG_ESP_NETIF_TCPIP_ADAPTER_COMPATIBLE_LAYER + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @defgroup ESP_NETIF_INIT_API ESP-NETIF Initialization API + * @brief Initialization and deinitialization of underlying TCP/IP stack and esp-netif instances + * + */ + +/** @addtogroup ESP_NETIF_INIT_API + * @{ + */ + +/** + * @brief Initialize the underlying TCP/IP stack + * + * @return + * - ESP_OK on success + * - ESP_FAIL if initializing failed + + * @note This function should be called exactly once from application code, when the application starts up. + */ +esp_err_t esp_netif_init(void); + +/** + * @brief Deinitialize the esp-netif component (and the underlying TCP/IP stack) + * + * Note: Deinitialization is not supported yet + * + * @return + * - ESP_ERR_INVALID_STATE if esp_netif not initialized + * - ESP_ERR_NOT_SUPPORTED otherwise + */ +esp_err_t esp_netif_deinit(void); + +/** + * @brief Creates an instance of new esp-netif object based on provided config + * + * @param[in] esp_netif_config pointer esp-netif configuration + * + * @return + * - pointer to esp-netif object on success + * - NULL otherwise + */ +esp_netif_t *esp_netif_new(const esp_netif_config_t *esp_netif_config); + +/** + * @brief Destroys the esp_netif object + * + * @param[in] esp_netif pointer to the object to be deleted + */ +void esp_netif_destroy(esp_netif_t *esp_netif); + +/** + * @brief Configures driver related options of esp_netif object + * + * @param[inout] esp_netif pointer to the object to be configured + * @param[in] driver_config pointer esp-netif io driver related configuration + * @return + * - ESP_OK on success + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS if invalid parameters provided + * + */ +esp_err_t esp_netif_set_driver_config(esp_netif_t *esp_netif, + const esp_netif_driver_ifconfig_t *driver_config); + +/** + * @brief Attaches esp_netif instance to the io driver handle + * + * Calling this function enables connecting specific esp_netif object + * with already initialized io driver to update esp_netif object with driver + * specific configuration (i.e. calls post_attach callback, which typically + * sets io driver callbacks to esp_netif instance and starts the driver) + * + * @param[inout] esp_netif pointer to esp_netif object to be attached + * @param[in] driver_handle pointer to the driver handle + * @return + * - ESP_OK on success + * - ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED if driver's pot_attach callback failed + */ +esp_err_t esp_netif_attach(esp_netif_t *esp_netif, esp_netif_iodriver_handle driver_handle); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_DATA_IO_API ESP-NETIF Input Output API + * @brief Input and Output functions to pass data packets from communication media (IO driver) + * to TCP/IP stack. + * + * These functions are usually not directly called from user code, but installed, or registered + * as callbacks in either IO driver on one hand or TCP/IP stack on the other. More specifically + * esp_netif_receive is typically called from io driver on reception callback to input the packets + * to TCP/IP stack. Similarly esp_netif_transmit is called from the TCP/IP stack whenever + * a packet ought to output to the communication media. + * + * @note These IO functions are registerd (installed) automatically for default interfaces + * (interfaces with the keys such as WIFI_STA_DEF, WIFI_AP_DEF, ETH_DEF). Custom interface + * has to register these IO functions when creating interface using @ref esp_netif_new + * + */ + +/** @addtogroup ESP_NETIF_DATA_IO_API + * @{ + */ + +/** + * @brief Passes the raw packets from communication media to the appropriate TCP/IP stack + * + * This function is called from the configured (peripheral) driver layer. + * The data are then forwarded as frames to the TCP/IP stack. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] buffer Received data + * @param[in] len Length of the data frame + * @param[in] eb Pointer to internal buffer (used in Wi-Fi driver) + * + * @return + * - ESP_OK + */ +esp_err_t esp_netif_receive(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_LIFECYCLE ESP-NETIF Lifecycle control + * @brief These APIS define basic building blocks to control network interface lifecycle, i.e. + * start, stop, set_up or set_down. These functions can be directly used as event handlers + * registered to follow the events from communication media. + */ + +/** @addtogroup ESP_NETIF_LIFECYCLE + * @{ + */ + +/** + * @brief Default building block for network interface action upon IO driver start event + * Creates network interface, if AUTOUP enabled turns the interface on, + * if DHCPS enabled starts dhcp server + * + * @note This API can be directly used as event handler + * + * @param[in] esp_netif Handle to esp-netif instance + * @param base + * @param event_id + * @param data + */ +void esp_netif_action_start(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data); + +/** + * @brief Default building block for network interface action upon IO driver stop event + * + * @note This API can be directly used as event handler + * + * @param[in] esp_netif Handle to esp-netif instance + * @param base + * @param event_id + * @param data + */ +void esp_netif_action_stop(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data); + +/** + * @brief Default building block for network interface action upon IO driver connected event + * + * @note This API can be directly used as event handler + * + * @param[in] esp_netif Handle to esp-netif instance + * @param base + * @param event_id + * @param data + */ +void esp_netif_action_connected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data); + +/** + * @brief Default building block for network interface action upon IO driver disconnected event + * + * @note This API can be directly used as event handler + * + * @param[in] esp_netif Handle to esp-netif instance + * @param base + * @param event_id + * @param data + */ +void esp_netif_action_disconnected(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data); + +/** + * @brief Default building block for network interface action upon network got IP event + * + * @note This API can be directly used as event handler + * + * @param[in] esp_netif Handle to esp-netif instance + * @param base + * @param event_id + * @param data + */ +void esp_netif_action_got_ip(void *esp_netif, esp_event_base_t base, int32_t event_id, void *data); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_GET_SET ESP-NETIF Runtime configuration + * @brief Getters and setters for various TCP/IP related parameters + */ + +/** @addtogroup ESP_NETIF_GET_SET + * @{ + */ + +/** + * @brief Set the mac address for the interface instance + + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] mac Desired mac address for the related network interface + * @return + * - ESP_OK - success + * - ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error + * - ESP_ERR_NOT_SUPPORTED - mac not supported on this interface + */ +esp_err_t esp_netif_set_mac(esp_netif_t *esp_netif, uint8_t mac[]); + +/** + * @brief Get the mac address for the interface instance + + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] mac Resultant mac address for the related network interface + * @return + * - ESP_OK - success + * - ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error + * - ESP_ERR_NOT_SUPPORTED - mac not supported on this interface + */ +esp_err_t esp_netif_get_mac(esp_netif_t *esp_netif, uint8_t mac[]); + +/** + * @brief Set the hostname of an interface + * + * The configured hostname overrides the default configuration value CONFIG_LWIP_LOCAL_HOSTNAME. + * Please note that when the hostname is altered after interface started/connected the changes + * would only be reflected once the interface restarts/reconnects + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] hostname New hostname for the interface. Maximum length 32 bytes. + * + * @return + * - ESP_OK - success + * - ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error + */ +esp_err_t esp_netif_set_hostname(esp_netif_t *esp_netif, const char *hostname); + +/** + * @brief Get interface hostname. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] hostname Returns a pointer to the hostname. May be NULL if no hostname is set. If set non-NULL, pointer remains valid (and string may change if the hostname changes). + * + * @return + * - ESP_OK - success + * - ESP_ERR_ESP_NETIF_IF_NOT_READY - interface status error + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS - parameter error + */ +esp_err_t esp_netif_get_hostname(esp_netif_t *esp_netif, const char **hostname); + +/** + * @brief Test if supplied interface is up or down + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - true - Interface is up + * - false - Interface is down + */ +bool esp_netif_is_netif_up(esp_netif_t *esp_netif); + +/** + * @brief Get interface's IP address information + * + * If the interface is up, IP information is read directly from the TCP/IP stack. + * If the interface is down, IP information is read from a copy kept in the ESP-NETIF instance + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] ip_info If successful, IP information will be returned in this argument. + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + */ +esp_err_t esp_netif_get_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info); + +/** + * @brief Get interface's old IP information + * + * Returns an "old" IP address previously stored for the interface when the valid IP changed. + * + * If the IP lost timer has expired (meaning the interface was down for longer than the configured interval) + * then the old IP information will be zero. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] ip_info If successful, IP information will be returned in this argument. + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + */ +esp_err_t esp_netif_get_old_ip_info(esp_netif_t *esp_netif, esp_netif_ip_info_t *ip_info); + +/** + * @brief Set interface's IP address information + * + * This function is mainly used to set a static IP on an interface. + * + * If the interface is up, the new IP information is set directly in the TCP/IP stack. + * + * The copy of IP information kept in the ESP-NETIF instance is also updated (this + * copy is returned if the IP is queried while the interface is still down.) + * + * @note DHCP client/server must be stopped (if enabled for this interface) before setting new IP information. + * + * @note Calling this interface for may generate a SYSTEM_EVENT_STA_GOT_IP or SYSTEM_EVENT_ETH_GOT_IP event. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] ip_info IP information to set on the specified interface + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED If DHCP server or client is still running + */ +esp_err_t esp_netif_set_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info); + +/** + * @brief Set interface old IP information + * + * This function is called from the DHCP client (if enabled), before a new IP is set. + * It is also called from the default handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events. + * + * Calling this function stores the previously configured IP, which can be used to determine if the IP changes in the future. + * + * If the interface is disconnected or down for too long, the "IP lost timer" will expire (after the configured interval) and set the old IP information to zero. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] ip_info Store the old IP information for the specified interface + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + */ +esp_err_t esp_netif_set_old_ip_info(esp_netif_t *esp_netif, const esp_netif_ip_info_t *ip_info); + +/** + * @brief Get net interface index from network stack implementation + * + * @note This index could be used in `setsockopt()` to bind socket with multicast interface + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * implementation specific index of interface represented with supplied esp_netif + */ +int esp_netif_get_netif_impl_index(esp_netif_t *esp_netif); + +/** + * @brief Get net interface name from network stack implementation + * + * @note This name could be used in `setsockopt()` to bind socket with appropriate interface + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] name Interface name as specified in underlying TCP/IP stack. Note that the + * actual name will be copied to the specified buffer, which must be allocated to hold + * maximum interface name size (6 characters for lwIP) + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS +*/ +esp_err_t esp_netif_get_netif_impl_name(esp_netif_t *esp_netif, char* name); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_NET_DHCP ESP-NETIF DHCP Settings + * @brief Network stack related interface to DHCP client and server + */ + +/** @addtogroup ESP_NETIF_NET_DHCP + * @{ + */ + +/** + * @brief Set or Get DHCP server option + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] opt_op ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. + * @param[in] opt_id Option index to get or set, must be one of the supported enum values. + * @param[inout] opt_val Pointer to the option parameter. + * @param[in] opt_len Length of the option parameter. + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED + */ +esp_err_t +esp_netif_dhcps_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, + void *opt_val, uint32_t opt_len); + +/** + * @brief Set or Get DHCP client option + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] opt_op ESP_NETIF_OP_SET to set an option, ESP_NETIF_OP_GET to get an option. + * @param[in] opt_id Option index to get or set, must be one of the supported enum values. + * @param[inout] opt_val Pointer to the option parameter. + * @param[in] opt_len Length of the option parameter. + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED + */ +esp_err_t +esp_netif_dhcpc_option(esp_netif_t *esp_netif, esp_netif_dhcp_option_mode_t opt_op, esp_netif_dhcp_option_id_t opt_id, + void *opt_val, uint32_t opt_len); + +/** + * @brief Start DHCP client (only if enabled in interface object) + * + * @note The default event handlers for the SYSTEM_EVENT_STA_CONNECTED and SYSTEM_EVENT_ETH_CONNECTED events call this function. + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED + * - ESP_ERR_ESP_NETIF_DHCPC_START_FAILED + */ +esp_err_t esp_netif_dhcpc_start(esp_netif_t *esp_netif); + +/** + * @brief Stop DHCP client (only if enabled in interface object) + * + * @note Calling action_netif_stop() will also stop the DHCP Client if it is running. + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED + * - ESP_ERR_ESP_NETIF_IF_NOT_READY + */ +esp_err_t esp_netif_dhcpc_stop(esp_netif_t *esp_netif); + +/** + * @brief Get DHCP client status + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] status If successful, the status of DHCP client will be returned in this argument. + * + * @return + * - ESP_OK + */ +esp_err_t esp_netif_dhcpc_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status); + +/** + * @brief Get DHCP Server status + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] status If successful, the status of the DHCP server will be returned in this argument. + * + * @return + * - ESP_OK + */ +esp_err_t esp_netif_dhcps_get_status(esp_netif_t *esp_netif, esp_netif_dhcp_status_t *status); + +/** + * @brief Start DHCP server (only if enabled in interface object) + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED + */ +esp_err_t esp_netif_dhcps_start(esp_netif_t *esp_netif); + +/** + * @brief Stop DHCP server (only if enabled in interface object) + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + * - ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED + * - ESP_ERR_ESP_NETIF_IF_NOT_READY + */ +esp_err_t esp_netif_dhcps_stop(esp_netif_t *esp_netif); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_NET_DNS ESP-NETIF DNS Settings + * @brief Network stack related interface to NDS + */ + +/** @addtogroup ESP_NETIF_NET_DNS + * @{ + */ + +/** + * @brief Set DNS Server information + * + * This function behaves differently if DHCP server or client is enabled + * + * If DHCP client is enabled, main and backup DNS servers will be updated automatically + * from the DHCP lease if the relevant DHCP options are set. Fallback DNS Server is never updated from the DHCP lease + * and is designed to be set via this API. + * If DHCP client is disabled, all DNS server types can be set via this API only. + * + * If DHCP server is enabled, the Main DNS Server setting is used by the DHCP server to provide a DNS Server option + * to DHCP clients (Wi-Fi stations). + * - The default Main DNS server is typically the IP of the Wi-Fi AP interface itself. + * - This function can override it by setting server type ESP_NETIF_DNS_MAIN. + * - Other DNS Server types are not supported for the Wi-Fi AP interface. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] type Type of DNS Server to set: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK + * @param[in] dns DNS Server address to set + * + * @return + * - ESP_OK on success + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params + */ +esp_err_t esp_netif_set_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns); + +/** + * @brief Get DNS Server information + * + * Return the currently configured DNS Server address for the specified interface and Server type. + * + * This may be result of a previous call to esp_netif_set_dns_info(). If the interface's DHCP client is enabled, + * the Main or Backup DNS Server may be set by the current DHCP lease. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] type Type of DNS Server to get: ESP_NETIF_DNS_MAIN, ESP_NETIF_DNS_BACKUP, ESP_NETIF_DNS_FALLBACK + * @param[out] dns DNS Server result is written here on success + * + * @return + * - ESP_OK on success + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS invalid params + */ +esp_err_t esp_netif_get_dns_info(esp_netif_t *esp_netif, esp_netif_dns_type_t type, esp_netif_dns_info_t *dns); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_NET_IP ESP-NETIF IP address related interface + * @brief Network stack related interface to IP + */ + +/** @addtogroup ESP_NETIF_NET_IP + * @{ + */ +#if CONFIG_LWIP_IPV6 +/** + * @brief Create interface link-local IPv6 address + * + * Cause the TCP/IP stack to create a link-local IPv6 address for the specified interface. + * + * This function also registers a callback for the specified interface, so that if the link-local address becomes + * verified as the preferred address then a SYSTEM_EVENT_GOT_IP6 event will be sent. + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + */ +esp_err_t esp_netif_create_ip6_linklocal(esp_netif_t *esp_netif); + +/** + * @brief Get interface link-local IPv6 address + * + * If the specified interface is up and a preferred link-local IPv6 address + * has been created for the interface, return a copy of it. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] if_ip6 IPv6 information will be returned in this argument if successful. + * + * @return + * - ESP_OK + * - ESP_FAIL If interface is down, does not have a link-local IPv6 address, + * or the link-local IPv6 address is not a preferred address. + */ +esp_err_t esp_netif_get_ip6_linklocal(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6); + +/** + * @brief Get interface global IPv6 address + * + * If the specified interface is up and a preferred global IPv6 address + * has been created for the interface, return a copy of it. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] if_ip6 IPv6 information will be returned in this argument if successful. + * + * @return + * - ESP_OK + * - ESP_FAIL If interface is down, does not have a global IPv6 address, + * or the global IPv6 address is not a preferred address. + */ +esp_err_t esp_netif_get_ip6_global(esp_netif_t *esp_netif, esp_ip6_addr_t *if_ip6); + +/** + * @brief Get all IPv6 addresses of the specified interface + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[out] if_ip6 Array of IPv6 addresses will be copied to the argument + * + * @return + * number of returned IPv6 addresses + */ +int esp_netif_get_all_ip6(esp_netif_t *esp_netif, esp_ip6_addr_t if_ip6[]); +#endif + +/** + * @brief Sets IPv4 address to the specified octets + * + * @param[out] addr IP address to be set + * @param a the first octet (127 for IP 127.0.0.1) + * @param b + * @param c + * @param d + */ +void esp_netif_set_ip4_addr(esp_ip4_addr_t *addr, uint8_t a, uint8_t b, uint8_t c, uint8_t d); + + +/** + * @brief Converts numeric IP address into decimal dotted ASCII representation. + * + * @param addr ip address in network order to convert + * @param buf target buffer where the string is stored + * @param buflen length of buf + * @return either pointer to buf which now holds the ASCII + * representation of addr or NULL if buf was too small + */ +char *esp_ip4addr_ntoa(const esp_ip4_addr_t *addr, char *buf, int buflen); + +/** + * @brief Ascii internet address interpretation routine + * The value returned is in network order. + * + * @param addr IP address in ascii representation (e.g. "127.0.0.1") + * @return ip address in network order +*/ +uint32_t esp_ip4addr_aton(const char *addr); + +/** + * @brief Converts Ascii internet IPv4 address into esp_ip4_addr_t + * + * @param[in] src IPv4 address in ascii representation (e.g. "127.0.0.1") + * @param[out] dst Address of the target esp_ip4_addr_t structure to receive converted address + * @return + * - ESP_OK on success + * - ESP_FAIL if conversion failed + * - ESP_ERR_INVALID_ARG if invalid parameter is passed into + */ +esp_err_t esp_netif_str_to_ip4(const char *src, esp_ip4_addr_t *dst); + +/** + * @brief Converts Ascii internet IPv6 address into esp_ip4_addr_t + * Zeros in the IP address can be stripped or completely ommited: "2001:db8:85a3:0:0:0:2:1" or "2001:db8::2:1") + * + * @param[in] src IPv6 address in ascii representation (e.g. ""2001:0db8:85a3:0000:0000:0000:0002:0001") + * @param[out] dst Address of the target esp_ip6_addr_t structure to receive converted address + * @return + * - ESP_OK on success + * - ESP_FAIL if conversion failed + * - ESP_ERR_INVALID_ARG if invalid parameter is passed into + */ +esp_err_t esp_netif_str_to_ip6(const char *src, esp_ip6_addr_t *dst); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_CONVERT ESP-NETIF Conversion utilities + * @brief ESP-NETIF conversion utilities to related keys, flags, implementation handle + */ + +/** @addtogroup ESP_NETIF_CONVERT + * @{ + */ + +/** + * @brief Gets media driver handle for this esp-netif instance + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return opaque pointer of related IO driver + */ +esp_netif_iodriver_handle esp_netif_get_io_driver(esp_netif_t *esp_netif); + +/** + * @brief Searches over a list of created objects to find an instance with supplied if key + * + * @param if_key Textual description of network interface + * + * @return Handle to esp-netif instance + */ +esp_netif_t *esp_netif_get_handle_from_ifkey(const char *if_key); + +/** + * @brief Returns configured flags for this interface + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return Configuration flags + */ +esp_netif_flags_t esp_netif_get_flags(esp_netif_t *esp_netif); + +/** + * @brief Returns configured interface key for this esp-netif instance + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return Textual description of related interface + */ +const char *esp_netif_get_ifkey(esp_netif_t *esp_netif); + +/** + * @brief Returns configured interface type for this esp-netif instance + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return Enumerated type of this interface, such as station, AP, ethernet + */ +const char *esp_netif_get_desc(esp_netif_t *esp_netif); + +/** + * @brief Returns configured routing priority number + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return Integer representing the instance's route-prio, or -1 if invalid paramters + */ +int esp_netif_get_route_prio(esp_netif_t *esp_netif); + +/** + * @brief Returns configured event for this esp-netif instance and supplied event type + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @param event_type (either get or lost IP) + * + * @return specific event id which is configured to be raised if the interface lost or acquired IP address + * -1 if supplied event_type is not known + */ +int32_t esp_netif_get_event_id(esp_netif_t *esp_netif, esp_netif_ip_event_type_t event_type); + +/** + * @} + */ + +/** + * @defgroup ESP_NETIF_LIST ESP-NETIF List of interfaces + * @brief APIs to enumerate all registered interfaces + */ + +/** @addtogroup ESP_NETIF_LIST + * @{ + */ + +/** + * @brief Iterates over list of interfaces. Returns first netif if NULL given as parameter + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return First netif from the list if supplied parameter is NULL, next one otherwise + */ +esp_netif_t *esp_netif_next(esp_netif_t *esp_netif); + +/** + * @brief Returns number of registered esp_netif objects + * + * @return Number of esp_netifs + */ +size_t esp_netif_get_nr_of_ifs(void); + +/** + * @brief increase the reference counter of net stack buffer + * + * @param[in] netstack_buf the net stack buffer + * + */ +void esp_netif_netstack_buf_ref(void *netstack_buf); + +/** + * @brief free the netstack buffer + * + * @param[in] netstack_buf the net stack buffer + * + */ +void esp_netif_netstack_buf_free(void *netstack_buf); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ESP_NETIF_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_defaults.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_defaults.h new file mode 100644 index 00000000..7ef65260 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_defaults.h @@ -0,0 +1,201 @@ +// Copyright 2015-2016 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. + +#ifndef _ESP_NETIF_DEFAULTS_H +#define _ESP_NETIF_DEFAULTS_H + +#include "esp_compiler.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// +// Macros to assemble master configs with partial configs from netif, stack and driver +// + +#define ESP_NETIF_INHERENT_DEFAULT_WIFI_STA() \ + { \ + .flags = (esp_netif_flags_t)(ESP_NETIF_DHCP_CLIENT | ESP_NETIF_FLAG_GARP | ESP_NETIF_FLAG_EVENT_IP_MODIFIED), \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(mac) \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(ip_info) \ + .get_ip_event = IP_EVENT_STA_GOT_IP, \ + .lost_ip_event = IP_EVENT_STA_LOST_IP, \ + .if_key = "WIFI_STA_DEF", \ + .if_desc = "sta", \ + .route_prio = 100 \ + } \ + +#define ESP_NETIF_INHERENT_DEFAULT_WIFI_AP() \ + { \ + .flags = (esp_netif_flags_t)(ESP_NETIF_DHCP_SERVER | ESP_NETIF_FLAG_AUTOUP), \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(mac) \ + .ip_info = &_g_esp_netif_soft_ap_ip, \ + .get_ip_event = 0, \ + .lost_ip_event = 0, \ + .if_key = "WIFI_AP_DEF", \ + .if_desc = "ap", \ + .route_prio = 10 \ + }; + +#define ESP_NETIF_INHERENT_DEFAULT_ETH() \ + { \ + .flags = (esp_netif_flags_t)(ESP_NETIF_DHCP_CLIENT | ESP_NETIF_FLAG_GARP | ESP_NETIF_FLAG_EVENT_IP_MODIFIED), \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(mac) \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(ip_info) \ + .get_ip_event = IP_EVENT_ETH_GOT_IP, \ + .lost_ip_event = 0, \ + .if_key = "ETH_DEF", \ + .if_desc = "eth", \ + .route_prio = 50 \ + }; + +#define ESP_NETIF_INHERENT_DEFAULT_PPP() \ + { \ + .flags = ESP_NETIF_FLAG_IS_PPP, \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(mac) \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(ip_info) \ + .get_ip_event = IP_EVENT_PPP_GOT_IP, \ + .lost_ip_event = IP_EVENT_PPP_LOST_IP, \ + .if_key = "PPP_DEF", \ + .if_desc = "ppp", \ + .route_prio = 20 \ +}; + +#define ESP_NETIF_INHERENT_DEFAULT_SLIP() \ + { \ + .flags = ESP_NETIF_FLAG_IS_SLIP, \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(mac) \ + ESP_COMPILER_DESIGNATED_INIT_AGGREGATE_TYPE_EMPTY(ip_info) \ + .get_ip_event = 0, \ + .lost_ip_event = 0, \ + .if_key = "SLP_DEF", \ + .if_desc = "slip", \ + .route_prio = 16 \ +}; + +/** + * @brief Default configuration reference of ethernet interface + */ +#define ESP_NETIF_DEFAULT_ETH() \ + { \ + .base = ESP_NETIF_BASE_DEFAULT_ETH, \ + .driver = NULL, \ + .stack = ESP_NETIF_NETSTACK_DEFAULT_ETH, \ + } + +/** + * @brief Default configuration reference of WIFI AP + */ +#define ESP_NETIF_DEFAULT_WIFI_AP() \ + { \ + .base = ESP_NETIF_BASE_DEFAULT_WIFI_AP, \ + .driver = NULL, \ + .stack = ESP_NETIF_NETSTACK_DEFAULT_WIFI_AP, \ + } + +/** +* @brief Default configuration reference of WIFI STA +*/ +#define ESP_NETIF_DEFAULT_WIFI_STA() \ + { \ + .base = ESP_NETIF_BASE_DEFAULT_WIFI_STA, \ + .driver = NULL, \ + .stack = ESP_NETIF_NETSTACK_DEFAULT_WIFI_STA, \ + } + +/** +* @brief Default configuration reference of PPP client +*/ +#define ESP_NETIF_DEFAULT_PPP() \ + { \ + .base = ESP_NETIF_BASE_DEFAULT_PPP, \ + .driver = NULL, \ + .stack = ESP_NETIF_NETSTACK_DEFAULT_PPP, \ + } + +/** +* @brief Default configuration reference of SLIP client +*/ +#define ESP_NETIF_DEFAULT_SLIP() \ + { \ + .base = ESP_NETIF_BASE_DEFAULT_SLIP, \ + .driver = NULL, \ + .stack = ESP_NETIF_NETSTACK_DEFAULT_SLIP, \ + } + + +/** + * @brief Default base config (esp-netif inherent) of WIFI STA + */ +#define ESP_NETIF_BASE_DEFAULT_WIFI_STA &_g_esp_netif_inherent_sta_config + +/** + * @brief Default base config (esp-netif inherent) of WIFI AP + */ +#define ESP_NETIF_BASE_DEFAULT_WIFI_AP &_g_esp_netif_inherent_ap_config + +/** + * @brief Default base config (esp-netif inherent) of ethernet interface + */ +#define ESP_NETIF_BASE_DEFAULT_ETH &_g_esp_netif_inherent_eth_config + +/** + * @brief Default base config (esp-netif inherent) of ppp interface + */ +#define ESP_NETIF_BASE_DEFAULT_PPP &_g_esp_netif_inherent_ppp_config + +/** + * @brief Default base config (esp-netif inherent) of slip interface + */ +#define ESP_NETIF_BASE_DEFAULT_SLIP &_g_esp_netif_inherent_slip_config + + + +#define ESP_NETIF_NETSTACK_DEFAULT_ETH _g_esp_netif_netstack_default_eth +#define ESP_NETIF_NETSTACK_DEFAULT_WIFI_STA _g_esp_netif_netstack_default_wifi_sta +#define ESP_NETIF_NETSTACK_DEFAULT_WIFI_AP _g_esp_netif_netstack_default_wifi_ap +#define ESP_NETIF_NETSTACK_DEFAULT_PPP _g_esp_netif_netstack_default_ppp +#define ESP_NETIF_NETSTACK_DEFAULT_SLIP _g_esp_netif_netstack_default_slip + +// +// Include default network stacks configs +// - Network stack configurations are provided in a specific network stack +// implementation that is invisible to user API +// - Here referenced only as opaque pointers +// +extern const esp_netif_netstack_config_t *_g_esp_netif_netstack_default_eth; +extern const esp_netif_netstack_config_t *_g_esp_netif_netstack_default_wifi_sta; +extern const esp_netif_netstack_config_t *_g_esp_netif_netstack_default_wifi_ap; +extern const esp_netif_netstack_config_t *_g_esp_netif_netstack_default_ppp; +extern const esp_netif_netstack_config_t *_g_esp_netif_netstack_default_slip; + +// +// Include default common configs inherent to esp-netif +// - These inherent configs are defined in esp_netif_defaults.c and describe +// common behavioural patterns for common interfaces such as STA, AP, ETH, PPP +// +extern const esp_netif_inherent_config_t _g_esp_netif_inherent_sta_config; +extern const esp_netif_inherent_config_t _g_esp_netif_inherent_ap_config; +extern const esp_netif_inherent_config_t _g_esp_netif_inherent_eth_config; +extern const esp_netif_inherent_config_t _g_esp_netif_inherent_ppp_config; +extern const esp_netif_inherent_config_t _g_esp_netif_inherent_slip_config; + +extern const esp_netif_ip_info_t _g_esp_netif_soft_ap_ip; + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_NETIF_DEFAULTS_H diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ip_addr.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ip_addr.h new file mode 100644 index 00000000..809404c1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ip_addr.h @@ -0,0 +1,131 @@ +// Copyright 2015-2019 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. + +#ifndef _ESP_NETIF_IP_ADDR_H_ +#define _ESP_NETIF_IP_ADDR_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if BYTE_ORDER == BIG_ENDIAN +#define esp_netif_htonl(x) ((uint32_t)(x)) +#else +#define esp_netif_htonl(x) ((((x) & (uint32_t)0x000000ffUL) << 24) | \ + (((x) & (uint32_t)0x0000ff00UL) << 8) | \ + (((x) & (uint32_t)0x00ff0000UL) >> 8) | \ + (((x) & (uint32_t)0xff000000UL) >> 24)) +#endif + +#define esp_netif_ip4_makeu32(a,b,c,d) (((uint32_t)((a) & 0xff) << 24) | \ + ((uint32_t)((b) & 0xff) << 16) | \ + ((uint32_t)((c) & 0xff) << 8) | \ + (uint32_t)((d) & 0xff)) + +// Access address in 16-bit block +#define ESP_IP6_ADDR_BLOCK1(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[0]) >> 16) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK2(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[0])) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK3(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[1]) >> 16) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK4(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[1])) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK5(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[2]) >> 16) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK6(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[2])) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK7(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[3]) >> 16) & 0xffff)) +#define ESP_IP6_ADDR_BLOCK8(ip6addr) ((uint16_t)((esp_netif_htonl((ip6addr)->addr[3])) & 0xffff)) + +#define IPSTR "%d.%d.%d.%d" +#define esp_ip4_addr_get_byte(ipaddr, idx) (((const uint8_t*)(&(ipaddr)->addr))[idx]) +#define esp_ip4_addr1(ipaddr) esp_ip4_addr_get_byte(ipaddr, 0) +#define esp_ip4_addr2(ipaddr) esp_ip4_addr_get_byte(ipaddr, 1) +#define esp_ip4_addr3(ipaddr) esp_ip4_addr_get_byte(ipaddr, 2) +#define esp_ip4_addr4(ipaddr) esp_ip4_addr_get_byte(ipaddr, 3) + + +#define esp_ip4_addr1_16(ipaddr) ((uint16_t)esp_ip4_addr1(ipaddr)) +#define esp_ip4_addr2_16(ipaddr) ((uint16_t)esp_ip4_addr2(ipaddr)) +#define esp_ip4_addr3_16(ipaddr) ((uint16_t)esp_ip4_addr3(ipaddr)) +#define esp_ip4_addr4_16(ipaddr) ((uint16_t)esp_ip4_addr4(ipaddr)) + +#define IP2STR(ipaddr) esp_ip4_addr1_16(ipaddr), \ + esp_ip4_addr2_16(ipaddr), \ + esp_ip4_addr3_16(ipaddr), \ + esp_ip4_addr4_16(ipaddr) + +#define IPV6STR "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x" + +#define IPV62STR(ipaddr) ESP_IP6_ADDR_BLOCK1(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK2(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK3(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK4(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK5(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK6(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK7(&(ipaddr)), \ + ESP_IP6_ADDR_BLOCK8(&(ipaddr)) + +#define ESP_IPADDR_TYPE_V4 0U +#define ESP_IPADDR_TYPE_V6 6U +#define ESP_IPADDR_TYPE_ANY 46U + +#define ESP_IP4TOUINT32(a,b,c,d) (((uint32_t)((a) & 0xffU) << 24) | \ + ((uint32_t)((b) & 0xffU) << 16) | \ + ((uint32_t)((c) & 0xffU) << 8) | \ + (uint32_t)((d) & 0xffU)) + +#define ESP_IP4TOADDR(a,b,c,d) esp_netif_htonl(ESP_IP4TOUINT32(a, b, c, d)) + +struct esp_ip6_addr { + uint32_t addr[4]; + uint8_t zone; +}; + +struct esp_ip4_addr { + uint32_t addr; +}; + +typedef struct esp_ip4_addr esp_ip4_addr_t; + +typedef struct esp_ip6_addr esp_ip6_addr_t; + +typedef struct _ip_addr { + union { + esp_ip6_addr_t ip6; + esp_ip4_addr_t ip4; + } u_addr; + uint8_t type; +} esp_ip_addr_t; + +typedef enum { + ESP_IP6_ADDR_IS_UNKNOWN, + ESP_IP6_ADDR_IS_GLOBAL, + ESP_IP6_ADDR_IS_LINK_LOCAL, + ESP_IP6_ADDR_IS_SITE_LOCAL, + ESP_IP6_ADDR_IS_UNIQUE_LOCAL, + ESP_IP6_ADDR_IS_IPV4_MAPPED_IPV6 +} esp_ip6_addr_type_t; + +/** + * @brief Get the IPv6 address type + * + * @param[in] ip6_addr IPv6 type + * + * @return IPv6 type in form of enum esp_ip6_addr_type_t + */ +esp_ip6_addr_type_t esp_netif_ip6_get_addr_type(esp_ip6_addr_t* ip6_addr); + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_NETIF_IP_ADDR_H_ diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_net_stack.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_net_stack.h new file mode 100644 index 00000000..ab6d6a07 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_net_stack.h @@ -0,0 +1,106 @@ +// Copyright 2015-2019 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. + +#ifndef _ESP_NETIF_NET_STACK_H_ +#define _ESP_NETIF_NET_STACK_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// +// Network stack API: This ESP-NETIF API are supposed to be called only from internals of TCP/IP stack +// + +/** @addtogroup ESP_NETIF_CONVERT + * @{ + */ + +/** + * @brief Returns esp-netif handle + * + * @param[in] dev opaque ptr to network interface of specific TCP/IP stack + * + * @return handle to related esp-netif instance + */ +esp_netif_t* esp_netif_get_handle_from_netif_impl(void *dev); + +/** + * @brief Returns network stack specific implementation handle (if supported) + * + * Note that it is not supported to acquire PPP netif impl pointer and + * this function will return NULL for esp_netif instances configured to PPP mode + * + * @param[in] esp_netif Handle to esp-netif instance + * + * @return handle to related network stack netif handle + */ +void* esp_netif_get_netif_impl(esp_netif_t *esp_netif); + +/** + * @} + */ + +/** @addtogroup ESP_NETIF_DATA_IO_API + * @{ + */ + +/** + * @brief Outputs packets from the TCP/IP stack to the media to be transmitted + * + * This function gets called from network stack to output packets to IO driver. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] data Data to be transmitted + * @param[in] len Length of the data frame + * + * @return ESP_OK on success, an error passed from the I/O driver otherwise + */ +esp_err_t esp_netif_transmit(esp_netif_t *esp_netif, void* data, size_t len); + +/** + * @brief Outputs packets from the TCP/IP stack to the media to be transmitted + * + * This function gets called from network stack to output packets to IO driver. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] data Data to be transmitted + * @param[in] len Length of the data frame + * @param[in] netstack_buf net stack buffer + * + * @return ESP_OK on success, an error passed from the I/O driver otherwise + */ +esp_err_t esp_netif_transmit_wrap(esp_netif_t *esp_netif, void *data, size_t len, void *netstack_buf); + +/** + * @brief Free the rx buffer allocated by the media driver + * + * This function gets called from network stack when the rx buffer to be freed in IO driver context, + * i.e. to deallocate a buffer owned by io driver (when data packets were passed to higher levels + * to avoid copying) + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] buffer Rx buffer pointer + */ +void esp_netif_free_rx_buffer(void *esp_netif, void* buffer); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_NETIF_NET_STACK_H_ diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ppp.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ppp.h new file mode 100644 index 00000000..413910c4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_ppp.h @@ -0,0 +1,110 @@ +// Copyright 2019 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. +// + +#ifndef _ESP_NETIF_PPP_H_ +#define _ESP_NETIF_PPP_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief PPP event base */ +ESP_EVENT_DECLARE_BASE(NETIF_PPP_STATUS); + +/** @brief Configuration structure for PPP network interface + * + */ +typedef struct esp_netif_ppp_config { + bool ppp_phase_event_enabled; /**< Enables events coming from PPP PHASE change */ + bool ppp_error_event_enabled; /**< Enables events from main PPP state machine producing errors */ +} esp_netif_ppp_config_t; + +/** @brief event id offset for PHASE related events + * + * All PPP related events are produced from esp-netif under `NETIF_PPP_STATUS`, this offset defines + * helps distinguish between error and phase events + */ +#define NETIF_PP_PHASE_OFFSET (0x100) + +/** @brief event ids for different PPP related events + * + */ +typedef enum { + NETIF_PPP_ERRORNONE = 0, /* No error. */ + NETIF_PPP_ERRORPARAM = 1, /* Invalid parameter. */ + NETIF_PPP_ERROROPEN = 2, /* Unable to open PPP session. */ + NETIF_PPP_ERRORDEVICE = 3, /* Invalid I/O device for PPP. */ + NETIF_PPP_ERRORALLOC = 4, /* Unable to allocate resources. */ + NETIF_PPP_ERRORUSER = 5, /* User interrupt. */ + NETIF_PPP_ERRORCONNECT = 6, /* Connection lost. */ + NETIF_PPP_ERRORAUTHFAIL = 7, /* Failed authentication challenge. */ + NETIF_PPP_ERRORPROTOCOL = 8, /* Failed to meet protocol. */ + NETIF_PPP_ERRORPEERDEAD = 9, /* Connection timeout */ + NETIF_PPP_ERRORIDLETIMEOUT = 10, /* Idle Timeout */ + NETIF_PPP_ERRORCONNECTTIME = 11, /* Max connect time reached */ + NETIF_PPP_ERRORLOOPBACK = 12, /* Loopback detected */ + NETIF_PPP_PHASE_DEAD = NETIF_PP_PHASE_OFFSET + 0, + NETIF_PPP_PHASE_MASTER = NETIF_PP_PHASE_OFFSET + 1, + NETIF_PPP_PHASE_HOLDOFF = NETIF_PP_PHASE_OFFSET + 2, + NETIF_PPP_PHASE_INITIALIZE = NETIF_PP_PHASE_OFFSET + 3, + NETIF_PPP_PHASE_SERIALCONN = NETIF_PP_PHASE_OFFSET + 4, + NETIF_PPP_PHASE_DORMANT = NETIF_PP_PHASE_OFFSET + 5, + NETIF_PPP_PHASE_ESTABLISH = NETIF_PP_PHASE_OFFSET + 6, + NETIF_PPP_PHASE_AUTHENTICATE = NETIF_PP_PHASE_OFFSET + 7, + NETIF_PPP_PHASE_CALLBACK = NETIF_PP_PHASE_OFFSET + 8, + NETIF_PPP_PHASE_NETWORK = NETIF_PP_PHASE_OFFSET + 9, + NETIF_PPP_PHASE_RUNNING = NETIF_PP_PHASE_OFFSET + 10, + NETIF_PPP_PHASE_TERMINATE = NETIF_PP_PHASE_OFFSET + 11, + NETIF_PPP_PHASE_DISCONNECT = NETIF_PP_PHASE_OFFSET + 12, +} esp_netif_ppp_status_event_t; + +/** @brief definitions of different authorisation types + * + */ +typedef enum { + NETIF_PPP_AUTHTYPE_NONE = 0x00, + NETIF_PPP_AUTHTYPE_PAP = 0x01, + NETIF_PPP_AUTHTYPE_CHAP = 0x02, + NETIF_PPP_AUTHTYPE_MSCHAP = 0x04, + NETIF_PPP_AUTHTYPE_MSCHAP_V2 = 0x08, + NETIF_PPP_AUTHTYPE_EAP = 0x10, +} esp_netif_auth_type_t; + +/** @brief Sets the auth parameters for the supplied esp-netif. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] authtype Authorisation type + * @param[in] user User name + * @param[in] passwd Password + * + * @return ESP_OK on success, ESP_ERR_ESP_NETIF_INVALID_PARAMS if netif null or not PPP + */ +esp_err_t esp_netif_ppp_set_auth(esp_netif_t *netif, esp_netif_auth_type_t authtype, const char *user, const char *passwd); + +/** @brief Sets common parameters for the supplied esp-netif. + * + * @param[in] esp_netif Handle to esp-netif instance + * @param[in] config Pointer to PPP netif configuration structure + * + * @return ESP_OK on success, ESP_ERR_ESP_NETIF_INVALID_PARAMS if netif null or not PPP + */ +esp_err_t esp_netif_ppp_set_params(esp_netif_t *netif, const esp_netif_ppp_config_t *config); + + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_NETIF_PPP_H_ diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_slip.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_slip.h new file mode 100644 index 00000000..20cad4a8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_slip.h @@ -0,0 +1,79 @@ +// Copyright 2019 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. +// + +#ifndef _ESP_NETIF_SLIP_H_ +#define _ESP_NETIF_SLIP_H_ + +#include "esp_netif.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @brief Configuration structure for SLIP network interface + * + */ +typedef struct esp_netif_slip_config { + esp_ip6_addr_t ip6_addr; /* Local IP6 address */ + +} esp_netif_slip_config_t; + + +/** @brief Sets common parameters for the supplied esp-netif. + * + * @param[in] esp_netif handle to slip esp-netif instance + * @param[in] config Pointer to SLIP netif configuration structure + * + * @return ESP_OK on success, ESP_ERR_ESP_NETIF_INVALID_PARAMS if netif null or not SLIP + */ +esp_err_t esp_netif_slip_set_params(esp_netif_t *netif, const esp_netif_slip_config_t *config); + +#if CONFIG_LWIP_IPV6 +/** @brief Sets IPV6 address for the supplied esp-netif. + * + * @param[in] netif handle to slip esp-netif instance + * @param[in] ipv6 IPv6 address of the SLIP interface + * + * @return ESP_OK on success, ESP_ERR_ESP_NETIF_INVALID_PARAMS if netif null or not SLIP + */ +esp_err_t esp_netif_slip_set_ipv6(esp_netif_t *netif, const esp_ip6_addr_t *ipv6); +#endif + +/** + * @brief Data path API to write raw packet ous the SLIP interface + * + * This API is typically used when implementing user defined methods + * + * @param[in] esp_netif handle to slip esp-netif instance + * @param[in] buffer pointer to the outgoing data + * @param[in] len length of the data + * + * @return + * - ESP_OK on success + */ +void esp_netif_lwip_slip_raw_output(esp_netif_t *netif, void *buffer, size_t len); + +/** + * @brief Fetch IP6 address attached to the SLIP interface + * + * @param[in] esp_netif handle to slip esp-netif instance + * @param[in] address index (unused) + * + * @return + * - pointer to the internal ip6 address object + */ +const esp_ip6_addr_t *esp_slip_get_ip6(esp_netif_t *slip_netif); + +#endif diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_sta_list.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_sta_list.h new file mode 100644 index 00000000..d464132a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_sta_list.h @@ -0,0 +1,71 @@ +// Copyright 2019 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. + +#ifndef _ESP_NETIF_STA_LIST_H_ +#define _ESP_NETIF_STA_LIST_H_ + +#include "esp_netif_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief station list info element + */ +typedef struct { + uint8_t mac[6]; /**< Station MAC address */ + esp_ip4_addr_t ip; /**< Station assigned IP address */ +} esp_netif_sta_info_t; + +/** + * @brief station list structure + */ +typedef struct { + esp_netif_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]; /**< Connected stations */ + int num; /**< Number of connected stations */ +} esp_netif_sta_list_t; + +/** + * @defgroup ESP_NETIF_STA_LIST ESP-NETIF STA list api + * @brief List of stations for Wi-Fi AP interface + * + */ + +/** @addtogroup ESP_NETIF_STA_LIST + * @{ + */ + +/** + * @brief Get IP information for stations connected to the Wi-Fi AP interface + * + * @param[in] wifi_sta_list Wi-Fi station info list, returned from esp_wifi_ap_get_sta_list() + * @param[out] netif_sta_list IP layer station info list, corresponding to MAC addresses provided in wifi_sta_list + * + * @return + * - ESP_OK + * - ESP_ERR_ESP_NETIF_NO_MEM + * - ESP_ERR_ESP_NETIF_INVALID_PARAMS + */ +esp_err_t esp_netif_get_sta_list(const wifi_sta_list_t *wifi_sta_list, esp_netif_sta_list_t *netif_sta_list); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_NETIF_STA_LIST_H_ diff --git a/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_types.h b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_types.h new file mode 100644 index 00000000..044ca0d1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_netif/include/esp_netif_types.h @@ -0,0 +1,220 @@ +// Copyright 2015-2019 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. + +#ifndef _ESP_NETIF_TYPES_H_ +#define _ESP_NETIF_TYPES_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Definition of ESP-NETIF based errors + */ +#define ESP_ERR_ESP_NETIF_BASE 0x5000 +#define ESP_ERR_ESP_NETIF_INVALID_PARAMS ESP_ERR_ESP_NETIF_BASE + 0x01 +#define ESP_ERR_ESP_NETIF_IF_NOT_READY ESP_ERR_ESP_NETIF_BASE + 0x02 +#define ESP_ERR_ESP_NETIF_DHCPC_START_FAILED ESP_ERR_ESP_NETIF_BASE + 0x03 +#define ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED ESP_ERR_ESP_NETIF_BASE + 0x04 +#define ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED ESP_ERR_ESP_NETIF_BASE + 0x05 +#define ESP_ERR_ESP_NETIF_NO_MEM ESP_ERR_ESP_NETIF_BASE + 0x06 +#define ESP_ERR_ESP_NETIF_DHCP_NOT_STOPPED ESP_ERR_ESP_NETIF_BASE + 0x07 +#define ESP_ERR_ESP_NETIF_DRIVER_ATTACH_FAILED ESP_ERR_ESP_NETIF_BASE + 0x08 +#define ESP_ERR_ESP_NETIF_INIT_FAILED ESP_ERR_ESP_NETIF_BASE + 0x09 +#define ESP_ERR_ESP_NETIF_DNS_NOT_CONFIGURED ESP_ERR_ESP_NETIF_BASE + 0x0A + + +/** @brief Type of esp_netif_object server */ +struct esp_netif_obj; + +typedef struct esp_netif_obj esp_netif_t; + + +/** @brief Type of DNS server */ +typedef enum { + ESP_NETIF_DNS_MAIN= 0, /**< DNS main server address*/ + ESP_NETIF_DNS_BACKUP, /**< DNS backup server address (Wi-Fi STA and Ethernet only) */ + ESP_NETIF_DNS_FALLBACK, /**< DNS fallback server address (Wi-Fi STA and Ethernet only) */ + ESP_NETIF_DNS_MAX +} esp_netif_dns_type_t; + +/** @brief DNS server info */ +typedef struct { + esp_ip_addr_t ip; /**< IPV4 address of DNS server */ +} esp_netif_dns_info_t; + +/** @brief Status of DHCP client or DHCP server */ +typedef enum { + ESP_NETIF_DHCP_INIT = 0, /**< DHCP client/server is in initial state (not yet started) */ + ESP_NETIF_DHCP_STARTED, /**< DHCP client/server has been started */ + ESP_NETIF_DHCP_STOPPED, /**< DHCP client/server has been stopped */ + ESP_NETIF_DHCP_STATUS_MAX +} esp_netif_dhcp_status_t; + + +/** @brief Mode for DHCP client or DHCP server option functions */ +typedef enum{ + ESP_NETIF_OP_START = 0, + ESP_NETIF_OP_SET, /**< Set option */ + ESP_NETIF_OP_GET, /**< Get option */ + ESP_NETIF_OP_MAX +} esp_netif_dhcp_option_mode_t; + +/** @brief Supported options for DHCP client or DHCP server */ +typedef enum{ + ESP_NETIF_SUBNET_MASK = 1, /**< Network mask */ + ESP_NETIF_DOMAIN_NAME_SERVER = 6, /**< Domain name server */ + ESP_NETIF_ROUTER_SOLICITATION_ADDRESS = 32, /**< Solicitation router address */ + ESP_NETIF_REQUESTED_IP_ADDRESS = 50, /**< Request specific IP address */ + ESP_NETIF_IP_ADDRESS_LEASE_TIME = 51, /**< Request IP address lease time */ + ESP_NETIF_IP_REQUEST_RETRY_TIME = 52, /**< Request IP address retry counter */ +} esp_netif_dhcp_option_id_t; + +/** IP event declarations */ +typedef enum { + IP_EVENT_STA_GOT_IP, /*!< station got IP from connected AP */ + IP_EVENT_STA_LOST_IP, /*!< station lost IP and the IP is reset to 0 */ + IP_EVENT_AP_STAIPASSIGNED, /*!< soft-AP assign an IP to a connected station */ + IP_EVENT_GOT_IP6, /*!< station or ap or ethernet interface v6IP addr is preferred */ + IP_EVENT_ETH_GOT_IP, /*!< ethernet got IP from connected AP */ + IP_EVENT_PPP_GOT_IP, /*!< PPP interface got IP */ + IP_EVENT_PPP_LOST_IP, /*!< PPP interface lost IP */ +} ip_event_t; + +/** @brief IP event base declaration */ +ESP_EVENT_DECLARE_BASE(IP_EVENT); + +/** Event structure for IP_EVENT_STA_GOT_IP, IP_EVENT_ETH_GOT_IP events */ + +typedef struct { + esp_ip4_addr_t ip; /**< Interface IPV4 address */ + esp_ip4_addr_t netmask; /**< Interface IPV4 netmask */ + esp_ip4_addr_t gw; /**< Interface IPV4 gateway address */ +} esp_netif_ip_info_t; + +/** @brief IPV6 IP address information + */ +typedef struct { + esp_ip6_addr_t ip; /**< Interface IPV6 address */ +} esp_netif_ip6_info_t; + +typedef struct { + int if_index; /*!< Interface index for which the event is received (left for legacy compilation) */ + esp_netif_t *esp_netif; /*!< Pointer to corresponding esp-netif object */ + esp_netif_ip_info_t ip_info; /*!< IP address, netmask, gatway IP address */ + bool ip_changed; /*!< Whether the assigned IP has changed or not */ +} ip_event_got_ip_t; + +/** Event structure for IP_EVENT_GOT_IP6 event */ +typedef struct { + int if_index; /*!< Interface index for which the event is received (left for legacy compilation) */ + esp_netif_t *esp_netif; /*!< Pointer to corresponding esp-netif object */ + esp_netif_ip6_info_t ip6_info; /*!< IPv6 address of the interface */ + int ip_index; /*!< IPv6 address index */ +} ip_event_got_ip6_t; + +/** Event structure for IP_EVENT_AP_STAIPASSIGNED event */ +typedef struct { + esp_ip4_addr_t ip; /*!< IP address which was assigned to the station */ +} ip_event_ap_staipassigned_t; + + + + +typedef enum esp_netif_flags { + ESP_NETIF_DHCP_CLIENT = 1 << 0, + ESP_NETIF_DHCP_SERVER = 1 << 1, + ESP_NETIF_FLAG_AUTOUP = 1 << 2, + ESP_NETIF_FLAG_GARP = 1 << 3, + ESP_NETIF_FLAG_EVENT_IP_MODIFIED = 1 << 4, + ESP_NETIF_FLAG_IS_PPP = 1 << 5, + ESP_NETIF_FLAG_IS_SLIP = 1 << 6, +} esp_netif_flags_t; + +typedef enum esp_netif_ip_event_type { + ESP_NETIF_IP_EVENT_GOT_IP = 1, + ESP_NETIF_IP_EVENT_LOST_IP = 2, +} esp_netif_ip_event_type_t; + + +// +// ESP-NETIF interface configuration: +// 1) general (behavioral) config (esp_netif_config_t) +// 2) (peripheral) driver specific config (esp_netif_driver_ifconfig_t) +// 3) network stack specific config (esp_netif_net_stack_ifconfig_t) -- no publicly available +// + +typedef struct esp_netif_inherent_config { + esp_netif_flags_t flags; /*!< flags that define esp-netif behavior */ + uint8_t mac[6]; /*!< initial mac address for this interface */ + const esp_netif_ip_info_t* ip_info; /*!< initial ip address for this interface */ + uint32_t get_ip_event; /*!< event id to be raised when interface gets an IP */ + uint32_t lost_ip_event; /*!< event id to be raised when interface losts its IP */ + const char * if_key; /*!< string identifier of the interface */ + const char * if_desc; /*!< textual description of the interface */ + int route_prio; /*!< numeric priority of this interface to become a default + routing if (if other netifs are up). + A higher value of route_prio indicates + a higher priority */ +} esp_netif_inherent_config_t; + +typedef struct esp_netif_config esp_netif_config_t; + +/** + * @brief IO driver handle type + */ +typedef void * esp_netif_iodriver_handle; + +typedef struct esp_netif_driver_base_s { + esp_err_t (*post_attach)(esp_netif_t *netif, esp_netif_iodriver_handle h); + esp_netif_t *netif; +} esp_netif_driver_base_t; + +/** + * @brief Specific IO driver configuration + */ +struct esp_netif_driver_ifconfig { + esp_netif_iodriver_handle handle; + esp_err_t (*transmit)(void *h, void *buffer, size_t len); + esp_err_t (*transmit_wrap)(void *h, void *buffer, size_t len, void *netstack_buffer); + void (*driver_free_rx_buffer)(void *h, void* buffer); +}; + +typedef struct esp_netif_driver_ifconfig esp_netif_driver_ifconfig_t; + +/** + * @brief Specific L3 network stack configuration + */ + +typedef struct esp_netif_netstack_config esp_netif_netstack_config_t; + +/** + * @brief Generic esp_netif configuration + */ +struct esp_netif_config { + const esp_netif_inherent_config_t *base; + const esp_netif_driver_ifconfig_t *driver; + const esp_netif_netstack_config_t *stack; +}; + +/** + * @brief ESP-NETIF Receive function type + */ +typedef esp_err_t (*esp_netif_receive_t)(esp_netif_t *esp_netif, void *buffer, size_t len, void *eb); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_NETIF_TYPES_H_ diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp32/pm.h b/tools/sdk/esp32c3/include/esp_pm/include/esp32/pm.h new file mode 100644 index 00000000..8c3682cc --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp32/pm.h @@ -0,0 +1,42 @@ +// Copyright 2016-2017 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. + + +#pragma once +#include +#include +#include "esp_err.h" + +#include "soc/rtc.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Power management config for ESP32 + * + * Pass a pointer to this structure as an argument to esp_pm_configure function. + */ +typedef struct { + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + int min_freq_mhz; /*!< Minimum CPU frequency to use when no locks are taken, in MHz */ + bool light_sleep_enable; /*!< Enter light sleep when no locks are taken */ +} esp_pm_config_esp32_t; + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp32c3/pm.h b/tools/sdk/esp32c3/include/esp_pm/include/esp32c3/pm.h new file mode 100644 index 00000000..7ceecd12 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp32c3/pm.h @@ -0,0 +1,42 @@ +// Copyright 2020 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. + + +#pragma once +#include +#include +#include "esp_err.h" + +#include "soc/rtc.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Power management config for ESP32C3 + * + * Pass a pointer to this structure as an argument to esp_pm_configure function. + */ +typedef struct { + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + int min_freq_mhz; /*!< Minimum CPU frequency to use when no locks are taken, in MHz */ + bool light_sleep_enable; /*!< Enter light sleep when no locks are taken */ +} esp_pm_config_esp32c3_t; + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp32s2/pm.h b/tools/sdk/esp32c3/include/esp_pm/include/esp32s2/pm.h new file mode 100644 index 00000000..dac31e0c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp32s2/pm.h @@ -0,0 +1,42 @@ +// Copyright 2016-2017 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. + + +#pragma once +#include +#include +#include "esp_err.h" + +#include "soc/rtc.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Power management config for ESP32 + * + * Pass a pointer to this structure as an argument to esp_pm_configure function. + */ +typedef struct { + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + int min_freq_mhz; /*!< Minimum CPU frequency to use when no locks are taken, in MHz */ + bool light_sleep_enable; /*!< Enter light sleep when no locks are taken */ +} esp_pm_config_esp32s2_t; + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp32s3/pm.h b/tools/sdk/esp32c3/include/esp_pm/include/esp32s3/pm.h new file mode 100644 index 00000000..0b29c66a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp32s3/pm.h @@ -0,0 +1,42 @@ +// Copyright 2016-2017 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. + + +#pragma once +#include +#include +#include "esp_err.h" + +#include "soc/rtc.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Power management config for ESP32 + * + * Pass a pointer to this structure as an argument to esp_pm_configure function. + */ +typedef struct { + int max_freq_mhz; /*!< Maximum CPU frequency, in MHz */ + int min_freq_mhz; /*!< Minimum CPU frequency to use when no locks are taken, in MHz */ + bool light_sleep_enable; /*!< Enter light sleep when no locks are taken */ +} esp_pm_config_esp32s3_t; + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp_pm.h b/tools/sdk/esp32c3/include/esp_pm/include/esp_pm.h new file mode 100644 index 00000000..4d514631 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp_pm.h @@ -0,0 +1,184 @@ +// Copyright 2016-2017 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. + +#pragma once +#include +#include +#include "esp_err.h" +#include "sdkconfig.h" +#if CONFIG_IDF_TARGET_ESP32 +#include "esp32/pm.h" +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/pm.h" +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/pm.h" +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/pm.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Power management constraints + */ +typedef enum { + /** + * Require CPU frequency to be at the maximum value set via esp_pm_configure. + * Argument is unused and should be set to 0. + */ + ESP_PM_CPU_FREQ_MAX, + /** + * Require APB frequency to be at the maximum value supported by the chip. + * Argument is unused and should be set to 0. + */ + ESP_PM_APB_FREQ_MAX, + /** + * Prevent the system from going into light sleep. + * Argument is unused and should be set to 0. + */ + ESP_PM_NO_LIGHT_SLEEP, +} esp_pm_lock_type_t; + +/** + * @brief Set implementation-specific power management configuration + * @param config pointer to implementation-specific configuration structure (e.g. esp_pm_config_esp32) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the configuration values are not correct + * - ESP_ERR_NOT_SUPPORTED if certain combination of values is not supported, + * or if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_configure(const void* config); + + +/** + * @brief Opaque handle to the power management lock + */ +typedef struct esp_pm_lock* esp_pm_lock_handle_t; + + +/** + * @brief Initialize a lock handle for certain power management parameter + * + * When lock is created, initially it is not taken. + * Call esp_pm_lock_acquire to take the lock. + * + * This function must not be called from an ISR. + * + * @param lock_type Power management constraint which the lock should control + * @param arg argument, value depends on lock_type, see esp_pm_lock_type_t + * @param name arbitrary string identifying the lock (e.g. "wifi" or "spi"). + * Used by the esp_pm_dump_locks function to list existing locks. + * May be set to NULL. If not set to NULL, must point to a string which is valid + * for the lifetime of the lock. + * @param[out] out_handle handle returned from this function. Use this handle when calling + * esp_pm_lock_delete, esp_pm_lock_acquire, esp_pm_lock_release. + * Must not be NULL. + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if the lock structure can not be allocated + * - ESP_ERR_INVALID_ARG if out_handle is NULL or type argument is not valid + * - ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_lock_create(esp_pm_lock_type_t lock_type, int arg, + const char* name, esp_pm_lock_handle_t* out_handle); + +/** + * @brief Take a power management lock + * + * Once the lock is taken, power management algorithm will not switch to the + * mode specified in a call to esp_pm_lock_create, or any of the lower power + * modes (higher numeric values of 'mode'). + * + * The lock is recursive, in the sense that if esp_pm_lock_acquire is called + * a number of times, esp_pm_lock_release has to be called the same number of + * times in order to release the lock. + * + * This function may be called from an ISR. + * + * This function is not thread-safe w.r.t. calls to other esp_pm_lock_* + * functions for the same handle. + * + * @param handle handle obtained from esp_pm_lock_create function + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the handle is invalid + * - ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_lock_acquire(esp_pm_lock_handle_t handle); + +/** + * @brief Release the lock taken using esp_pm_lock_acquire. + * + * Call to this functions removes power management restrictions placed when + * taking the lock. + * + * Locks are recursive, so if esp_pm_lock_acquire is called a number of times, + * esp_pm_lock_release has to be called the same number of times in order to + * actually release the lock. + * + * This function may be called from an ISR. + * + * This function is not thread-safe w.r.t. calls to other esp_pm_lock_* + * functions for the same handle. + * + * @param handle handle obtained from esp_pm_lock_create function + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the handle is invalid + * - ESP_ERR_INVALID_STATE if lock is not acquired + * - ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_lock_release(esp_pm_lock_handle_t handle); + +/** + * @brief Delete a lock created using esp_pm_lock + * + * The lock must be released before calling this function. + * + * This function must not be called from an ISR. + * + * @param handle handle obtained from esp_pm_lock_create function + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the handle argument is NULL + * - ESP_ERR_INVALID_STATE if the lock is still acquired + * - ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_lock_delete(esp_pm_lock_handle_t handle); + +/** + * Dump the list of all locks to stderr + * + * This function dumps debugging information about locks created using + * esp_pm_lock_create to an output stream. + * + * This function must not be called from an ISR. If esp_pm_lock_acquire/release + * are called while this function is running, inconsistent results may be + * reported. + * + * @param stream stream to print information to; use stdout or stderr to print + * to the console; use fmemopen/open_memstream to print to a + * string buffer. + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_SUPPORTED if CONFIG_PM_ENABLE is not enabled in sdkconfig + */ +esp_err_t esp_pm_dump_locks(FILE* stream); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_impl.h b/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_impl.h new file mode 100644 index 00000000..e208d2bc --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_impl.h @@ -0,0 +1,217 @@ +// Copyright 2016-2017 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. + +#pragma once + +/** + * @file esp_private/pm_impl.h + * + * This header file defines interface between PM lock functions (pm_locks.c) + * and the chip-specific power management (DFS/light sleep) implementation. + */ + +#include "soc/rtc.h" +#include "esp_pm.h" +#include "esp_timer.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * This is an enum of possible power modes supported by the implementation + */ +typedef enum { + PM_MODE_LIGHT_SLEEP,//!< Light sleep + PM_MODE_APB_MIN, //!< Idle (no CPU frequency or APB frequency locks) + PM_MODE_APB_MAX, //!< Maximum APB frequency mode + PM_MODE_CPU_MAX, //!< Maximum CPU frequency mode + PM_MODE_COUNT //!< Number of items +} pm_mode_t; + +/** + * @brief Get the mode corresponding to a certain lock + * @param type lock type + * @param arg argument value for this lock (passed to esp_pm_lock_create) + * @return lowest power consumption mode which meets the constraints of the lock + */ +pm_mode_t esp_pm_impl_get_mode(esp_pm_lock_type_t type, int arg); + +/** + * @brief Get CPU clock frequency by power mode + * @param mode power mode + * @return CPU clock frequency + */ +int esp_pm_impl_get_cpu_freq(pm_mode_t mode); + +/** + * If profiling is enabled, this data type will be used to store microsecond + * timestamps. + */ +typedef int64_t pm_time_t; + +/** + * See \ref esp_pm_impl_switch_mode + */ +typedef enum { + MODE_LOCK, + MODE_UNLOCK +} pm_mode_switch_t; + +/** + * @brief Switch between power modes when lock is taken or released + * @param mode pm_mode_t corresponding to the lock being taken or released, + * as returned by \ref esp_pm_impl_get_mode + * @param lock_or_unlock + * - MODE_LOCK: lock was taken. Implementation needs to make sure + * that the constraints of the lock are met by switching to the + * given 'mode' or any of the higher power ones. + * - MODE_UNLOCK: lock was released. If all the locks for given + * mode are released, and no locks for higher power modes are + * taken, implementation can switch to one of lower power modes. + * @param now timestamp when the lock was taken or released. Passed as + * a minor optimization, so that the implementation does not need to + * call pm_get_time again. + */ +void esp_pm_impl_switch_mode(pm_mode_t mode, pm_mode_switch_t lock_or_unlock, pm_time_t now); + +/** + * @brief Call once at startup to initialize pm implementation + */ +void esp_pm_impl_init(void); + +/** + * @brief Hook function for the idle task + * Must be called from the IDLE task on each CPU before entering waiti state. + */ +void esp_pm_impl_idle_hook(void); + +/** + * @brief Hook function for the interrupt dispatcher + * Must be called soon after entering the ISR + */ +void esp_pm_impl_isr_hook(void); + +/** + * @brief Dump the information about time spent in each of the pm modes. + * + * Prints three columns: + * mode name, total time in mode (in microseconds), percentage of time in mode + * + * @param out stream to dump the information to + */ +void esp_pm_impl_dump_stats(FILE* out); + +/** + * @brief Hook function implementing `waiti` instruction, should be invoked from idle task context + */ +void esp_pm_impl_waiti(void); + +/** + * @brief Callback function type for peripherals to skip light sleep. + * + */ +typedef bool (* skip_light_sleep_cb_t)(void); + +/** + * @brief Register peripherals skip light sleep callback + * + * This function allows you to register a callback that gets the result + * that if light sleep should be skipped by peripherals. + * @param cb function to get the result + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if no more callback slots are available + */ +esp_err_t esp_pm_register_skip_light_sleep_callback(skip_light_sleep_cb_t cb); + +/** + * @brief Unregisterperipherals skip light sleep callback + * + * This function allows you to unregister a callback which was previously + * registered using esp_register_skip_light_sleep_callback. + * @param cb function to get the result + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the given callback hasn't been registered before + */ +esp_err_t esp_pm_unregister_skip_light_sleep_callback(skip_light_sleep_cb_t cb); + +/** + * @brief Callback function type for peripherals to know light sleep wakeup overhead. + * + */ +typedef void (* inform_out_light_sleep_overhead_cb_t)(uint32_t); + +/** + * @brief Register informing peripherals light sleep wakeup overhead time callback + * + * This function allows you to register a callback that informs the peripherals of + * the wakeup overhead time of light sleep. + * @param cb function to inform time + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if no more callback slots are available + */ +esp_err_t esp_pm_register_inform_out_light_sleep_overhead_callback(inform_out_light_sleep_overhead_cb_t cb); + +/** + * @brief Unregister informing peripherals light sleep wakeup overhead time callback + * + * This function allows you to unregister a callback that informs the peripherals of + * the wakeup overhead time of light sleep. + * @param cb function to inform time + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the given callback hasn't been registered before + */ +esp_err_t esp_pm_unregister_inform_out_light_sleep_overhead_callback(inform_out_light_sleep_overhead_cb_t cb); + +/** + * @brief Callback function type for peripherals to know light sleep default parameters + */ +typedef void (* update_light_sleep_default_params_config_cb_t)(int, int); + +/** + * @brief Register peripherals light sleep default parameters configure callback + * + * This function allows you to register a callback that configure the peripherals + * of default parameters of light sleep + * @param cb function to update default parameters + */ +void esp_pm_register_light_sleep_default_params_config_callback(update_light_sleep_default_params_config_cb_t cb); + +/** + * @brief Unregister peripherals light sleep default parameters configure Callback + * + * This function allows you to unregister a callback that configure the peripherals + * of default parameters of light sleep + */ +void esp_pm_unregister_light_sleep_default_params_config_callback(void); + +#ifdef CONFIG_PM_PROFILING +#define WITH_PROFILING +#endif + +#ifdef WITH_PROFILING +static inline pm_time_t IRAM_ATTR pm_get_time(void) +{ + return esp_timer_get_time(); +} +#endif // WITH_PROFILING + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_trace.h b/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_trace.h new file mode 100644 index 00000000..e6cb7b92 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_pm/include/esp_private/pm_trace.h @@ -0,0 +1,53 @@ +// Copyright 2016-2017 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. + +#pragma once + +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ESP_PM_TRACE_IDLE, + ESP_PM_TRACE_TICK, + ESP_PM_TRACE_FREQ_SWITCH, + ESP_PM_TRACE_CCOMPARE_UPDATE, + ESP_PM_TRACE_ISR_HOOK, + ESP_PM_TRACE_SLEEP, + ESP_PM_TRACE_TYPE_MAX +} esp_pm_trace_event_t; + +void esp_pm_trace_init(void); +void esp_pm_trace_enter(esp_pm_trace_event_t event, int core_id); +void esp_pm_trace_exit(esp_pm_trace_event_t event, int core_id); + +#ifdef CONFIG_PM_TRACE + +#define ESP_PM_TRACE_ENTER(event, core_id) \ + esp_pm_trace_enter(ESP_PM_TRACE_ ## event, core_id) +#define ESP_PM_TRACE_EXIT(event, core_id) \ + esp_pm_trace_exit(ESP_PM_TRACE_ ## event, core_id) + +#else // CONFIG_PM_TRACE + +#define ESP_PM_TRACE_ENTER(type, core_id) do { (void) core_id; } while(0) +#define ESP_PM_TRACE_EXIT(type, core_id) do { (void) core_id; } while(0) + +#endif // CONFIG_PM_TRACE + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_ringbuf/include/freertos/ringbuf.h b/tools/sdk/esp32c3/include/esp_ringbuf/include/freertos/ringbuf.h new file mode 100644 index 00000000..df6cc7a6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_ringbuf/include/freertos/ringbuf.h @@ -0,0 +1,518 @@ +// Copyright 2015-2019 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. + +#ifndef FREERTOS_RINGBUF_H +#define FREERTOS_RINGBUF_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include ringbuf.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * Type by which ring buffers are referenced. For example, a call to xRingbufferCreate() + * returns a RingbufHandle_t variable that can then be used as a parameter to + * xRingbufferSend(), xRingbufferReceive(), etc. + */ +typedef void * RingbufHandle_t; + +typedef enum { + /** + * No-split buffers will only store an item in contiguous memory and will + * never split an item. Each item requires an 8 byte overhead for a header + * and will always internally occupy a 32-bit aligned size of space. + */ + RINGBUF_TYPE_NOSPLIT = 0, + /** + * Allow-split buffers will split an item into two parts if necessary in + * order to store it. Each item requires an 8 byte overhead for a header, + * splitting incurs an extra header. Each item will always internally occupy + * a 32-bit aligned size of space. + */ + RINGBUF_TYPE_ALLOWSPLIT, + /** + * Byte buffers store data as a sequence of bytes and do not maintain separate + * items, therefore byte buffers have no overhead. All data is stored as a + * sequence of byte and any number of bytes can be sent or retrieved each + * time. + */ + RINGBUF_TYPE_BYTEBUF, + RINGBUF_TYPE_MAX, +} RingbufferType_t; + +/** + * @brief Struct that is equivalent in size to the ring buffer's data structure + * + * The contents of this struct are not meant to be used directly. This + * structure is meant to be used when creating a statically allocated ring + * buffer where this struct is of the exact size required to store a ring + * buffer's control data structure. + * + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1) +typedef struct xSTATIC_RINGBUFFER { + /** @cond */ //Doxygen command to hide this structure from API Reference + size_t xDummy1[2]; + UBaseType_t uxDummy2; + BaseType_t xDummy3; + void *pvDummy4[11]; + StaticSemaphore_t xDummy5[2]; + portMUX_TYPE muxDummy; + /** @endcond */ +} StaticRingbuffer_t; +#endif + +/** + * @brief Create a ring buffer + * + * @param[in] xBufferSize Size of the buffer in bytes. Note that items require + * space for overhead in no-split/allow-split buffers + * @param[in] xBufferType Type of ring buffer, see documentation. + * + * @note xBufferSize of no-split/allow-split buffers will be rounded up to the nearest 32-bit aligned size. + * + * @return A handle to the created ring buffer, or NULL in case of error. + */ +RingbufHandle_t xRingbufferCreate(size_t xBufferSize, RingbufferType_t xBufferType); + +/** + * @brief Create a ring buffer of type RINGBUF_TYPE_NOSPLIT for a fixed item_size + * + * This API is similar to xRingbufferCreate(), but it will internally allocate + * additional space for the headers. + * + * @param[in] xItemSize Size of each item to be put into the ring buffer + * @param[in] xItemNum Maximum number of items the buffer needs to hold simultaneously + * + * @return A RingbufHandle_t handle to the created ring buffer, or NULL in case of error. + */ +RingbufHandle_t xRingbufferCreateNoSplit(size_t xItemSize, size_t xItemNum); + + +/** + * @brief Create a ring buffer but manually provide the required memory + * + * @param[in] xBufferSize Size of the buffer in bytes. + * @param[in] xBufferType Type of ring buffer, see documentation + * @param[in] pucRingbufferStorage Pointer to the ring buffer's storage area. + * Storage area must of the same size as specified by xBufferSize + * @param[in] pxStaticRingbuffer Pointed to a struct of type StaticRingbuffer_t + * which will be used to hold the ring buffer's data structure + * + * @note xBufferSize of no-split/allow-split buffers MUST be 32-bit aligned. + * + * @return A handle to the created ring buffer + */ +#if ( configSUPPORT_STATIC_ALLOCATION == 1) +RingbufHandle_t xRingbufferCreateStatic(size_t xBufferSize, + RingbufferType_t xBufferType, + uint8_t *pucRingbufferStorage, + StaticRingbuffer_t *pxStaticRingbuffer); +#endif + +/** + * @brief Insert an item into the ring buffer + * + * Attempt to insert an item into the ring buffer. This function will block until + * enough free space is available or until it times out. + * + * @param[in] xRingbuffer Ring buffer to insert the item into + * @param[in] pvItem Pointer to data to insert. NULL is allowed if xItemSize is 0. + * @param[in] xItemSize Size of data to insert. + * @param[in] xTicksToWait Ticks to wait for room in the ring buffer. + * + * @note For no-split/allow-split ring buffers, the actual size of memory that + * the item will occupy will be rounded up to the nearest 32-bit aligned + * size. This is done to ensure all items are always stored in 32-bit + * aligned fashion. + * + * @return + * - pdTRUE if succeeded + * - pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer + */ +BaseType_t xRingbufferSend(RingbufHandle_t xRingbuffer, + const void *pvItem, + size_t xItemSize, + TickType_t xTicksToWait); + +/** + * @brief Insert an item into the ring buffer in an ISR + * + * Attempt to insert an item into the ring buffer from an ISR. This function + * will return immediately if there is insufficient free space in the buffer. + * + * @param[in] xRingbuffer Ring buffer to insert the item into + * @param[in] pvItem Pointer to data to insert. NULL is allowed if xItemSize is 0. + * @param[in] xItemSize Size of data to insert. + * @param[out] pxHigherPriorityTaskWoken Value pointed to will be set to pdTRUE if the function woke up a higher priority task. + * + * @note For no-split/allow-split ring buffers, the actual size of memory that + * the item will occupy will be rounded up to the nearest 32-bit aligned + * size. This is done to ensure all items are always stored in 32-bit + * aligned fashion. + * + * @return + * - pdTRUE if succeeded + * - pdFALSE when the ring buffer does not have space. + */ +BaseType_t xRingbufferSendFromISR(RingbufHandle_t xRingbuffer, + const void *pvItem, + size_t xItemSize, + BaseType_t *pxHigherPriorityTaskWoken); + +/** + * @brief Acquire memory from the ring buffer to be written to by an external + * source and to be sent later. + * + * Attempt to allocate buffer for an item to be sent into the ring buffer. This + * function will block until enough free space is available or until it + * timesout. + * + * The item, as well as the following items ``SendAcquire`` or ``Send`` after it, + * will not be able to be read from the ring buffer until this item is actually + * sent into the ring buffer. + * + * @param[in] xRingbuffer Ring buffer to allocate the memory + * @param[out] ppvItem Double pointer to memory acquired (set to NULL if no memory were retrieved) + * @param[in] xItemSize Size of item to acquire. + * @param[in] xTicksToWait Ticks to wait for room in the ring buffer. + * + * @note Only applicable for no-split ring buffers now, the actual size of + * memory that the item will occupy will be rounded up to the nearest 32-bit + * aligned size. This is done to ensure all items are always stored in 32-bit + * aligned fashion. + * + * @return + * - pdTRUE if succeeded + * - pdFALSE on time-out or when the data is larger than the maximum permissible size of the buffer + */ +BaseType_t xRingbufferSendAcquire(RingbufHandle_t xRingbuffer, void **ppvItem, size_t xItemSize, TickType_t xTicksToWait); + +/** + * @brief Actually send an item into the ring buffer allocated before by + * ``xRingbufferSendAcquire``. + * + * @param[in] xRingbuffer Ring buffer to insert the item into + * @param[in] pvItem Pointer to item in allocated memory to insert. + * + * @note Only applicable for no-split ring buffers. Only call for items + * allocated by ``xRingbufferSendAcquire``. + * + * @return + * - pdTRUE if succeeded + * - pdFALSE if fail for some reason. + */ +BaseType_t xRingbufferSendComplete(RingbufHandle_t xRingbuffer, void *pvItem); + +/** + * @brief Retrieve an item from the ring buffer + * + * Attempt to retrieve an item from the ring buffer. This function will block + * until an item is available or until it times out. + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] pxItemSize Pointer to a variable to which the size of the retrieved item will be written. + * @param[in] xTicksToWait Ticks to wait for items in the ring buffer. + * + * @note A call to vRingbufferReturnItem() is required after this to free the item retrieved. + * + * @return + * - Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. + * - NULL on timeout, *pxItemSize is untouched in that case. + */ +void *xRingbufferReceive(RingbufHandle_t xRingbuffer, size_t *pxItemSize, TickType_t xTicksToWait); + +/** + * @brief Retrieve an item from the ring buffer in an ISR + * + * Attempt to retrieve an item from the ring buffer. This function returns immediately + * if there are no items available for retrieval + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] pxItemSize Pointer to a variable to which the size of the + * retrieved item will be written. + * + * @note A call to vRingbufferReturnItemFromISR() is required after this to free the item retrieved. + * @note Byte buffers do not allow multiple retrievals before returning an item + * @note Two calls to RingbufferReceiveFromISR() are required if the bytes wrap around the end of the ring buffer. + * + * @return + * - Pointer to the retrieved item on success; *pxItemSize filled with the length of the item. + * - NULL when the ring buffer is empty, *pxItemSize is untouched in that case. + */ +void *xRingbufferReceiveFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize); + +/** + * @brief Retrieve a split item from an allow-split ring buffer + * + * Attempt to retrieve a split item from an allow-split ring buffer. If the item + * is not split, only a single item is retried. If the item is split, both parts + * will be retrieved. This function will block until an item is available or + * until it times out. + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] ppvHeadItem Double pointer to first part (set to NULL if no items were retrieved) + * @param[out] ppvTailItem Double pointer to second part (set to NULL if item is not split) + * @param[out] pxHeadItemSize Pointer to size of first part (unmodified if no items were retrieved) + * @param[out] pxTailItemSize Pointer to size of second part (unmodified if item is not split) + * @param[in] xTicksToWait Ticks to wait for items in the ring buffer. + * + * @note Call(s) to vRingbufferReturnItem() is required after this to free up the item(s) retrieved. + * @note This function should only be called on allow-split buffers + * + * @return + * - pdTRUE if an item (split or unsplit) was retrieved + * - pdFALSE when no item was retrieved + */ +BaseType_t xRingbufferReceiveSplit(RingbufHandle_t xRingbuffer, + void **ppvHeadItem, + void **ppvTailItem, + size_t *pxHeadItemSize, + size_t *pxTailItemSize, + TickType_t xTicksToWait); + +/** + * @brief Retrieve a split item from an allow-split ring buffer in an ISR + * + * Attempt to retrieve a split item from an allow-split ring buffer. If the item + * is not split, only a single item is retried. If the item is split, both parts + * will be retrieved. This function returns immediately if there are no items + * available for retrieval + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] ppvHeadItem Double pointer to first part (set to NULL if no items were retrieved) + * @param[out] ppvTailItem Double pointer to second part (set to NULL if item is not split) + * @param[out] pxHeadItemSize Pointer to size of first part (unmodified if no items were retrieved) + * @param[out] pxTailItemSize Pointer to size of second part (unmodified if item is not split) + * + * @note Calls to vRingbufferReturnItemFromISR() is required after this to free up the item(s) retrieved. + * @note This function should only be called on allow-split buffers + * + * @return + * - pdTRUE if an item (split or unsplit) was retrieved + * - pdFALSE when no item was retrieved + */ +BaseType_t xRingbufferReceiveSplitFromISR(RingbufHandle_t xRingbuffer, + void **ppvHeadItem, + void **ppvTailItem, + size_t *pxHeadItemSize, + size_t *pxTailItemSize); + +/** + * @brief Retrieve bytes from a byte buffer, specifying the maximum amount of bytes to retrieve + * + * Attempt to retrieve data from a byte buffer whilst specifying a maximum number + * of bytes to retrieve. This function will block until there is data available + * for retrieval or until it times out. + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] pxItemSize Pointer to a variable to which the size of the retrieved item will be written. + * @param[in] xTicksToWait Ticks to wait for items in the ring buffer. + * @param[in] xMaxSize Maximum number of bytes to return. + * + * @note A call to vRingbufferReturnItem() is required after this to free up the data retrieved. + * @note This function should only be called on byte buffers + * @note Byte buffers do not allow multiple retrievals before returning an item + * @note Two calls to RingbufferReceiveUpTo() are required if the bytes wrap around the end of the ring buffer. + * + * @return + * - Pointer to the retrieved item on success; *pxItemSize filled with + * the length of the item. + * - NULL on timeout, *pxItemSize is untouched in that case. + */ +void *xRingbufferReceiveUpTo(RingbufHandle_t xRingbuffer, + size_t *pxItemSize, + TickType_t xTicksToWait, + size_t xMaxSize); + +/** + * @brief Retrieve bytes from a byte buffer, specifying the maximum amount of + * bytes to retrieve. Call this from an ISR. + * + * Attempt to retrieve bytes from a byte buffer whilst specifying a maximum number + * of bytes to retrieve. This function will return immediately if there is no data + * available for retrieval. + * + * @param[in] xRingbuffer Ring buffer to retrieve the item from + * @param[out] pxItemSize Pointer to a variable to which the size of the retrieved item will be written. + * @param[in] xMaxSize Maximum number of bytes to return. + * + * @note A call to vRingbufferReturnItemFromISR() is required after this to free up the data received. + * @note This function should only be called on byte buffers + * @note Byte buffers do not allow multiple retrievals before returning an item + * + * @return + * - Pointer to the retrieved item on success; *pxItemSize filled with + * the length of the item. + * - NULL when the ring buffer is empty, *pxItemSize is untouched in that case. + */ +void *xRingbufferReceiveUpToFromISR(RingbufHandle_t xRingbuffer, size_t *pxItemSize, size_t xMaxSize); + +/** + * @brief Return a previously-retrieved item to the ring buffer + * + * @param[in] xRingbuffer Ring buffer the item was retrieved from + * @param[in] pvItem Item that was received earlier + * + * @note If a split item is retrieved, both parts should be returned by calling this function twice + */ +void vRingbufferReturnItem(RingbufHandle_t xRingbuffer, void *pvItem); + +/** + * @brief Return a previously-retrieved item to the ring buffer from an ISR + * + * @param[in] xRingbuffer Ring buffer the item was retrieved from + * @param[in] pvItem Item that was received earlier + * @param[out] pxHigherPriorityTaskWoken Value pointed to will be set to pdTRUE + * if the function woke up a higher priority task. + * + * @note If a split item is retrieved, both parts should be returned by calling this function twice + */ +void vRingbufferReturnItemFromISR(RingbufHandle_t xRingbuffer, void *pvItem, BaseType_t *pxHigherPriorityTaskWoken); + +/** + * @brief Delete a ring buffer + * + * @param[in] xRingbuffer Ring buffer to delete + * + * @note This function will not deallocate any memory if the ring buffer was + * created using xRingbufferCreateStatic(). Deallocation must be done + * manually be the user. + */ +void vRingbufferDelete(RingbufHandle_t xRingbuffer); + +/** + * @brief Get maximum size of an item that can be placed in the ring buffer + * + * This function returns the maximum size an item can have if it was placed in + * an empty ring buffer. + * + * @param[in] xRingbuffer Ring buffer to query + * + * @note The max item size for a no-split buffer is limited to + * ((buffer_size/2)-header_size). This limit is imposed so that an item + * of max item size can always be sent to the an empty no-split buffer + * regardless of the internal positions of the buffer's read/write/free + * pointers. + * + * @return Maximum size, in bytes, of an item that can be placed in a ring buffer. + */ +size_t xRingbufferGetMaxItemSize(RingbufHandle_t xRingbuffer); + +/** + * @brief Get current free size available for an item/data in the buffer + * + * This gives the real time free space available for an item/data in the ring + * buffer. This represents the maximum size an item/data can have if it was + * currently sent to the ring buffer. + * + * @warning This API is not thread safe. So, if multiple threads are accessing + * the same ring buffer, it is the application's responsibility to + * ensure atomic access to this API and the subsequent Send + * + * @note An empty no-split buffer has a max current free size for an item + * that is limited to ((buffer_size/2)-header_size). See API reference + * for xRingbufferGetMaxItemSize(). + * + * @param[in] xRingbuffer Ring buffer to query + * + * @return Current free size, in bytes, available for an entry + */ +size_t xRingbufferGetCurFreeSize(RingbufHandle_t xRingbuffer); + +/** + * @brief Add the ring buffer's read semaphore to a queue set. + * + * The ring buffer's read semaphore indicates that data has been written + * to the ring buffer. This function adds the ring buffer's read semaphore to + * a queue set. + * + * @param[in] xRingbuffer Ring buffer to add to the queue set + * @param[in] xQueueSet Queue set to add the ring buffer's read semaphore to + * + * @return + * - pdTRUE on success, pdFALSE otherwise + */ +BaseType_t xRingbufferAddToQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet); + + +/** + * @brief Check if the selected queue set member is the ring buffer's read semaphore + * + * This API checks if queue set member returned from xQueueSelectFromSet() + * is the read semaphore of this ring buffer. If so, this indicates the ring buffer + * has items waiting to be retrieved. + * + * @param[in] xRingbuffer Ring buffer which should be checked + * @param[in] xMember Member returned from xQueueSelectFromSet + * + * @return + * - pdTRUE when semaphore belongs to ring buffer + * - pdFALSE otherwise. + */ +BaseType_t xRingbufferCanRead(RingbufHandle_t xRingbuffer, QueueSetMemberHandle_t xMember); + +/** + * @brief Remove the ring buffer's read semaphore from a queue set. + * + * This specifically removes a ring buffer's read semaphore from a queue set. The + * read semaphore is used to indicate when data has been written to the ring buffer + * + * @param[in] xRingbuffer Ring buffer to remove from the queue set + * @param[in] xQueueSet Queue set to remove the ring buffer's read semaphore from + * + * @return + * - pdTRUE on success + * - pdFALSE otherwise + */ +BaseType_t xRingbufferRemoveFromQueueSetRead(RingbufHandle_t xRingbuffer, QueueSetHandle_t xQueueSet); + +/** + * @brief Get information about ring buffer status + * + * Get information of the a ring buffer's current status such as + * free/read/write pointer positions, and number of items waiting to be retrieved. + * Arguments can be set to NULL if they are not required. + * + * @param[in] xRingbuffer Ring buffer to remove from the queue set + * @param[out] uxFree Pointer use to store free pointer position + * @param[out] uxRead Pointer use to store read pointer position + * @param[out] uxWrite Pointer use to store write pointer position + * @param[out] uxAcquire Pointer use to store acquire pointer position + * @param[out] uxItemsWaiting Pointer use to store number of items (bytes for byte buffer) waiting to be retrieved + */ +void vRingbufferGetInfo(RingbufHandle_t xRingbuffer, + UBaseType_t *uxFree, + UBaseType_t *uxRead, + UBaseType_t *uxWrite, + UBaseType_t *uxAcquire, + UBaseType_t *uxItemsWaiting); + +/** + * @brief Debugging function to print the internal pointers in the ring buffer + * + * @param xRingbuffer Ring buffer to show + */ +void xRingbufferPrintInfo(RingbufHandle_t xRingbuffer); + +#ifdef __cplusplus +} +#endif + +#endif /* FREERTOS_RINGBUF_H */ diff --git a/tools/sdk/esp32c3/include/esp_rom/esp32c3/esp_rom_caps.h b/tools/sdk/esp32c3/include/esp_rom/esp32c3/esp_rom_caps.h new file mode 100644 index 00000000..bae770da --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/esp32c3/esp_rom_caps.h @@ -0,0 +1,20 @@ +// Copyright 2020 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. + +#pragma once + +#define ESP_ROM_HAS_CRC_LE (1) // ROM CRC library supports Little Endian +#define ESP_ROM_HAS_CRC_BE (1) // ROM CRC library supports Big Endian +#define ESP_ROM_HAS_JPEG_DECODE (1) // ROM has JPEG decode library +#define ESP_ROM_UART_CLK_IS_XTAL (1) // UART clock source is selected to XTAL in ROM diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/aes.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/aes.h new file mode 100644 index 00000000..bbe13d22 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/aes.h @@ -0,0 +1,57 @@ +/* + ROM functions for hardware AES support. + + It is not recommended to use these functions directly, + use the wrapper functions in esp32/aes.h instead. + + */ +// Copyright 2015-2016 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. + +#ifndef _ROM_AES_H_ +#define _ROM_AES_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//TODO, add comment for aes apis +enum AES_BITS { + AES128, + AES192, + AES256 +}; + +void ets_aes_enable(void); + +void ets_aes_disable(void); + +void ets_aes_set_endian(bool key_word_swap, bool key_byte_swap, + bool in_word_swap, bool in_byte_swap, + bool out_word_swap, bool out_byte_swap); + +bool ets_aes_setkey_enc(const uint8_t *key, enum AES_BITS bits); + +bool ets_aes_setkey_dec(const uint8_t *key, enum AES_BITS bits); + +void ets_aes_crypt(const uint8_t input[16], uint8_t output[16]); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_AES_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/bigint.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/bigint.h new file mode 100644 index 00000000..97ad7220 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/bigint.h @@ -0,0 +1,62 @@ +/* + ROM functions for hardware bigint support. + + It is not recommended to use these functions directly, + use the wrapper functions in hwcrypto/mpi.h instead. + + */ +// Copyright 2015-2016 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. + +#ifndef _ROM_BIGINT_H_ +#define _ROM_BIGINT_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//TODO: add comment here +void ets_bigint_enable(void); + +void ets_bigint_disable(void); + +void ets_bigint_wait_finish(void); + +bool ets_bigint_mod_power_prepare(uint32_t *x, uint32_t *y, uint32_t *m, + uint32_t m_dash, uint32_t *rb, uint32_t len, bool again); + +bool ets_bigint_mod_power_getz(uint32_t *z, uint32_t len); + +bool ets_bigint_mult_prepare(uint32_t *x, uint32_t *y, uint32_t len); + +bool ets_bigint_mult_getz(uint32_t *z, uint32_t len); + +bool ets_bigint_montgomery_mult_prepare(uint32_t *x, uint32_t *y, uint32_t *m, + uint32_t m_dash, uint32_t len, bool again); + +bool ets_bigint_montgomery_mult_getz(uint32_t *z, uint32_t len); + +bool ets_bigint_mod_mult_prepare(uint32_t *x, uint32_t *y, uint32_t *m, + uint32_t m_dash, uint32_t *rb, uint32_t len, bool again); + +bool ets_bigint_mod_mult_getz(uint32_t *m, uint32_t *z, uint32_t len); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_BIGINT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/cache.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/cache.h new file mode 100644 index 00000000..4b923e66 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/cache.h @@ -0,0 +1,186 @@ +// Copyright 2015-2016 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. + +#ifndef _ROM_CACHE_H_ +#define _ROM_CACHE_H_ + +#include "soc/dport_access.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + +/** + * @brief Initialise cache mmu, mark all entries as invalid. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : 0 for PRO cpu, 1 for APP cpu. + * + * @return None + */ +void mmu_init(int cpu_no); + +/** + * @brief Set Flash-Cache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : CPU number, 0 for PRO cpu, 1 for APP cpu. + * + * @param int pod : process identifier. Range 0~7. + * + * @param unsigned int vaddr : virtual address in CPU address space. + * Can be IRam0, IRam1, IRom0 and DRom0 memory address. + * Should be aligned by psize. + * + * @param unsigned int paddr : physical address in Flash. + * Should be aligned by psize. + * + * @param int psize : page size of flash, in kilobytes. Should be 64 here. + * + * @param int num : pages to be set. + * + * @return unsigned int: error status + * 0 : mmu set success + * 1 : vaddr or paddr is not aligned + * 2 : pid error + * 3 : psize error + * 4 : mmu table to be written is out of range + * 5 : vaddr is out of range + */ +static inline unsigned int IRAM_ATTR cache_flash_mmu_set(int cpu_no, int pid, unsigned int vaddr, unsigned int paddr, int psize, int num) +{ + extern unsigned int cache_flash_mmu_set_rom(int cpu_no, int pid, unsigned int vaddr, unsigned int paddr, int psize, int num); + + unsigned int ret; + + DPORT_STALL_OTHER_CPU_START(); + ret = cache_flash_mmu_set_rom(cpu_no, pid, vaddr, paddr, psize, num); + DPORT_STALL_OTHER_CPU_END(); + + return ret; +} + +/** + * @brief Set Ext-SRAM-Cache mmu mapping. + * Please do not call this function in your SDK application. + * + * Note that this code lives in IRAM and has a bugfix in respect to the ROM version + * of this function (which erroneously refused a vaddr > 2MiB + * + * @param int cpu_no : CPU number, 0 for PRO cpu, 1 for APP cpu. + * + * @param int pod : process identifier. Range 0~7. + * + * @param unsigned int vaddr : virtual address in CPU address space. + * Can be IRam0, IRam1, IRom0 and DRom0 memory address. + * Should be aligned by psize. + * + * @param unsigned int paddr : physical address in Ext-SRAM. + * Should be aligned by psize. + * + * @param int psize : page size of flash, in kilobytes. Should be 32 here. + * + * @param int num : pages to be set. + * + * @return unsigned int: error status + * 0 : mmu set success + * 1 : vaddr or paddr is not aligned + * 2 : pid error + * 3 : psize error + * 4 : mmu table to be written is out of range + * 5 : vaddr is out of range + */ +unsigned int IRAM_ATTR cache_sram_mmu_set(int cpu_no, int pid, unsigned int vaddr, unsigned int paddr, int psize, int num); + +/** + * @brief Initialise cache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : 0 for PRO cpu, 1 for APP cpu. + * + * @return None + */ +static inline void IRAM_ATTR Cache_Read_Init(int cpu_no) +{ + extern void Cache_Read_Init_rom(int cpu_no); + DPORT_STALL_OTHER_CPU_START(); + Cache_Read_Init_rom(cpu_no); + DPORT_STALL_OTHER_CPU_END(); +} + +/** + * @brief Flush the cache value for the cpu. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : 0 for PRO cpu, 1 for APP cpu. + * + * @return None + */ +static inline void IRAM_ATTR Cache_Flush(int cpu_no) +{ + extern void Cache_Flush_rom(int cpu_no); + DPORT_STALL_OTHER_CPU_START(); + Cache_Flush_rom(cpu_no); + DPORT_STALL_OTHER_CPU_END(); +} + +/** + * @brief Disable Cache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : 0 for PRO cpu, 1 for APP cpu. + * + * @return None + */ +static inline void IRAM_ATTR Cache_Read_Disable(int cpu_no) +{ + extern void Cache_Read_Disable_rom(int cpu_no); + DPORT_STALL_OTHER_CPU_START(); + Cache_Read_Disable_rom(cpu_no); + DPORT_STALL_OTHER_CPU_END(); +} + +/** + * @brief Enable Cache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param int cpu_no : 0 for PRO cpu, 1 for APP cpu. + * + * @return None + */ +static inline void IRAM_ATTR Cache_Read_Enable(int cpu_no) +{ + extern void Cache_Read_Enable_rom(int cpu_no); + DPORT_STALL_OTHER_CPU_START(); + Cache_Read_Enable_rom(cpu_no); + DPORT_STALL_OTHER_CPU_END(); +} + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_CACHE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/crc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/crc.h new file mode 100644 index 00000000..a5703611 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/crc.h @@ -0,0 +1,160 @@ +// Copyright 2015-2016 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. + +#ifndef ROM_CRC_H +#define ROM_CRC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + + +/* Notes about CRC APIs usage + * The ESP32 ROM include some CRC tables and CRC APIs to speed up CRC calculation. + * The CRC APIs include CRC8, CRC16, CRC32 algorithms for both little endian and big endian modes. + * Here are the polynomials for the algorithms: + * CRC-8 x8+x2+x1+1 0x07 + * CRC16-CCITT x16+x12+x5+1 0x1021 + * CRC32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x1+1 0x04c11db7 + * + * These group of CRC APIs are designed to calculate the data in buffers either continuous or not. + * To make it easy, we had added a `~` at the beginning and the end of the functions. + * To calculate non-continuous buffers, we can write the code like this: + * init = ~init; + * crc = crc32_le(init, buf0, length0); + * crc = crc32_le(crc, buf1, length1); + * crc = ~crc; + * + * However, it is not easy to select which API to use and give the correct parameters. + * A specific CRC algorithm will include this parameters: width, polynomials, init, refin, refout, xorout + * refin and refout show the endian of the algorithm: + * if both of them are true, please use the little endian API. + * if both of them are false, please use the big endian API. + * xorout is the value which you need to be xored to the raw result. + * However, these group of APIs need one '~' before and after the APIs. + * + * Here are some examples for CRC16: + * CRC-16/CCITT, poly = 0x1021, init = 0x0000, refin = true, refout = true, xorout = 0x0000 + * crc = ~crc16_le((uint16_t)~0x0000, buf, length); + * + * CRC-16/CCITT-FALSE, poly = 0x1021, init = 0xffff, refin = false, refout = false, xorout = 0x0000 + * crc = ~crc16_be((uint16_t)~0xffff, buf, length); + * + * CRC-16/X25, poly = 0x1021, init = 0xffff, refin = true, refout = true, xorout = 0xffff + * crc = (~crc16_le((uint16_t)~(0xffff), buf, length))^0xffff; + * + * CRC-16/XMODEM, poly= 0x1021, init = 0x0000, refin = false, refout = false, xorout = 0x0000 + * crc = ~crc16_be((uint16_t)~0x0000, buf, length); + * + * + */ + +/** + * @brief CRC32 value that is in little endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC32 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_be(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC16 value that is in little endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC16 value that is in big endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_be(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC8 value that is in little endian. + * + * @param uint8_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC8 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_be(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/efuse.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/efuse.h new file mode 100644 index 00000000..337227ab --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/efuse.h @@ -0,0 +1,117 @@ +// Copyright 2015-2016 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. + +#ifndef _ROM_EFUSE_H_ +#define _ROM_EFUSE_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup efuse_APIs efuse APIs + * @brief ESP32 efuse read/write APIs + * @attention + * + */ + +/** @addtogroup efuse_APIs + * @{ + */ + +/** + * @brief Do a efuse read operation, to update the efuse value to efuse read registers. + * + * @param null + * + * @return null + */ +void ets_efuse_read_op(void); + +/** + * @brief Do a efuse write operation, to update efuse write registers to efuse, then you need call ets_efuse_read_op again. + * + * @param null + * + * @return null + */ +void ets_efuse_program_op(void); + +/** + * @brief Read 8M Analog Clock value(8 bit) in efuse, the analog clock will not change with temperature. + * It can be used to test the external xtal frequency, do not touch this efuse field. + * + * @param null + * + * @return u32: 1 for 100KHZ, range is 0 to 255. + */ +uint32_t ets_efuse_get_8M_clock(void); + +/** + * @brief Read spi flash pin configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - 1 for default HSPI pins. + * - Other values define a custom pin configuration mask. Pins are encoded as per the EFUSE_SPICONFIG_RET_SPICLK, + * EFUSE_SPICONFIG_RET_SPIQ, EFUSE_SPICONFIG_RET_SPID, EFUSE_SPICONFIG_RET_SPICS0, EFUSE_SPICONFIG_RET_SPIHD macros. + * WP pin (for quad I/O modes) is not saved in efuse and not returned by this function. + */ +uint32_t ets_efuse_get_spiconfig(void); + +#define EFUSE_SPICONFIG_SPI_DEFAULTS 0 +#define EFUSE_SPICONFIG_HSPI_DEFAULTS 1 + +#define EFUSE_SPICONFIG_RET_SPICLK_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICLK_SHIFT 0 +#define EFUSE_SPICONFIG_RET_SPICLK(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICLK_SHIFT) & EFUSE_SPICONFIG_RET_SPICLK_MASK) + +#define EFUSE_SPICONFIG_RET_SPIQ_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIQ_SHIFT 6 +#define EFUSE_SPICONFIG_RET_SPIQ(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIQ_SHIFT) & EFUSE_SPICONFIG_RET_SPIQ_MASK) + +#define EFUSE_SPICONFIG_RET_SPID_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPID_SHIFT 12 +#define EFUSE_SPICONFIG_RET_SPID(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPID_SHIFT) & EFUSE_SPICONFIG_RET_SPID_MASK) + +#define EFUSE_SPICONFIG_RET_SPICS0_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICS0_SHIFT 18 +#define EFUSE_SPICONFIG_RET_SPICS0(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICS0_SHIFT) & EFUSE_SPICONFIG_RET_SPICS0_MASK) + + +#define EFUSE_SPICONFIG_RET_SPIHD_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIHD_SHIFT 24 +#define EFUSE_SPICONFIG_RET_SPIHD(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIHD_SHIFT) & EFUSE_SPICONFIG_RET_SPIHD_MASK) + +/** + * @brief A crc8 algorithm used in efuse check. + * + * @param unsigned char const *p : Pointer to original data. + * + * @param unsigned int len : Data length in byte. + * + * @return unsigned char: Crc value. + */ +unsigned char esp_crc8(unsigned char const *p, unsigned int len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_EFUSE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/ets_sys.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/ets_sys.h new file mode 100644 index 00000000..3485f0d4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/ets_sys.h @@ -0,0 +1,654 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_ETS_SYS_H_ +#define _ROM_ETS_SYS_H_ + +#include +#include +#include + +#include "sdkconfig.h" + +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/soc.h" +#endif + +#ifndef CONFIG_IDF_TARGET_ESP32 +#error "This header should only be included when building for ESP32" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup ets_sys_apis, ets system related apis + * @brief ets system apis + */ + +/** @addtogroup ets_sys_apis + * @{ + */ + +/************************************************************************ + * NOTE + * Many functions in this header files can't be run in FreeRTOS. + * Please see the comment of the Functions. + * There are also some functions that doesn't work on FreeRTOS + * without listed in the header, such as: + * xtos functions start with "_xtos_" in ld file. + * + *********************************************************************** + */ + +/** \defgroup ets_apis, Espressif Task Scheduler related apis + * @brief ets apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +typedef enum { + ETS_OK = 0, /**< return successful in ets*/ + ETS_FAILED = 1 /**< return failed in ets*/ +} ETS_STATUS; + +typedef uint32_t ETSSignal; +typedef uint32_t ETSParam; + +typedef struct ETSEventTag ETSEvent; /**< Event transmit/receive in ets*/ + +struct ETSEventTag { + ETSSignal sig; /**< Event signal, in same task, different Event with different signal*/ + ETSParam par; /**< Event parameter, sometimes without usage, then will be set as 0*/ +}; + +typedef void (*ETSTask)(ETSEvent *e); /**< Type of the Task processer*/ +typedef void (* ets_idle_cb_t)(void *arg); /**< Type of the system idle callback*/ + +/** + * @brief Start the Espressif Task Scheduler, which is an infinit loop. Please do not add code after it. + * + * @param none + * + * @return none + */ +void ets_run(void); + +/** + * @brief Set the Idle callback, when Tasks are processed, will call the callback before CPU goto sleep. + * + * @param ets_idle_cb_t func : The callback function. + * + * @param void *arg : Argument of the callback. + * + * @return None + */ +void ets_set_idle_cb(ets_idle_cb_t func, void *arg); + +/** + * @brief Init a task with processer, priority, queue to receive Event, queue length. + * + * @param ETSTask task : The task processer. + * + * @param uint8_t prio : Task priority, 0-31, bigger num with high priority, one priority with one task. + * + * @param ETSEvent *queue : Queue belongs to the task, task always receives Events, Queue is circular used. + * + * @param uint8_t qlen : Queue length. + * + * @return None + */ +void ets_task(ETSTask task, uint8_t prio, ETSEvent *queue, uint8_t qlen); + +/** + * @brief Post an event to an Task. + * + * @param uint8_t prio : Priority of the Task. + * + * @param ETSSignal sig : Event signal. + * + * @param ETSParam par : Event parameter + * + * @return ETS_OK : post successful + * @return ETS_FAILED : post failed + */ +ETS_STATUS ets_post(uint8_t prio, ETSSignal sig, ETSParam par); + +/** + * @} + */ + +/** \defgroup ets_boot_apis, Boot routing related apis + * @brief ets boot apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +extern const char *const exc_cause_table[40]; ///**< excption cause that defined by the core.*/ + +/** + * @brief Set Pro cpu Entry code, code can be called in PRO CPU when booting is not completed. + * When Pro CPU booting is completed, Pro CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the PRO Entry code address value in uint32_t + * + * @return None + */ +void ets_set_user_start(uint32_t start); + +/** + * @brief Set Pro cpu Startup code, code can be called when booting is not completed, or in Entry code. + * When Entry code completed, CPU will call the Startup code if not NULL, else call ets_run. + * + * @param uint32_t callback : the Startup code address value in uint32_t + * + * @return None : post successful + */ +void ets_set_startup_callback(uint32_t callback); + +/** + * @brief Set App cpu Entry code, code can be called in PRO CPU. + * When APP booting is completed, APP CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the APP Entry code address value in uint32_t, stored in register APPCPU_CTRL_REG_D. + * + * @return None + */ +void ets_set_appcpu_boot_addr(uint32_t start); + +/** + * @brief unpack the image in flash to iram and dram, no using cache. + * + * @param uint32_t pos : Flash physical address. + * + * @param uint32_t *entry_addr: the pointer of an variable that can store Entry code address. + * + * @param bool jump : Jump into the code in the function or not. + * + * @param bool config : Config the flash when unpacking the image, config should be done only once. + * + * @return ETS_OK : unpack successful + * @return ETS_FAILED : unpack failed + */ +ETS_STATUS ets_unpack_flash_code_legacy(uint32_t pos, uint32_t *entry_addr, bool jump, bool config); + +/** + * @brief unpack the image in flash to iram and dram, using cache, maybe decrypting. + * + * @param uint32_t pos : Flash physical address. + * + * @param uint32_t *entry_addr: the pointer of an variable that can store Entry code address. + * + * @param bool jump : Jump into the code in the function or not. + * + * @param bool sb_need_check : Do security boot check or not. + * + * @param bool config : Config the flash when unpacking the image, config should be done only once. + * + * @return ETS_OK : unpack successful + * @return ETS_FAILED : unpack failed + */ +ETS_STATUS ets_unpack_flash_code(uint32_t pos, uint32_t *entry_addr, bool jump, bool sb_need_check, bool config); + +/** + * @} + */ + +/** \defgroup ets_printf_apis, ets_printf related apis used in ets + * @brief ets printf apis + */ + +/** @addtogroup ets_printf_apis + * @{ + */ + +/** + * @brief Printf the strings to uart or other devices, similar with printf, simple than printf. + * Can not print float point data format, or longlong data format. + * So we maybe only use this in ROM. + * + * @param const char *fmt : See printf. + * + * @param ... : See printf. + * + * @return int : the length printed to the output device. + */ +int ets_printf(const char *fmt, ...); + +/** + * @brief Output a char to uart, which uart to output(which is in uart module in ROM) is not in scope of the function. + * Can not print float point data format, or longlong data format + * + * @param char c : char to output. + * + * @return None + */ +void ets_write_char_uart(char c); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc1, which is defaulted installed as ets_write_char_uart in none silent boot mode, as NULL in silent mode. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc1(void (*p)(char c)); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc2, which is defaulted installed as NULL. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc2(void (*p)(char c)); + +/** + * @brief Install putc1 as ets_write_char_uart. + * In silent boot mode(to void interfere the UART attached MCU), we can call this function, after booting ok. + * + * @param None + * + * @return None + */ +void ets_install_uart_printf(void); + +#define ETS_PRINTF(...) ets_printf(...) + +#define ETS_ASSERT(v) do { \ + if (!(v)) { \ + ets_printf("%s %u \n", __FILE__, __LINE__); \ + while (1) {}; \ + } \ +} while (0) + +/** + * @} + */ + +/** \defgroup ets_timer_apis, ets_timer related apis used in ets + * @brief ets timer apis + */ + +/** @addtogroup ets_timer_apis + * @{ + */ +typedef void ETSTimerFunc(void *timer_arg);/**< timer handler*/ + +typedef struct _ETSTIMER_ { + struct _ETSTIMER_ *timer_next; /**< timer linker*/ + uint32_t timer_expire; /**< abstruct time when timer expire*/ + uint32_t timer_period; /**< timer period, 0 means timer is not periodic repeated*/ + ETSTimerFunc *timer_func; /**< timer handler*/ + void *timer_arg; /**< timer handler argument*/ +} ETSTimer; + +/** + * @brief Init ets timer, this timer range is 640 us to 429496 ms + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_init(void); + +/** + * @brief In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_deinit(void); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in ms, range is 1 to 429496. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm(ETSTimer *timer, uint32_t tmout, bool repeat); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in us, range is 1 to 429496729. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm_us(ETSTimer *ptimer, uint32_t us, bool repeat); + +/** + * @brief Disarm an ets timer. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_disarm(ETSTimer *timer); + +/** + * @brief Set timer callback and argument. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param ETSTimerFunc *pfunction : Timer callback. + * + * @param void *parg : Timer callback argument. + * + * @return None + */ +void ets_timer_setfn(ETSTimer *ptimer, ETSTimerFunc *pfunction, void *parg); + +/** + * @brief Unset timer callback and argument to NULL. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_done(ETSTimer *ptimer); + +/** + * @brief CPU do while loop for some time. + * In FreeRTOS task, please call FreeRTOS apis. + * + * @param uint32_t us : Delay time in us. + * + * @return None + */ +void ets_delay_us(uint32_t us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * Call this function when CPU frequency is changed. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency(uint32_t ticks_per_us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * + * @note This function only sets the tick rate for the current CPU. It is located in ROM, + * so the deep sleep stub can use it even if IRAM is not initialized yet. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency_rom(uint32_t ticks_per_us); + +/** + * @brief Get the real CPU ticks per us to the ets. + * This function do not return real CPU ticks per us, just the record in ets. It can be used to check with the real CPU frequency. + * + * @param None + * + * @return uint32_t : CPU ticks per us record in ets. + */ +uint32_t ets_get_cpu_frequency(void); + +/** + * @brief Get xtal_freq/analog_8M*256 value calibrated in rtc module. + * + * @param None + * + * @return uint32_t : xtal_freq/analog_8M*256. + */ +uint32_t ets_get_xtal_scale(void); + +/** + * @brief Get xtal_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if rtc store the value (RTC_STORE5 high 16 bits and low 16 bits with same value), read from rtc register. + * clock = (REG_READ(RTC_STORE5) & 0xffff) << 12; + * else if analog_8M in efuse + * clock = ets_get_xtal_scale() * 15625 * ets_efuse_get_8M_clock() / 40; + * else clock = 26M. + */ +uint32_t ets_get_detected_xtal_freq(void); + +/** + * @} + */ + +/** \defgroup ets_intr_apis, ets interrupt configure related apis + * @brief ets intr apis + */ + +/** @addtogroup ets_intr_apis + * @{ + */ + +typedef void (* ets_isr_t)(void *);/**< interrupt handler type*/ + +/** + * @brief Attach a interrupt handler to a CPU interrupt number. + * This function equals to _xtos_set_interrupt_handler_arg(i, func, arg). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param int i : CPU interrupt number. + * + * @param ets_isr_t func : Interrupt handler. + * + * @param void *arg : argument of the handler. + * + * @return None + */ +void ets_isr_attach(int i, ets_isr_t func, void *arg); + +/** + * @brief Mask the interrupts which show in mask bits. + * This function equals to _xtos_ints_off(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_mask(uint32_t mask); + +/** + * @brief Unmask the interrupts which show in mask bits. + * This function equals to _xtos_ints_on(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_unmask(uint32_t unmask); + +/** + * @brief Lock the interrupt to level 2. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_lock(void); + +/** + * @brief Unlock the interrupt to level 0. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_unlock(void); + +/** + * @brief Unlock the interrupt to level 0, and CPU will go into power save mode(wait interrupt). + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_waiti0(void); + +/** + * @brief Attach an CPU interrupt to a hardware source. + * We have 4 steps to use an interrupt: + * 1.Attach hardware interrupt source to CPU. intr_matrix_set(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM); + * 2.Set interrupt handler. xt_set_interrupt_handler(ETS_WMAC_INUM, func, NULL); + * 3.Enable interrupt for CPU. xt_ints_on(1 << ETS_WMAC_INUM); + * 4.Enable interrupt in the module. + * + * @param int cpu_no : The CPU which the interrupt number belongs. + * + * @param uint32_t model_num : The interrupt hardware source number, please see the interrupt hardware source table. + * + * @param uint32_t intr_num : The interrupt number CPU, please see the interrupt cpu using table. + * + * @return None + */ +void intr_matrix_set(int cpu_no, uint32_t model_num, uint32_t intr_num); + +#define _ETSTR(v) # v +#define _ETS_SET_INTLEVEL(intlevel) ({ unsigned __tmp; \ + __asm__ __volatile__( "rsil %0, " _ETSTR(intlevel) "\n" \ + : "=a" (__tmp) : : "memory" ); \ + }) + +#ifdef CONFIG_NONE_OS +#define ETS_INTR_LOCK() \ + ets_intr_lock() + +#define ETS_INTR_UNLOCK() \ + ets_intr_unlock() + +#define ETS_ISR_ATTACH \ + ets_isr_attach + +#define ETS_INTR_ENABLE(inum) \ + ets_isr_unmask((1< +#include + +#include "esp_attr.h" + +#include "sdkconfig.h" + +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/gpio_reg.h" +#include "soc/soc_caps.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup gpio_apis, uart configuration and communication related apis + * @brief gpio apis + */ + +/** @addtogroup gpio_apis + * @{ + */ + +#define GPIO_REG_READ(reg) READ_PERI_REG(reg) +#define GPIO_REG_WRITE(reg, val) WRITE_PERI_REG(reg, val) +#define GPIO_ID_PIN0 0 +#define GPIO_ID_PIN(n) (GPIO_ID_PIN0+(n)) +#define GPIO_PIN_ADDR(i) (GPIO_PIN0_REG + i*4) + +#define GPIO_FUNC_IN_HIGH 0x38 +#define GPIO_FUNC_IN_LOW 0x30 + +#define GPIO_ID_IS_PIN_REGISTER(reg_id) \ + ((reg_id >= GPIO_ID_PIN0) && (reg_id <= GPIO_ID_PIN(GPIO_PIN_COUNT-1))) + +#define GPIO_REGID_TO_PINIDX(reg_id) ((reg_id) - GPIO_ID_PIN0) + +typedef enum { + GPIO_PIN_INTR_DISABLE = 0, + GPIO_PIN_INTR_POSEDGE = 1, + GPIO_PIN_INTR_NEGEDGE = 2, + GPIO_PIN_INTR_ANYEDGE = 3, + GPIO_PIN_INTR_LOLEVEL = 4, + GPIO_PIN_INTR_HILEVEL = 5 +} GPIO_INT_TYPE; + +#define GPIO_OUTPUT_SET(gpio_no, bit_value) \ + ((gpio_no < 32) ? gpio_output_set(bit_value<>gpio_no)&BIT0) : ((gpio_input_get_high()>>(gpio_no - 32))&BIT0)) + +/* GPIO interrupt handler, registered through gpio_intr_handler_register */ +typedef void (* gpio_intr_handler_fn_t)(uint32_t intr_mask, bool high, void *arg); + +/** + * @brief Initialize GPIO. This includes reading the GPIO Configuration DataSet + * to initialize "output enables" and pin configurations for each gpio pin. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_init(void); + +/** + * @brief Change GPIO(0-31) pin output by setting, clearing, or disabling pins, GPIO0<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Change GPIO(32-39) pin output by setting, clearing, or disabling pins, GPIO32<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set_high(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Sample the value of GPIO input pins(0-31) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO0. + */ +uint32_t gpio_input_get(void); + +/** + * @brief Sample the value of GPIO input pins(32-39) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO32. + */ +uint32_t gpio_input_get_high(void); + +/** + * @brief Register an application-specific interrupt handler for GPIO pin interrupts. + * Once the interrupt handler is called, it will not be called again until after a call to gpio_intr_ack. + * Please do not call this function in SDK. + * + * @param gpio_intr_handler_fn_t fn : gpio application-specific interrupt handler + * + * @param void *arg : gpio application-specific interrupt handler argument. + * + * @return None + */ +void gpio_intr_handler_register(gpio_intr_handler_fn_t fn, void *arg); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO0. + */ +uint32_t gpio_intr_pending(void); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO32. + */ +uint32_t gpio_intr_pending_high(void); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO0. + * + * @return None + */ +void gpio_intr_ack(uint32_t ack_mask); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO32. + * + * @return None + */ +void gpio_intr_ack_high(uint32_t ack_mask); + +/** + * @brief Set GPIO to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param uint32_t i: gpio number. + * + * @param GPIO_INT_TYPE intr_state : only GPIO_PIN_INTR_LOLEVEL\GPIO_PIN_INTR_HILEVEL can be used + * + * @return None + */ +void gpio_pin_wakeup_enable(uint32_t i, GPIO_INT_TYPE intr_state); + +/** + * @brief disable GPIOs to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_pin_wakeup_disable(void); + +/** + * @brief set gpio input to a signal, one gpio can input to several signals. + * + * @param uint32_t gpio : gpio number, 0~0x27 + * gpio == 0x30, input 0 to signal + * gpio == 0x34, ??? + * gpio == 0x38, input 1 to signal + * + * @param uint32_t signal_idx : signal index. + * + * @param bool inv : the signal is inv or not + * + * @return None + */ +void gpio_matrix_in(uint32_t gpio, uint32_t signal_idx, bool inv); + +/** + * @brief set signal output to gpio, one signal can output to several gpios. + * + * @param uint32_t gpio : gpio number, 0~0x27 + * + * @param uint32_t signal_idx : signal index. + * signal_idx == 0x100, cancel output put to the gpio + * + * @param bool out_inv : the signal output is inv or not + * + * @param bool oen_inv : the signal output enable is inv or not + * + * @return None + */ +void gpio_matrix_out(uint32_t gpio, uint32_t signal_idx, bool out_inv, bool oen_inv); + +/** + * @brief Select pad as a gpio function from IOMUX. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @return None + */ +void gpio_pad_select_gpio(uint8_t gpio_num); + +/** + * @brief Set pad driver capability. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @param uint8_t drv : 0-3 + * + * @return None + */ +void gpio_pad_set_drv(uint8_t gpio_num, uint8_t drv); + +/** + * @brief Pull up the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @return None + */ +void gpio_pad_pullup(uint8_t gpio_num); + +/** + * @brief Pull down the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @return None + */ +void gpio_pad_pulldown(uint8_t gpio_num); + +/** + * @brief Unhold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @return None + */ +void gpio_pad_unhold(uint8_t gpio_num); + +/** + * @brief Hold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x27 + * + * @return None + */ +void gpio_pad_hold(uint8_t gpio_num); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_GPIO_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/libc_stubs.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/libc_stubs.h new file mode 100644 index 00000000..47e75bcb --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/libc_stubs.h @@ -0,0 +1,89 @@ +// Copyright 2015-2016 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. +#ifndef _ROM_LIBC_STUBS_H_ +#define _ROM_LIBC_STUBS_H_ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* +ESP32 ROM code contains implementations of some of C library functions. +Whenever a function in ROM needs to use a syscall, it calls a pointer to the corresponding syscall +implementation defined in the following struct. + +The table itself, by default, is not allocated in RAM. There are two pointers, `syscall_table_ptr_pro` and +`syscall_table_ptr_app`, which can be set to point to the locations of syscall tables of CPU 0 (aka PRO CPU) +and CPU 1 (aka APP CPU). Location of these pointers in .bss segment of ROM code is defined in linker script. + +So, before using any of the C library functions (except for pure functions and memcpy/memset functions), +application must allocate syscall table structure for each CPU being used, and populate it with pointers +to actual implementations of corresponding syscalls. +*/ + +struct syscall_stub_table +{ + struct _reent* (*__getreent)(void); + void* (*_malloc_r)(struct _reent *r, size_t); + void (*_free_r)(struct _reent *r, void*); + void* (*_realloc_r)(struct _reent *r, void*, size_t); + void* (*_calloc_r)(struct _reent *r, size_t, size_t); + void (*_abort)(void); + int (*_system_r)(struct _reent *r, const char*); + int (*_rename_r)(struct _reent *r, const char*, const char*); + clock_t (*_times_r)(struct _reent *r, struct tms *); + int (*_gettimeofday_r) (struct _reent *r, struct timeval *, void *); + void (*_raise_r)(struct _reent *r); /* function signature is incorrect in ROM */ + int (*_unlink_r)(struct _reent *r, const char*); + int (*_link_r)(struct _reent *r, const char*, const char*); + int (*_stat_r)(struct _reent *r, const char*, struct stat *); + int (*_fstat_r)(struct _reent *r, int, struct stat *); + void* (*_sbrk_r)(struct _reent *r, ptrdiff_t); + int (*_getpid_r)(struct _reent *r); + int (*_kill_r)(struct _reent *r, int, int); + void (*_exit_r)(struct _reent *r, int); + int (*_close_r)(struct _reent *r, int); + int (*_open_r)(struct _reent *r, const char *, int, int); + int (*_write_r)(struct _reent *r, int, const void *, int); + int (*_lseek_r)(struct _reent *r, int, int, int); + int (*_read_r)(struct _reent *r, int, void *, int); + void (*_lock_init)(_lock_t *lock); + void (*_lock_init_recursive)(_lock_t *lock); + void (*_lock_close)(_lock_t *lock); + void (*_lock_close_recursive)(_lock_t *lock); + void (*_lock_acquire)(_lock_t *lock); + void (*_lock_acquire_recursive)(_lock_t *lock); + int (*_lock_try_acquire)(_lock_t *lock); + int (*_lock_try_acquire_recursive)(_lock_t *lock); + void (*_lock_release)(_lock_t *lock); + void (*_lock_release_recursive)(_lock_t *lock); + int (*_printf_float)(struct _reent *data, void *pdata, FILE * fp, int (*pfunc) (struct _reent *, FILE *, const char *, size_t len), va_list * ap); + int (*_scanf_float) (struct _reent *rptr, void *pdata, FILE *fp, va_list *ap); +}; + +extern struct syscall_stub_table* syscall_table_ptr_pro; +extern struct syscall_stub_table* syscall_table_ptr_app; + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /* _ROM_LIBC_STUBS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/lldesc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/lldesc.h new file mode 100644 index 00000000..ae5b4160 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/lldesc.h @@ -0,0 +1,176 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_LLDESC_H_ +#define _ROM_LLDESC_H_ + +#include + +#include "sys/queue.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LLDESC_TX_MBLK_SIZE 268 /* */ +#define LLDESC_RX_SMBLK_SIZE 64 /* small block size, for small mgmt frame */ +#define LLDESC_RX_MBLK_SIZE 524 /* rx is large sinec we want to contain mgmt frame in one block*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_SIZE 64 /* it is a small buffer which is a cycle link*/ +#define LLDESC_RX_AMPDU_LEN_MBLK_SIZE 256 /*for ampdu entry*/ +#ifdef ESP_MAC_5 +#define LLDESC_TX_MBLK_NUM 116 /* 64K / 256 */ +#define LLDESC_RX_MBLK_NUM 82 /* 64K / 512 MAX 172*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 12 +#else +#ifdef SBUF_RXTX +#define LLDESC_TX_MBLK_NUM_MAX (2 * 48) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MAX (2 * 48) /* 23K / 524 */ +#define LLDESC_TX_MBLK_NUM_MIN (2 * 16) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MIN (2 * 16) /* 23K / 524 */ +#endif +#define LLDESC_TX_MBLK_NUM 10 //(2 * 32) /* 23K / 260 - 8 */ + +#ifdef IEEE80211_RX_AMPDU +#define LLDESC_RX_MBLK_NUM 30 +#else +#define LLDESC_RX_MBLK_NUM 10 +#endif /*IEEE80211_RX_AMPDU*/ + +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 8 +#endif /* !ESP_MAC_5 */ +/* + * SLC2 DMA Desc struct, aka lldesc_t + * + * -------------------------------------------------------------- + * | own | EoF | sub_sof | 5'b0 | length [11:0] | size [11:0] | + * -------------------------------------------------------------- + * | buf_ptr [31:0] | + * -------------------------------------------------------------- + * | next_desc_ptr [31:0] | + * -------------------------------------------------------------- + */ + +/* this bitfield is start from the LSB!!! */ +typedef struct lldesc_s { + volatile uint32_t size :12, + length:12, + offset: 5, /* h/w reserved 5bit, s/w use it as offset in buffer */ + sosf : 1, /* start of sub-frame */ + eof : 1, /* end of frame */ + owner : 1; /* hw or sw */ + volatile uint8_t *buf; /* point to buffer data */ + union{ + volatile uint32_t empty; + STAILQ_ENTRY(lldesc_s) qe; /* pointing to the next desc */ + }; +} lldesc_t; + +typedef struct tx_ampdu_entry_s{ + uint32_t sub_len :12, + dili_num : 7, + : 1, + null_byte: 2, + data : 1, + enc : 1, + seq : 8; +} tx_ampdu_entry_t; + +typedef struct lldesc_chain_s { + lldesc_t *head; + lldesc_t *tail; +} lldesc_chain_t; + +#ifdef SBUF_RXTX +enum sbuf_mask_s { + SBUF_MOVE_NO = 0, + SBUF_MOVE_TX2RX, + SBUF_MOVE_RX2TX, +} ; + +#define SBUF_MOVE_STEP 8 +#endif +#define LLDESC_SIZE sizeof(struct lldesc_s) + +/* SLC Descriptor */ +#define LLDESC_OWNER_MASK 0x80000000 +#define LLDESC_OWNER_SHIFT 31 +#define LLDESC_SW_OWNED 0 +#define LLDESC_HW_OWNED 1 + +#define LLDESC_EOF_MASK 0x40000000 +#define LLDESC_EOF_SHIFT 30 + +#define LLDESC_SOSF_MASK 0x20000000 +#define LLDESC_SOSF_SHIFT 29 + +#define LLDESC_LENGTH_MASK 0x00fff000 +#define LLDESC_LENGTH_SHIFT 12 + +#define LLDESC_SIZE_MASK 0x00000fff +#define LLDESC_SIZE_SHIFT 0 + +#define LLDESC_ADDR_MASK 0x000fffff + +void lldesc_build_chain(uint8_t *descptr, uint32_t desclen, uint8_t * mblkptr, uint32_t buflen, uint32_t blksz, uint8_t owner, + lldesc_t **head, +#ifdef TO_HOST_RESTART + lldesc_t ** one_before_tail, +#endif + lldesc_t **tail); + +lldesc_t *lldesc_num2link(lldesc_t * head, uint16_t nblks); + +lldesc_t *lldesc_set_owner(lldesc_t * head, uint16_t nblks, uint8_t owner); + +static inline uint32_t lldesc_get_chain_length(lldesc_t *head) +{ + lldesc_t *ds = head; + uint32_t len = 0; + + while (ds) { + len += ds->length; + ds = STAILQ_NEXT(ds, qe); + } + + return len; +} + +static inline void lldesc_config(lldesc_t *ds, uint8_t owner, uint8_t eof, uint8_t sosf, uint16_t len) +{ + ds->owner = owner; + ds->eof = eof; + ds->sosf = sosf; + ds->length = len; +} + +#define LLDESC_CONFIG(_desc, _owner, _eof, _sosf, _len) do { \ + (_desc)->owner = (_owner); \ + (_desc)->eof = (_eof); \ + (_desc)->sosf = (_sosf); \ + (_desc)->length = (_len); \ +} while(0) + +#define LLDESC_FROM_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#define LLDESC_MAC_RX_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, (ds)->size) + +#define LLDESC_TO_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_LLDESC_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/md5_hash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/md5_hash.h new file mode 100644 index 00000000..f116f1e6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/md5_hash.h @@ -0,0 +1,38 @@ +/* + * MD5 internal definitions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#ifndef _ROM_MD5_HASH_H_ +#define _ROM_MD5_HASH_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); +void MD5Final(unsigned char digest[16], struct MD5Context *context); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_MD5_HASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/miniz.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/miniz.h new file mode 100644 index 00000000..7661f804 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/miniz.h @@ -0,0 +1,791 @@ +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times, and the C run-time funcs that get/set times won't be called. +// The current downside is the times written to your archives will be from 1979. +#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +#define MINIZ_NO_MALLOC + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) + // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux + #define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) + #include +#endif + +//Hardcoded options for Xtensa - JD +#define MINIZ_X86_OR_X64_CPU 0 +#define MINIZ_LITTLE_ENDIAN 1 +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_HAS_64BIT_REGISTERS 0 +#define TINFL_USE_64BIT_BITBUF 0 + + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s +{ + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; + #define Z_NULL 0 + #define Z_NO_FLUSH MZ_NO_FLUSH + #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH + #define Z_SYNC_FLUSH MZ_SYNC_FLUSH + #define Z_FULL_FLUSH MZ_FULL_FLUSH + #define Z_FINISH MZ_FINISH + #define Z_BLOCK MZ_BLOCK + #define Z_OK MZ_OK + #define Z_STREAM_END MZ_STREAM_END + #define Z_NEED_DICT MZ_NEED_DICT + #define Z_ERRNO MZ_ERRNO + #define Z_STREAM_ERROR MZ_STREAM_ERROR + #define Z_DATA_ERROR MZ_DATA_ERROR + #define Z_MEM_ERROR MZ_MEM_ERROR + #define Z_BUF_ERROR MZ_BUF_ERROR + #define Z_VERSION_ERROR MZ_VERSION_ERROR + #define Z_PARAM_ERROR MZ_PARAM_ERROR + #define Z_NO_COMPRESSION MZ_NO_COMPRESSION + #define Z_BEST_SPEED MZ_BEST_SPEED + #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION + #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION + #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY + #define Z_FILTERED MZ_FILTERED + #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY + #define Z_RLE MZ_RLE + #define Z_FIXED MZ_FIXED + #define Z_DEFLATED MZ_DEFLATED + #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + #define alloc_func mz_alloc_func + #define free_func mz_free_func + #define internal_state mz_internal_state + #define z_stream mz_stream + #define deflateInit mz_deflateInit + #define deflateInit2 mz_deflateInit2 + #define deflateReset mz_deflateReset + #define deflate mz_deflate + #define deflateEnd mz_deflateEnd + #define deflateBound mz_deflateBound + #define compress mz_compress + #define compress2 mz_compress2 + #define compressBound mz_compressBound + #define inflateInit mz_inflateInit + #define inflateInit2 mz_inflateInit2 + #define inflate mz_inflate + #define inflateEnd mz_inflateEnd + #define uncompress mz_uncompress + #define crc32 mz_crc32 + #define adler32 mz_adler32 + #define MAX_WBITS 15 + #define MAX_MEM_LEVEL 9 + #define zError mz_error + #define ZLIB_VERSION MZ_VERSION + #define ZLIB_VERNUM MZ_VERNUM + #define ZLIB_VER_MAJOR MZ_VER_MAJOR + #define ZLIB_VER_MINOR MZ_VER_MINOR + #define ZLIB_VER_REVISION MZ_VER_REVISION + #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + #define zlibVersion mz_version + #define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct +{ + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct mz_zip_archive_tag +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +// +// Note: Due to MINIZ_NO_MALLOC, this function will not work. +// +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags) __attribute__((warning("miniz is compiled without malloc so this function does not work"))); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +// +// Note: Due to MINIZ_NO_MALLOC, this function will not work. +// +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) __attribute__((warning("miniz is compiled without malloc so this function does not work"))); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// +// Note: Due to MINIZ_NO_MALLOC, this function will not work. +// +// Returns 1 on success or 0 or -1 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) __attribute__((warning("miniz is compiled without malloc so this function does not work")));; + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 1 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum +{ + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +// +// Note: Due to MINIZ_NO_MALLOC, this function will not work. +// +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) __attribute__((warning("miniz is compiled without malloc so this function does not work")));; + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL +// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +// +// Note: Due to MINIZ_NO_MALLOC, this function will not work. +// +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) __attribute__((warning("miniz is compiled without malloc so this function does not work")));; + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rsa_pss.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rsa_pss.h new file mode 100644 index 00000000..bfc1e68c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rsa_pss.h @@ -0,0 +1,50 @@ +// Copyright 2020 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. + +#pragma once + +#include "sdkconfig.h" +#ifdef CONFIG_ESP32_REV_MIN_3 + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ETS_SIG_LEN 384 /* Bytes */ +#define ETS_DIGEST_LEN 32 /* SHA-256, bytes */ + +/* Secure Boot Version 2 - Public Key format */ +typedef struct { + uint8_t n[384]; /* Public key modulus */ + uint32_t e; /* Public key exponent */ + uint8_t rinv[384]; + uint32_t mdash; +} ets_rsa_pubkey_t; + + +bool ets_rsa_pss_verify(const ets_rsa_pubkey_t *key, const uint8_t *sig, const uint8_t *digest, uint8_t *verified_digest); + +void ets_mgf1_sha256(const uint8_t *mgfSeed, size_t seedLen, size_t maskLen, uint8_t *mask); + +bool ets_emsa_pss_verify(const uint8_t *encoded_message, const uint8_t *mhash, uint8_t *verified_digest); + +#ifdef __cplusplus +} +#endif + +#endif // CONFIG_ESP32_REV_MIN_3 diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rtc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rtc.h new file mode 100644 index 00000000..79ad9b0a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/rtc.h @@ -0,0 +1,237 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_RTC_H_ +#define _ROM_RTC_H_ + +#include "ets_sys.h" + +#include +#include + +#include "soc/soc.h" +#include "soc/rtc_cntl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup rtc_apis, rtc registers and memory related apis + * @brief rtc apis + */ + +/** @addtogroup rtc_apis + * @{ + */ + +/************************************************************************************** + * Note: * + * Some Rtc memory and registers are used, in ROM or in internal library. * + * Please do not use reserved or used rtc memory or registers. * + * * + ************************************************************************************* + * RTC Memory & Store Register usage + ************************************************************************************* + * rtc memory addr type size usage + * 0x3ff61000(0x50000000) Slow SIZE_CP Co-Processor code/Reset Entry + * 0x3ff61000+SIZE_CP Slow 8192-SIZE_CP + * + * 0x3ff80000(0x400c0000) Fast 8192 deep sleep entry code + * + ************************************************************************************* + * RTC store registers usage + * RTC_CNTL_STORE0_REG Reserved + * RTC_CNTL_STORE1_REG RTC_SLOW_CLK calibration value + * RTC_CNTL_STORE2_REG Boot time, low word + * RTC_CNTL_STORE3_REG Boot time, high word + * RTC_CNTL_STORE4_REG External XTAL frequency. The frequency must necessarily be even, otherwise there will be a conflict with the low bit, which is used to disable logs in the ROM code. + * RTC_CNTL_STORE5_REG APB bus frequency + * RTC_CNTL_STORE6_REG FAST_RTC_MEMORY_ENTRY + * RTC_CNTL_STORE7_REG FAST_RTC_MEMORY_CRC + ************************************************************************************* + */ + +#define RTC_SLOW_CLK_CAL_REG RTC_CNTL_STORE1_REG +#define RTC_BOOT_TIME_LOW_REG RTC_CNTL_STORE2_REG +#define RTC_BOOT_TIME_HIGH_REG RTC_CNTL_STORE3_REG +#define RTC_XTAL_FREQ_REG RTC_CNTL_STORE4_REG +#define RTC_APB_FREQ_REG RTC_CNTL_STORE5_REG +#define RTC_ENTRY_ADDR_REG RTC_CNTL_STORE6_REG +#define RTC_RESET_CAUSE_REG RTC_CNTL_STORE6_REG +#define RTC_MEMORY_CRC_REG RTC_CNTL_STORE7_REG + +#define RTC_DISABLE_ROM_LOG ((1 << 0) | (1 << 16)) //!< Disable logging from the ROM code. + +typedef enum { + AWAKE = 0, // +#include "ets_sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void ets_secure_boot_start(void); + +void ets_secure_boot_finish(void); + +void ets_secure_boot_hash(const uint32_t *buf); + +void ets_secure_boot_obtain(void); + +int ets_secure_boot_check(uint32_t *buf); + +void ets_secure_boot_rd_iv(uint32_t *buf); + +void ets_secure_boot_rd_abstract(uint32_t *buf); + +bool ets_secure_boot_check_start(uint8_t abs_index, uint32_t iv_addr); + +int ets_secure_boot_check_finish(uint32_t *abstract); + +#ifdef CONFIG_ESP32_REV_MIN_3 +#include "rsa_pss.h" + +#define SECURE_BOOT_NUM_BLOCKS 1 + +#define CRC_SIGN_BLOCK_LEN 1196 +#define SIG_BLOCK_PADDING 4096 +#define ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC 0xE7 + +// Anti-FI measure: use full words for success/fail internally, instead of 0/non-zero +typedef enum { + SBV2_SUCCESS = 0x3A5A5AA5, + SB_SUCCESS = 0x3A5A5AA5, + SBV2_FAILED = 0xA533885A, + SB_FAILED = 0xA533885A, +} secure_boot_v2_status_t; + +/* Secure Boot Version 2 signature format for ESP32 ECO3 */ +typedef struct { + uint8_t magic_byte; + uint8_t version; + uint8_t _reserved1; + uint8_t _reserved2; + uint8_t image_digest[32]; + ets_rsa_pubkey_t key; + uint8_t signature[384]; + uint32_t block_crc; + uint8_t _padding[16]; +} ets_secure_boot_sig_block_t; +_Static_assert(sizeof(ets_secure_boot_sig_block_t) == 1216, "invalid sig block size"); + +/* ROM supports up to 3, but IDF only checks the first one (SECURE_BOOT_NUM_BLOCKS) */ +#define SECURE_BOOT_MAX_APPENDED_SIGN_BLOCKS_TO_IMAGE 3 + +/* Multiple key block support */ +typedef struct { + ets_secure_boot_sig_block_t block[SECURE_BOOT_MAX_APPENDED_SIGN_BLOCKS_TO_IMAGE]; + uint8_t _padding[4096 - (sizeof(ets_secure_boot_sig_block_t) * SECURE_BOOT_MAX_APPENDED_SIGN_BLOCKS_TO_IMAGE)]; +} ets_secure_boot_signature_t; + +_Static_assert(sizeof(ets_secure_boot_signature_t) == 4096, "invalid sig sector size"); + +typedef struct { + const void *key_digests[SECURE_BOOT_NUM_BLOCKS]; +} ets_secure_boot_key_digests_t; + +/** @brief Verifies the signature block appended to a firmware image. Implemented in the ROM. + * + * This function is used to verify the bootloader before burning its public key hash into Efuse. + * Also, it is used to verify the app on loading the image on boot and on OTA. + * + * @param sig The signature block flashed aligned 4096 bytes from the firmware. (ROM implementation expects 3 blocks, sig->block[3]). + * @param image_digest The SHA-256 Digest of the firmware to be verified + * @param trusted_key_digest The SHA-256 Digest of the public key (ets_rsa_pubkey_t) of a single signature block. + * @param verified_digest RSA-PSS signature of image_digest. Pass an uninitialised array. + * + * @return SBV2_SUCCESS if signature is valid + * SBV2_FAILED for failures. + */ +secure_boot_v2_status_t ets_secure_boot_verify_signature(const ets_secure_boot_signature_t *sig, const uint8_t *image_digest, const uint8_t *trusted_key_digest, uint8_t *verified_digest); + +/** @brief This function verifies the 1st stage bootloader. Implemented in the ROM. + * Reboots post verification. It reads the Efuse key for verification of the public key. + * + * This function is not used in the current workflow. + * + */ +void ets_secure_boot_verify_boot_bootloader(void); + +/** @brief Confirms if the secure boot V2 has been enabled. Implemented in the ROM. + * + * In ESP32-ECO3 - It checks the value of ABS_DONE_1 in EFuse. + * + * @return true if is Secure boot v2 has been enabled + * False if Secure boot v2 has not been enabled. + */ +bool ets_use_secure_boot_v2(void); + +#else +#define SECURE_BOOT_NUM_BLOCKS 0 + +#endif /* CONFIG_ESP32_REV_MIN_3 */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SECURE_BOOT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/sha.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/sha.h new file mode 100644 index 00000000..f43c19d1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/sha.h @@ -0,0 +1,65 @@ +/* + ROM functions for hardware SHA support. + + It is not recommended to use these functions directly. If using + them from esp-idf then use the esp_sha_lock_engine() and + esp_sha_lock_memory_block() functions in esp32/sha.h to ensure + exclusive access. + */ +// Copyright 2015-2016 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. +#ifndef _ROM_SHA_H_ +#define _ROM_SHA_H_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct SHAContext { + bool start; + uint32_t total_input_bits[4]; +} SHA_CTX; + +enum SHA_TYPE { + SHA1 = 0, + SHA2_256, + SHA2_384, + SHA2_512, + + + SHA_INVALID = -1, +}; + +/* Do not use these function in multi core mode due to + * inside they have no safe implementation (without DPORT workaround). +*/ +void ets_sha_init(SHA_CTX *ctx); + +void ets_sha_enable(void); + +void ets_sha_disable(void); + +void ets_sha_update(SHA_CTX *ctx, enum SHA_TYPE type, const uint8_t *input, size_t input_bits); + +void ets_sha_finish(SHA_CTX *ctx, enum SHA_TYPE type, uint8_t *output); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SHA_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/spi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/spi_flash.h new file mode 100644 index 00000000..6d162343 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/spi_flash.h @@ -0,0 +1,569 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_SPI_FLASH_H_ +#define _ROM_SPI_FLASH_H_ + +#include +#include + +#include "esp_attr.h" + +#include "sdkconfig.h" + +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/spi_reg.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup spi_flash_apis, spi flash operation related apis + * @brief spi_flash apis + */ + +/** @addtogroup spi_flash_apis + * @{ + */ + +/************************************************************* + * Note + ************************************************************* + * 1. ESP32 chip have 4 SPI slave/master, however, SPI0 is + * used as an SPI master to access Flash and ext-SRAM by + * Cache module. It will support Decryto read for Flash, + * read/write for ext-SRAM. And SPI1 is also used as an + * SPI master for Flash read/write and ext-SRAM read/write. + * It will support Encrypto write for Flash. + * 2. As an SPI master, SPI support Highest clock to 80M, + * however, Flash with 80M Clock should be configured + * for different Flash chips. If you want to use 80M + * clock We should use the SPI that is certified by + * Espressif. However, the certification is not started + * at the time, so please use 40M clock at the moment. + * 3. SPI Flash can use 2 lines or 4 lines mode. If you + * use 2 lines mode, you can save two pad SPIHD and + * SPIWP for gpio. ESP32 support configured SPI pad for + * Flash, the configuration is stored in efuse and flash. + * However, the configurations of pads should be certified + * by Espressif. If you use this function, please use 40M + * clock at the moment. + * 4. ESP32 support to use Common SPI command to configure + * Flash to QIO mode, if you failed to configure with fix + * command. With Common SPI Command, ESP32 can also provide + * a way to use same Common SPI command groups on different + * Flash chips. + * 5. This functions are not protected by packeting, Please use the + ************************************************************* + */ + +#define PERIPHS_SPI_FLASH_CMD SPI_CMD_REG(1) +#define PERIPHS_SPI_FLASH_ADDR SPI_ADDR_REG(1) +#define PERIPHS_SPI_FLASH_CTRL SPI_CTRL_REG(1) +#define PERIPHS_SPI_FLASH_CTRL1 SPI_CTRL1_REG(1) +#define PERIPHS_SPI_FLASH_STATUS SPI_RD_STATUS_REG(1) +#define PERIPHS_SPI_FLASH_USRREG SPI_USER_REG(1) +#define PERIPHS_SPI_FLASH_USRREG1 SPI_USER1_REG(1) +#define PERIPHS_SPI_FLASH_USRREG2 SPI_USER2_REG(1) +#define PERIPHS_SPI_FLASH_C0 SPI_W0_REG(1) +#define PERIPHS_SPI_FLASH_C1 SPI_W1_REG(1) +#define PERIPHS_SPI_FLASH_C2 SPI_W2_REG(1) +#define PERIPHS_SPI_FLASH_C3 SPI_W3_REG(1) +#define PERIPHS_SPI_FLASH_C4 SPI_W4_REG(1) +#define PERIPHS_SPI_FLASH_C5 SPI_W5_REG(1) +#define PERIPHS_SPI_FLASH_C6 SPI_W6_REG(1) +#define PERIPHS_SPI_FLASH_C7 SPI_W7_REG(1) +#define PERIPHS_SPI_FLASH_TX_CRC SPI_TX_CRC_REG(1) + +#define SPI0_R_QIO_DUMMY_CYCLELEN 3 +#define SPI0_R_QIO_ADDR_BITSLEN 31 +#define SPI0_R_FAST_DUMMY_CYCLELEN 7 +#define SPI0_R_DIO_DUMMY_CYCLELEN 1 +#define SPI0_R_DIO_ADDR_BITSLEN 27 +#define SPI0_R_FAST_ADDR_BITSLEN 23 +#define SPI0_R_SIO_ADDR_BITSLEN 23 + +#define SPI1_R_QIO_DUMMY_CYCLELEN 3 +#define SPI1_R_QIO_ADDR_BITSLEN 31 +#define SPI1_R_FAST_DUMMY_CYCLELEN 7 +#define SPI1_R_DIO_DUMMY_CYCLELEN 3 +#define SPI1_R_DIO_ADDR_BITSLEN 31 +#define SPI1_R_FAST_ADDR_BITSLEN 23 +#define SPI1_R_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_W_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_TWO_BYTE_STATUS_EN SPI_WRSR_2B + +//SPI address register +#define ESP_ROM_SPIFLASH_BYTES_LEN 24 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_WRITE_NUM 32 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM 64 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_BITS 0x3f + +//SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 +#define ESP_ROM_SPIFLASH_BP_MASK_ISSI (BIT7 | BIT5 | BIT4 | BIT3 | BIT2) + +//Extra dummy for flash read +#define ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_20M 0 +#define ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_26M 0 +#define ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_40M 1 +#define ESP_ROM_SPIFLASH_DUMMY_LEN_PLUS_80M 2 + +#define FLASH_ID_GD25LQ32C 0xC86016 + +typedef enum { + ESP_ROM_SPIFLASH_QIO_MODE = 0, + ESP_ROM_SPIFLASH_QOUT_MODE, + ESP_ROM_SPIFLASH_DIO_MODE, + ESP_ROM_SPIFLASH_DOUT_MODE, + ESP_ROM_SPIFLASH_FASTRD_MODE, + ESP_ROM_SPIFLASH_SLOWRD_MODE +} esp_rom_spiflash_read_mode_t; + +typedef enum { + ESP_ROM_SPIFLASH_RESULT_OK, + ESP_ROM_SPIFLASH_RESULT_ERR, + ESP_ROM_SPIFLASH_RESULT_TIMEOUT +} esp_rom_spiflash_result_t; + +typedef struct { + uint32_t device_id; + uint32_t chip_size; // chip size in bytes + uint32_t block_size; + uint32_t sector_size; + uint32_t page_size; + uint32_t status_mask; +} esp_rom_spiflash_chip_t; + +typedef struct { + uint8_t data_length; + uint8_t read_cmd0; + uint8_t read_cmd1; + uint8_t write_cmd; + uint16_t data_mask; + uint16_t data; +} esp_rom_spiflash_common_cmd_t; + +/** + * @brief Fix the bug in SPI hardware communication with Flash/Ext-SRAM in High Speed. + * Please do not call this function in SDK. + * + * @param uint8_t spi: 0 for SPI0(Cache Access), 1 for SPI1(Flash read/write). + * + * @param uint8_t freqdiv: Pll is 80M, 4 for 20M, 3 for 26.7M, 2 for 40M, 1 for 80M. + * + * @return None + */ +void esp_rom_spiflash_fix_dummylen(uint8_t spi, uint8_t freqdiv); + +/** + * @brief Select SPI Flash to QIO mode when WP pad is read from Flash. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_qiomode(uint8_t wp_gpio_num, uint32_t ishspi); + +/** + * @brief Set SPI Flash pad drivers. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t *drvs: drvs[0]-bit[3:0] for cpiclk, bit[7:4] for spiq, drvs[1]-bit[3:0] for spid, drvs[1]-bit[7:4] for spid + * drvs[2]-bit[3:0] for spihd, drvs[2]-bit[7:4] for spiwp. + * Values usually read from falsh by rom code, function usually callde by rom code. + * if value with bit(3) set, the value is valid, bit[2:0] is the real value. + * + * @return None + */ +void esp_rom_spiflash_set_drvs(uint8_t wp_gpio_num, uint32_t ishspi, uint8_t *drvs); + +/** + * @brief Select SPI Flash function for pads. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_padsfunc(uint32_t ishspi); + +/** + * @brief SPI Flash init, clock divisor is 4, use 1 line Slow read mode. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t legacy: In legacy mode, more SPI command is used in line. + * + * @return None + */ +void esp_rom_spiflash_attach(uint32_t ishspi, bool legacy); + +/** + * @brief SPI Read Flash status register. We use CMD 0x05 (RDSR). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_status(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief SPI Read Flash status register bits 8-15. We use CMD 0x35 (RDSR2). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_statushigh(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief Write status to Falsh status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t status_value : Value to . + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_status(esp_rom_spiflash_chip_t *spi, uint32_t status_value); + +/** + * @brief Use a command to Read Flash status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t*status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_user_cmd(uint32_t *status, uint8_t cmd); + +/** + * @brief Config SPI Flash read mode when init. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_read_mode_t mode : QIO/QOUT/DIO/DOUT/FastRD/SlowRD. + * + * This function does not try to set the QIO Enable bit in the status register, caller is responsible for this. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_readmode(esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Config SPI Flash clock divisor. + * Please do not call this function in SDK. + * + * @param uint8_t freqdiv: clock divisor. + * + * @param uint8_t spi: 0 for SPI0, 1 for SPI1. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_clk(uint8_t freqdiv, uint8_t spi); + +/** + * @brief Send CommonCmd to Flash so that is can go into QIO mode, some Flash use different CMD. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_common_cmd_t *cmd : A struct to show the action of a command. + * + * @return uint16_t 0 : do not send command any more. + * 1 : go to the next command. + * n > 1 : skip (n - 1) commands. + */ +uint16_t esp_rom_spiflash_common_cmd(esp_rom_spiflash_common_cmd_t *cmd); + +/** + * @brief Unlock SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Unlock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Unlock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Unlock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_unlock(void); + +/** + * @brief SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Lock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Lock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Lock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_lock(void); + +/** + * @brief Update SPI Flash parameter. + * Please do not call this function in SDK. + * + * @param uint32_t deviceId : Device ID read from SPI, the low 32 bit. + * + * @param uint32_t chip_size : The Flash size. + * + * @param uint32_t block_size : The Flash block size. + * + * @param uint32_t sector_size : The Flash sector size. + * + * @param uint32_t page_size : The Flash page size. + * + * @param uint32_t status_mask : The Mask used when read status from Flash(use single CMD). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Update OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Update error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Update timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_param(uint32_t deviceId, uint32_t chip_size, uint32_t block_size, + uint32_t sector_size, uint32_t page_size, uint32_t status_mask); + +/** + * @brief Erase whole flash chip. + * Please do not call this function in SDK. + * + * @param None + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_chip(void); + +/** + * @brief Erase a 64KB block of flash + * Uses SPI flash command D8H. + * Please do not call this function in SDK. + * + * @param uint32_t block_num : Which block to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_block(uint32_t block_num); + +/** + * @brief Erase a sector of flash. + * Uses SPI flash command 20H. + * Please do not call this function in SDK. + * + * @param uint32_t sector_num : Which sector to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_sector(uint32_t sector_num); + +/** + * @brief Erase some sectors. + * Please do not call this function in SDK. + * + * @param uint32_t start_addr : Start addr to erase, should be sector aligned. + * + * @param uint32_t area_len : Length to erase, should be sector aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_area(uint32_t start_addr, uint32_t area_len); + +/** + * @brief Write Data to Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t dest_addr : Address to write, should be 4 bytes aligned. + * + * @param const uint32_t *src : The pointer to data which is to write. + * + * @param uint32_t len : Length to write, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write(uint32_t dest_addr, const uint32_t *src, int32_t len); + +/** + * @brief Read Data from Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t src_addr : Address to read, should be 4 bytes aligned. + * + * @param uint32_t *dest : The buf to read the data. + * + * @param uint32_t len : Length to read, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read(uint32_t src_addr, uint32_t *dest, int32_t len); + +/** + * @brief SPI1 go into encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_enable(void); + +/** + * @brief Prepare 32 Bytes data to encrpto writing, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 bytes aligned. + * + * @param uint32_t *data : The pointer to data which is to write. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Prepare OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Prepare error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Prepare timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_prepare_encrypted_data(uint32_t flash_addr, uint32_t *data); + +/** + * @brief SPI1 go out of encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_disable(void); + +/** + * @brief Write data to flash with transparent encryption. + * @note Sectors to be written should already be erased. + * + * @note Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 byte aligned. + * + * @param uint32_t *data : The pointer to data to write. Note, this pointer must + * be 32 bit aligned and the content of the data will be + * modified by the encryption function. + * + * @param uint32_t len : Length to write, should be 32 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Data written successfully. + * ESP_ROM_SPIFLASH_RESULT_ERR : Encryption write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Encrypto write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_encrypted(uint32_t flash_addr, uint32_t *data, uint32_t len); + + +/** @brief Wait until SPI flash write operation is complete + * + * @note Please do not call this function in SDK. + * + * Reads the Write In Progress bit of the SPI flash status register, + * repeats until this bit is zero (indicating write complete). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write is complete + * ESP_ROM_SPIFLASH_RESULT_ERR : Error while reading status. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_wait_idle(esp_rom_spiflash_chip_t *spi); + + +/** @brief Enable Quad I/O pin functions + * + * @note Please do not call this function in SDK. + * + * Sets the HD & WP pin functions for Quad I/O modes, based on the + * efuse SPI pin configuration. + * + * @param wp_gpio_num - Number of the WP pin to reconfigure for quad I/O. + * + * @param spiconfig - Pin configuration, as returned from ets_efuse_get_spiconfig(). + * - If this parameter is 0, default SPI pins are used and wp_gpio_num parameter is ignored. + * - If this parameter is 1, default HSPI pins are used and wp_gpio_num parameter is ignored. + * - For other values, this parameter encodes the HD pin number and also the CLK pin number. CLK pin selection is used + * to determine if HSPI or SPI peripheral will be used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). + * Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral. + */ +void esp_rom_spiflash_select_qio_pins(uint8_t wp_gpio_num, uint32_t spiconfig); + +/** + * @brief Clear WEL bit unconditionally. + * + * @return always ESP_ROM_SPIFLASH_RESULT_OK + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_disable(void); + +/** @brief Global esp_rom_spiflash_chip_t structure used by ROM functions + * + */ +extern esp_rom_spiflash_chip_t g_rom_flashchip; + +extern uint8_t g_rom_spiflash_dummy_len_plus[]; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SPI_FLASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tbconsole.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tbconsole.h new file mode 100644 index 00000000..d6ca069c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tbconsole.h @@ -0,0 +1,27 @@ +// Copyright 2015-2016 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. +#ifndef _ROM_TBCONSOLE_H_ +#define _ROM_TBCONSOLE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +void start_tb_console(void); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_TBCONSOLE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tjpgd.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tjpgd.h new file mode 100644 index 00000000..3c110a13 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/tjpgd.h @@ -0,0 +1,99 @@ +/*----------------------------------------------------------------------------/ +/ TJpgDec - Tiny JPEG Decompressor include file (C)ChaN, 2012 +/----------------------------------------------------------------------------*/ +#ifndef _TJPGDEC +#define _TJPGDEC +/*---------------------------------------------------------------------------*/ +/* System Configurations */ + +#define JD_SZBUF 512 /* Size of stream input buffer */ +#define JD_FORMAT 0 /* Output pixel format 0:RGB888 (3 BYTE/pix), 1:RGB565 (1 WORD/pix) */ +#define JD_USE_SCALE 1 /* Use descaling feature for output */ +#define JD_TBLCLIP 1 /* Use table for saturation (might be a bit faster but increases 1K bytes of code size) */ + +/*---------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/* These types must be 16-bit, 32-bit or larger integer */ +typedef int INT; +typedef unsigned int UINT; + +/* These types must be 8-bit integer */ +typedef char CHAR; +typedef unsigned char UCHAR; +typedef unsigned char BYTE; + +/* These types must be 16-bit integer */ +typedef short SHORT; +typedef unsigned short USHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types must be 32-bit integer */ +typedef long LONG; +typedef unsigned long ULONG; +typedef unsigned long DWORD; + + +/* Error code */ +typedef enum { + JDR_OK = 0, /* 0: Succeeded */ + JDR_INTR, /* 1: Interrupted by output function */ + JDR_INP, /* 2: Device error or wrong termination of input stream */ + JDR_MEM1, /* 3: Insufficient memory pool for the image */ + JDR_MEM2, /* 4: Insufficient stream input buffer */ + JDR_PAR, /* 5: Parameter error */ + JDR_FMT1, /* 6: Data format error (may be damaged data) */ + JDR_FMT2, /* 7: Right format but not supported */ + JDR_FMT3 /* 8: Not supported JPEG standard */ +} JRESULT; + + + +/* Rectangular structure */ +typedef struct { + WORD left, right, top, bottom; +} JRECT; + + + +/* Decompressor object structure */ +typedef struct JDEC JDEC; +struct JDEC { + UINT dctr; /* Number of bytes available in the input buffer */ + BYTE* dptr; /* Current data read ptr */ + BYTE* inbuf; /* Bit stream input buffer */ + BYTE dmsk; /* Current bit in the current read byte */ + BYTE scale; /* Output scaling ratio */ + BYTE msx, msy; /* MCU size in unit of block (width, height) */ + BYTE qtid[3]; /* Quantization table ID of each component */ + SHORT dcv[3]; /* Previous DC element of each component */ + WORD nrst; /* Restart inverval */ + UINT width, height; /* Size of the input image (pixel) */ + BYTE* huffbits[2][2]; /* Huffman bit distribution tables [id][dcac] */ + WORD* huffcode[2][2]; /* Huffman code word tables [id][dcac] */ + BYTE* huffdata[2][2]; /* Huffman decoded data tables [id][dcac] */ + LONG* qttbl[4]; /* Dequaitizer tables [id] */ + void* workbuf; /* Working buffer for IDCT and RGB output */ + BYTE* mcubuf; /* Working buffer for the MCU */ + void* pool; /* Pointer to available memory pool */ + UINT sz_pool; /* Size of momory pool (bytes available) */ + UINT (*infunc)(JDEC*, BYTE*, UINT);/* Pointer to jpeg stream input function */ + void* device; /* Pointer to I/O device identifiler for the session */ +}; + + + +/* TJpgDec API functions */ +JRESULT jd_prepare (JDEC*, UINT(*)(JDEC*,BYTE*,UINT), void*, UINT, void*); +JRESULT jd_decomp (JDEC*, UINT(*)(JDEC*,void*,JRECT*), BYTE); + + +#ifdef __cplusplus +} +#endif + +#endif /* _TJPGDEC */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/uart.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/uart.h new file mode 100644 index 00000000..49d0e8cf --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32/rom/uart.h @@ -0,0 +1,420 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_UART_H_ +#define _ROM_UART_H_ + +#include "esp_types.h" +#include "esp_attr.h" +#include "ets_sys.h" +#include "soc/soc.h" +#include "soc/uart_periph.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + +#define RX_BUFF_SIZE 0x100 +#define TX_BUFF_SIZE 100 + +//uart int enable register ctrl bits +#define UART_RCV_INTEN BIT0 +#define UART_TRX_INTEN BIT1 +#define UART_LINE_STATUS_INTEN BIT2 + +//uart int identification ctrl bits +#define UART_INT_FLAG_MASK 0x0E + +//uart fifo ctrl bits +#define UART_CLR_RCV_FIFO BIT1 +#define UART_CLR_TRX_FIFO BIT2 +#define UART_RCVFIFO_TRG_LVL_BITS BIT6 + +//uart line control bits +#define UART_DIV_LATCH_ACCESS_BIT BIT7 + +//uart line status bits +#define UART_RCV_DATA_RDY_FLAG BIT0 +#define UART_RCV_OVER_FLOW_FLAG BIT1 +#define UART_RCV_PARITY_ERR_FLAG BIT2 +#define UART_RCV_FRAME_ERR_FLAG BIT3 +#define UART_BRK_INT_FLAG BIT4 +#define UART_TRX_FIFO_EMPTY_FLAG BIT5 +#define UART_TRX_ALL_EMPTY_FLAG BIT6 // include fifo and shift reg +#define UART_RCV_ERR_FLAG BIT7 + +//send and receive message frame head +#define FRAME_FLAG 0x7E + +typedef enum { + UART_LINE_STATUS_INT_FLAG = 0x06, + UART_RCV_FIFO_INT_FLAG = 0x04, + UART_RCV_TMOUT_INT_FLAG = 0x0C, + UART_TXBUFF_EMPTY_INT_FLAG = 0x02 +} UartIntType; //consider bit0 for int_flag + +typedef enum { + RCV_ONE_BYTE = 0x0, + RCV_FOUR_BYTE = 0x1, + RCV_EIGHT_BYTE = 0x2, + RCV_FOURTEEN_BYTE = 0x3 +} UartRcvFifoTrgLvl; + +typedef enum { + FIVE_BITS = 0x0, + SIX_BITS = 0x1, + SEVEN_BITS = 0x2, + EIGHT_BITS = 0x3 +} UartBitsNum4Char; + +typedef enum { + ONE_STOP_BIT = 1, + ONE_HALF_STOP_BIT = 2, + TWO_STOP_BIT = 3 +} UartStopBitsNum; + +typedef enum { + NONE_BITS = 0, + ODD_BITS = 2, + EVEN_BITS = 3 + +} UartParityMode; + +typedef enum { + STICK_PARITY_DIS = 0, + STICK_PARITY_EN = 2 +} UartExistParity; + +typedef enum { + BIT_RATE_9600 = 9600, + BIT_RATE_19200 = 19200, + BIT_RATE_38400 = 38400, + BIT_RATE_57600 = 57600, + BIT_RATE_115200 = 115200, + BIT_RATE_230400 = 230400, + BIT_RATE_460800 = 460800, + BIT_RATE_921600 = 921600 +} UartBautRate; + +typedef enum { + NONE_CTRL, + HARDWARE_CTRL, + XON_XOFF_CTRL +} UartFlowCtrl; + +typedef enum { + EMPTY, + UNDER_WRITE, + WRITE_OVER +} RcvMsgBuffState; + +typedef struct { + uint8_t *pRcvMsgBuff; + uint8_t *pWritePos; + uint8_t *pReadPos; + uint8_t TrigLvl; + RcvMsgBuffState BuffState; +} RcvMsgBuff; + +typedef struct { + uint32_t TrxBuffSize; + uint8_t *pTrxBuff; +} TrxMsgBuff; + +typedef enum { + BAUD_RATE_DET, + WAIT_SYNC_FRM, + SRCH_MSG_HEAD, + RCV_MSG_BODY, + RCV_ESC_CHAR, +} RcvMsgState; + +typedef struct { + UartBautRate baut_rate; + UartBitsNum4Char data_bits; + UartExistParity exist_parity; + UartParityMode parity; // chip size in byte + UartStopBitsNum stop_bits; + UartFlowCtrl flow_ctrl; + uint8_t buff_uart_no; //indicate which uart use tx/rx buffer + uint8_t tx_uart_no; + RcvMsgBuff rcv_buff; +// TrxMsgBuff trx_buff; + RcvMsgState rcv_state; + int received; +} UartDevice; + +/** + * @brief Init uart device struct value and reset uart0/uart1 rx. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void uartAttach(void); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, else for UART1. + * + * @param uint32_t clock : clock used by uart module, to adjust baudrate. + * + * @return None + */ +void Uart_Init(uint8_t uart_no, uint32_t clock); + +/** + * @brief Modify uart baudrate. + * This function will reset RX/TX fifo for uart. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint32_t DivLatchValue : (clock << 4)/baudrate. + * + * @return None + */ +void uart_div_modify(uint8_t uart_no, uint32_t DivLatchValue); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint8_t is_sync : 0, only one UART module, easy to detect, wait until detected; + * 1, two UART modules, hard to detect, detect and return. + * + * @return None + */ +int uart_baudrate_detect(uint8_t uart_no, uint8_t is_sync); + +/** + * @brief Switch printf channel of uart_tx_one_char. + * Please do not call this function when printf. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_tx_switch(uint8_t uart_no); + +/** + * @brief Switch message exchange channel for UART download booting. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_buff_switch(uint8_t uart_no); + +/** + * @brief Output a char to printf channel, wait until fifo not full. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char(uint8_t TxChar); + +/** + * @brief Output a char to message exchange channel, wait until fifo not full. + * Please do not call this function in SDK. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char2(uint8_t TxChar); + +/** + * @brief Wait until uart tx full empty. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None. + */ +void uart_tx_flush(uint8_t uart_no); + +/** + * @brief Wait until uart tx full empty and the last char send ok. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2 + * + * The function defined in ROM code has a bug, so we define the correct version + * here for compatibility. + */ +static inline void IRAM_ATTR uart_tx_wait_idle(uint8_t uart_no) { + uint32_t status; + do { + status = READ_PERI_REG(UART_STATUS_REG(uart_no)); + /* either tx count or state is non-zero */ + } while ((status & (UART_ST_UTX_OUT_M | UART_TXFIFO_CNT_M)) != 0); +} + +/** + * @brief Get an input char from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pRxChar : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_one_char(uint8_t *pRxChar); + +/** + * @brief Get an input char from message channel, wait until successful. + * Please do not call this function in SDK. + * + * @param None + * + * @return char : input char value. + */ +char uart_rx_one_char_block(void); + +/** + * @brief Get an input string line from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pString : the pointer to store the string. + * + * @param uint8_t MaxStrlen : the max string length, include '\0'. + * + * @return OK. + */ +STATUS UartRxString(uint8_t *pString, uint8_t MaxStrlen); + +/** + * @brief Process uart received information in the interrupt handler. + * Please do not call this function in SDK. + * + * @param void *para : the message receive buffer. + * + * @return None + */ +void uart_rx_intr_handler(void *para); + +/** + * @brief Get an char from receive buffer. + * Please do not call this function in SDK. + * + * @param RcvMsgBuff *pRxBuff : the pointer to the struct that include receive buffer. + * + * @param uint8_t *pRxByte : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_readbuff( RcvMsgBuff *pRxBuff, uint8_t *pRxByte); + +/** + * @brief Get all chars from receive buffer. + * Please do not call this function in SDK. + * + * @param uint8_t *pCmdLn : the pointer to store the string. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS UartGetCmdLn(uint8_t *pCmdLn); + +/** + * @brief Get uart configuration struct. + * Please do not call this function in SDK. + * + * @param None + * + * @return UartDevice * : uart configuration struct pointer. + */ +UartDevice *GetUartDevice(void); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to output string. + * + * @param int len : the string length. + * + * @return None. + */ +void send_packet(uint8_t *p, int len); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to input string. + * + * @param int len : If string length > len, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return int : the length of the string. + */ +int recv_packet(uint8_t *p, int len, uint8_t is_sync); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t DataLen : the string length. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS SendMsg(uint8_t *pData, uint16_t DataLen); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t MaxDataLen : If string length > MaxDataLen, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS RcvMsg(uint8_t *pData, uint16_t MaxDataLen, uint8_t is_sync); + +extern UartDevice UartDev; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_UART_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/aes.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/aes.h new file mode 100644 index 00000000..d8002ef5 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/aes.h @@ -0,0 +1,58 @@ +// Copyright 2020 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. + +#ifndef _ROM_AES_H_ +#define _ROM_AES_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AES_BLOCK_SIZE 16 + +enum AES_TYPE { + AES_ENC, + AES_DEC, +}; + +enum AES_BITS { + AES128, + AES192, + AES256 +}; + +void ets_aes_enable(void); + +void ets_aes_disable(void); + +void ets_aes_set_endian(bool key_word_swap, bool key_byte_swap, + bool in_word_swap, bool in_byte_swap, + bool out_word_swap, bool out_byte_swap); + +int ets_aes_setkey(enum AES_TYPE type, const void *key, enum AES_BITS bits); + +int ets_aes_setkey_enc(const void *key, enum AES_BITS bits); + +int ets_aes_setkey_dec(const void *key, enum AES_BITS bits); + +void ets_aes_block(const void *input, void *output); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_AES_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/apb_backup_dma.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/apb_backup_dma.h new file mode 100644 index 00000000..d4e709b7 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/apb_backup_dma.h @@ -0,0 +1,25 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +void ets_apb_backup_init_lock_func(void(* _apb_backup_lock)(void), void(* _apb_backup_unlock)(void)); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/bigint.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/bigint.h new file mode 100644 index 00000000..b63172ea --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/bigint.h @@ -0,0 +1,43 @@ +// Copyright 2020 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. + +#ifndef _ROM_BIGINT_H_ +#define _ROM_BIGINT_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void ets_bigint_enable(void); + +void ets_bigint_disable(void); + +int ets_bigint_multiply(const uint32_t *x, const uint32_t *y, uint32_t len_words); + +int ets_bigint_modmult(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, uint32_t len_words); + +int ets_bigint_modexp(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, bool constant_time, uint32_t len_words); + +void ets_bigint_wait_finish(void); + +int ets_bigint_getz(uint32_t *z, uint32_t len_words); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_BIGINT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/cache.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/cache.h new file mode 100644 index 00000000..487143e6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/cache.h @@ -0,0 +1,796 @@ +// Copyright 2020 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. + +#ifndef _ROM_CACHE_H_ +#define _ROM_CACHE_H_ + +#include +#include "esp_bit_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup cache_apis, cache operation related apis + * @brief cache apis + */ + +/** @addtogroup cache_apis + * @{ + */ +#define MIN_ICACHE_SIZE 16384 +#define MAX_ICACHE_SIZE 16384 +#define MIN_ICACHE_WAYS 8 +#define MAX_ICACHE_WAYS 8 +#define MAX_CACHE_WAYS 8 +#define MIN_CACHE_LINE_SIZE 32 +#define TAG_SIZE 4 +#define MIN_ICACHE_BANK_NUM 1 +#define MAX_ICACHE_BANK_NUM 1 +#define CACHE_MEMORY_BANK_NUM 1 +#define CACHE_MEMORY_IBANK_SIZE 0x4000 + +#define MAX_ITAG_BANK_ITEMS (MAX_ICACHE_SIZE / MAX_ICACHE_BANK_NUM / MIN_CACHE_LINE_SIZE) +#define MAX_ITAG_BLOCK_ITEMS (MAX_ICACHE_SIZE / MAX_ICACHE_BANK_NUM / MAX_ICACHE_WAYS / MIN_CACHE_LINE_SIZE) +#define MAX_ITAG_BANK_SIZE (MAX_ITAG_BANK_ITEMS * TAG_SIZE) +#define MAX_ITAG_BLOCK_SIZE (MAX_ITAG_BLOCK_ITEMS * TAG_SIZE) + +typedef enum { + CACHE_DCACHE = 0, + CACHE_ICACHE0 = 1, + CACHE_ICACHE1 = 2, +} cache_t; + +typedef enum { + CACHE_MEMORY_INVALID = 0, + CACHE_MEMORY_IBANK0 = BIT(0), + CACHE_MEMORY_IBANK1 = BIT(1), + CACHE_MEMORY_IBANK2 = BIT(2), + CACHE_MEMORY_IBANK3 = BIT(3), + CACHE_MEMORY_DBANK0 = BIT(0), + CACHE_MEMORY_DBANK1 = BIT(1), + CACHE_MEMORY_DBANK2 = BIT(2), + CACHE_MEMORY_DBANK3 = BIT(3), +} cache_array_t; + +#define ICACHE_SIZE_16KB CACHE_SIZE_HALF +#define ICACHE_SIZE_32KB CACHE_SIZE_FULL +#define DCACHE_SIZE_32KB CACHE_SIZE_HALF +#define DCACHE_SIZE_64KB CACHE_SIZE_FULL + +typedef enum { + CACHE_SIZE_HALF = 0, /*!< 8KB for icache and dcache */ + CACHE_SIZE_FULL = 1, /*!< 16KB for icache and dcache */ +} cache_size_t; + +typedef enum { + CACHE_4WAYS_ASSOC = 0, /*!< 4 way associated cache */ + CACHE_8WAYS_ASSOC = 1, /*!< 8 way associated cache */ +} cache_ways_t; + +typedef enum { + CACHE_LINE_SIZE_16B = 0, /*!< 16 Byte cache line size */ + CACHE_LINE_SIZE_32B = 1, /*!< 32 Byte cache line size */ + CACHE_LINE_SIZE_64B = 2, /*!< 64 Byte cache line size */ +} cache_line_size_t; + +typedef enum { + CACHE_AUTOLOAD_POSITIVE = 0, /*!< cache autoload step is positive */ + CACHE_AUTOLOAD_NEGATIVE = 1, /*!< cache autoload step is negative */ +} cache_autoload_order_t; + +#define CACHE_AUTOLOAD_STEP(i) ((i) - 1) + +typedef enum { + CACHE_AUTOLOAD_MISS_TRIGGER = 0, /*!< autoload only triggered by cache miss */ + CACHE_AUTOLOAD_HIT_TRIGGER = 1, /*!< autoload only triggered by cache hit */ + CACHE_AUTOLOAD_BOTH_TRIGGER = 2, /*!< autoload triggered both by cache miss and hit */ +} cache_autoload_trigger_t; + +typedef enum { + CACHE_FREEZE_ACK_BUSY = 0, /*!< in this mode, cache ack busy to CPU if a cache miss happens*/ + CACHE_FREEZE_ACK_ERROR = 1, /*!< in this mode, cache ack wrong data to CPU and trigger an error if a cache miss happens */ +} cache_freeze_mode_t; + +struct cache_mode { + uint32_t cache_size; /*!< cache size in byte */ + uint16_t cache_line_size; /*!< cache line size in byte */ + uint8_t cache_ways; /*!< cache ways, always 4 */ + uint8_t ibus; /*!< the cache index, 0 for dcache, 1 for icache */ +}; + +struct icache_tag_item { + uint32_t valid:1; /*!< the tag item is valid or not */ + uint32_t lock:1; /*!< the cache line is locked or not */ + uint32_t fifo_cnt:3; /*!< fifo cnt, 0 ~ 3 for 4 ways cache */ + uint32_t tag:13; /*!< the tag is the high part of the cache address, however is only 16MB (8MB Ibus + 8MB Dbus) range, and without low part */ + uint32_t reserved:14; +}; + +struct autoload_config { + uint8_t order; /*!< autoload step is positive or negative */ + uint8_t trigger; /*!< autoload trigger */ + uint8_t ena0; /*!< autoload region0 enable */ + uint8_t ena1; /*!< autoload region1 enable */ + uint32_t addr0; /*!< autoload region0 start address */ + uint32_t size0; /*!< autoload region0 size */ + uint32_t addr1; /*!< autoload region1 start address */ + uint32_t size1; /*!< autoload region1 size */ +}; + +struct tag_group_info { + struct cache_mode mode; /*!< cache and cache mode */ + uint32_t filter_addr; /*!< the address that used to generate the struct */ + uint32_t vaddr_offset; /*!< virtual address offset of the cache ways */ + uint32_t tag_addr[MAX_CACHE_WAYS]; /*!< tag memory address, only [0~mode.ways-1] is valid to use */ + uint32_t cache_memory_offset[MAX_CACHE_WAYS]; /*!< cache memory address, only [0~mode.ways-1] is valid to use */ +}; + +struct lock_config { + uint32_t addr; /*!< manual lock address*/ + uint16_t size; /*!< manual lock size*/ + uint16_t group; /*!< manual lock group, 0 or 1*/ +}; + +struct cache_internal_stub_table { + uint32_t (* icache_line_size)(void); + uint32_t (* icache_addr)(uint32_t addr); + uint32_t (* dcache_addr)(uint32_t addr); + void (* invalidate_icache_items)(uint32_t addr, uint32_t items); + void (* lock_icache_items)(uint32_t addr, uint32_t items); + void (* unlock_icache_items)(uint32_t addr, uint32_t items); + uint32_t (* suspend_icache_autoload)(void); + void (* resume_icache_autoload)(uint32_t autoload); + void (* freeze_icache_enable)(cache_freeze_mode_t mode); + void (* freeze_icache_disable)(void); + int (* op_addr)(uint32_t start_addr, uint32_t size, uint32_t cache_line_size, uint32_t max_sync_num, void(* cache_Iop)(uint32_t, uint32_t)); +}; + +/* Defined in the interface file, default value is rom_default_cache_internal_table */ +extern const struct cache_internal_stub_table* rom_cache_internal_table_ptr; + +typedef void (* cache_op_start)(void); +typedef void (* cache_op_end)(void); + +typedef struct { + cache_op_start start; + cache_op_end end; +} cache_op_cb_t; + +/* Defined in the interface file, default value is NULL */ +extern const cache_op_cb_t* rom_cache_op_cb; + +#define ESP_ROM_ERR_INVALID_ARG 1 +#define MMU_SET_ADDR_ALIGNED_ERROR 2 +#define MMU_SET_PASE_SIZE_ERROR 3 +#define MMU_SET_VADDR_OUT_RANGE 4 + +#define CACHE_OP_ICACHE_Y 1 +#define CACHE_OP_ICACHE_N 0 + +/** + * @brief Initialise cache mmu, mark all entries as invalid. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_MMU_Init(void); + +/** + * @brief Set ICache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_INVALID for invalid. In + * esp32c3, external memory is always flash + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be Iram0,Iram1,Irom0,Drom0 and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of ICache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + * + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Ibus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Set DCache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_INVALID for invalid. In + * esp32c3, external memory is always flash + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be DRam0, DRam1, DRom0, DPort and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of DCache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Dbus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Count the pages in the bus room address which map to Flash. + * Please do not call this function in your SDK application. + * + * @param uint32_t bus : the bus to count with. + * + * @param uint32_t * page0_mapped : value should be initial by user, 0 for not mapped, other for mapped count. + * + * return uint32_t : the number of pages which map to Flash. + */ +uint32_t Cache_Count_Flash_Pages(uint32_t bus, uint32_t * page0_mapped); + +/** + * @brief allocate memory to used by ICache. + * Please do not call this function in your SDK application. + * + * @param cache_array_t icache_low : the data array bank used by icache low part. Due to timing constraint, can only be CACHE_MEMORY_INVALID, CACHE_MEMORY_IBANK0 + * + * return none + */ +void Cache_Occupy_ICache_MEMORY(cache_array_t icache_low); + +/** + * @brief Get cache mode of ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the pointer of cache mode struct, caller should set the icache field + * + * return none + */ +void Cache_Get_Mode(struct cache_mode * mode); + +/** + * @brief set ICache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_HALF and CACHE_SIZE_FULL + * + * @param cache_ways_t ways : the associate ways of cache, can be CACHE_4WAYS_ASSOC and CACHE_8WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B and CACHE_LINE_SIZE_64B + * + * return none + */ +void Cache_Set_ICache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief set DCache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_8KB and CACHE_SIZE_16KB + * + * @param cache_ways_t ways : the associate ways of cache, can be CACHE_4WAYS_ASSOC and CACHE_8WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B and CACHE_LINE_SIZE_64B + * + * return none + */ +void Cache_Set_DCache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief check if the address is accessed through ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through ICache, 0 if not. + */ +uint32_t Cache_Address_Through_ICache(uint32_t addr); + +/** + * @brief check if the address is accessed through DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through DCache, 0 if not. + */ +uint32_t Cache_Address_Through_DCache(uint32_t addr); + +/** + * @brief Init mmu owner register to make i/d cache use half mmu entries. + * + * @param None + * + * @return None + */ +void Cache_Owner_Init(void); + +/** + * @brief Invalidate the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to invalidate + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Invalidate_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Invalidate the Cache items in the region from ICache or DCache. + * If the region is not in Cache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : invalidated region start address. + * + * @param uint32_t size : invalidated region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Invalidate_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Invalidate all cache items in ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Invalidate_ICache_All(void); + +/** + * @brief Mask all buses through ICache and DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Mask_All(void); + +/** + * @brief Suspend ICache auto preload operation, then you can resume it after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache not auto preload before suspend. + */ +uint32_t Cache_Suspend_ICache_Autoload(void); + +/** + * @brief Resume ICache auto preload operation after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before suspend. + * + * @return None. + */ +void Cache_Resume_ICache_Autoload(uint32_t autoload); + +/** + * @brief Start an ICache manual preload, will suspend auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of the preload region. + * + * @param uint32_t size : size of the preload region, should not exceed the size of ICache. + * + * @param uint32_t order : the preload order, 0 for positive, other for negative + * + * @return uint32_t : 0 for ICache not auto preload before manual preload. + */ +uint32_t Cache_Start_ICache_Preload(uint32_t addr, uint32_t size, uint32_t order); + +/** + * @brief Return if the ICache manual preload done. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache manual preload not done. + */ +uint32_t Cache_ICache_Preload_Done(void); + +/** + * @brief End the ICache manual preload to resume auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before manual preload. + * + * @return None + */ +void Cache_End_ICache_Preload(uint32_t autoload); + +/** + * @brief Config autoload parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct autoload_config * config : autoload parameters. + * + * @return None + */ +void Cache_Config_ICache_Autoload(const struct autoload_config * config); + +/** + * @brief Enable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Enable_ICache_Autoload(void); + +/** + * @brief Disable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Disable_ICache_Autoload(void); + +/** + * @brief Config a group of prelock parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct lock_config * config : a group of lock parameters. + * + * @return None + */ + +void Cache_Enable_ICache_PreLock(const struct lock_config *config); + +/** + * @brief Disable a group of prelock parameters for ICache. + * However, the locked data will not be released. + * Please do not call this function in your SDK application. + * + * @param uint16_t group : 0 for group0, 1 for group1. + * + * @return None + */ +void Cache_Disable_ICache_PreLock(uint16_t group); + +/** + * @brief Lock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to lock + * + * @param uint32_t items: cache lines to lock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Lock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Unlock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to unlock + * + * @param uint32_t items: cache lines to unlock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Unlock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Lock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of lock region. + * + * @param uint32_t size : size of lock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Lock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Unlock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of unlock region. + * + * @param uint32_t size : size of unlock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Unlock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Disable ICache access for the cpu. + * This operation will make all ICache tag memory invalid, CPU can't access ICache, ICache will keep idle. + * Please do not call this function in your SDK application. + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Disable_ICache(void); + +/** + * @brief Enable ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Enable_ICache(uint32_t autoload); + +/** + * @brief Suspend ICache access for the cpu. + * The ICache tag memory is still there, CPU can't access ICache, ICache will keep idle. + * Please do not change MMU, cache mode or tag memory(tag memory can be changed in some special case). + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Suspend_ICache(void); + +/** + * @brief Resume ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Resume_ICache(uint32_t autoload); + +/** + * @brief Get ICache cache line size + * + * @param None + * + * @return uint32_t: 16, 32, 64 Byte + */ +uint32_t Cache_Get_ICache_Line_Size(void); + +/** + * @brief Set default mode from boot, 8KB ICache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Set_Default_Mode(void); + +/** + * @brief Set default mode from boot, 8KB ICache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Enable_Defalut_ICache_Mode(void); + +/** + * @brief Enable freeze for ICache. + * Any miss request will be rejected, including cpu miss and preload/autoload miss. + * Please do not call this function in your SDK application. + * + * @param cache_freeze_mode_t mode : 0 for assert busy 1 for assert hit + * + * @return None + */ +void Cache_Freeze_ICache_Enable(cache_freeze_mode_t mode); + +/** + * @brief Disable freeze for ICache. + * Please do not call this function in your SDK application. + * + * @return None + */ +void Cache_Freeze_ICache_Disable(void); + +/** + * @brief Travel tag memory to run a call back function. + * ICache and DCache are suspend when doing this. + * The callback will get the parameter tag_group_info, which will include a group of tag memory addresses and cache memory addresses. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to check and the cache mode. + * + * @param uint32_t filter_addr : only the cache lines which may include the filter_address will be returned to the call back function. + * 0 for do not filter, all cache lines will be returned. + * + * @param void (* process)(struct tag_group_info *) : call back function, which may be called many times, a group(the addresses in the group are in the same position in the cache ways) a time. + * + * @return None + */ +void Cache_Travel_Tag_Memory(struct cache_mode * mode, uint32_t filter_addr, void (* process)(struct tag_group_info *)); + +/** + * @brief Get the virtual address from cache mode, cache tag and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t tag : the tag part fo a tag item, 12-14 bits. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Virtual_Addr(struct cache_mode *mode, uint32_t tag, uint32_t vaddr_offset); + +/** + * @brief Get cache memory block base address. + * Please do not call this function in your SDK application. + * + * @param uint32_t icache : 0 for dcache, other for icache. + * + * @param uint32_t bank_no : 0 ~ 3 bank. + * + * @return uint32_t : the cache memory block base address, 0 if the block not used. + */ +uint32_t Cache_Get_Memory_BaseAddr(uint32_t icache, uint32_t bank_no); + +/** + * @brief Get the cache memory address from cache mode, cache memory offset and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t cache_memory_offset : the cache memory offset of the whole cache (ICache or DCache) for the cache line. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Memory_Addr(struct cache_mode *mode, uint32_t cache_memory_offset, uint32_t vaddr_offset); + +/** + * @brief Get the cache memory value by DRAM address. + * Please do not call this function in your SDK application. + * + * @param uint32_t cache_memory_addr : DRAM address for the cache memory, should be 4 byte aligned for IBus address. + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_Memory_value(uint32_t cache_memory_addr); +/** + * @} + */ + +/** + * @brief Get the cache MMU IROM end address. + * Please do not call this function in your SDK application. + * + * @param void + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_IROM_MMU_End(void); + +/** + * @brief Get the cache MMU DROM end address. + * Please do not call this function in your SDK application. + * + * @param void + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_DROM_MMU_End(void); + +/** + * @brief Lock the permission control section configuration. After lock, any + * configuration modification will be bypass. Digital reset will clear the lock! + * Please do not call this function in your SDK application. + * + * @param int ibus : 1 for lock ibus pms, 0 for lock dbus pms + * + * @return None + */ +void Cache_Pms_Lock(int ibus); + +/** + * @brief Set three ibus pms boundary address, which will determine pms reject section and section 1/2. + * Please do not call this function in your SDK application. + * + * @param uint32_t ibus_boundary0_addr : vaddress for split line0 + * + * @param uint32_t ibus_boundary1_addr : vaddress for split line1 + * + * @param uint32_t ibus_boundary2_addr : vaddress for split line2 + * + * @return int : ESP_ROM_ERR_INVALID_ARG for invalid address, 0 for success + */ +int Cache_Ibus_Pms_Set_Addr(uint32_t ibus_boundary0_addr, uint32_t ibus_boundary1_addr, uint32_t ibus_boundary2_addr); + +/** + * @brief Set three ibus pms attribute, which will determine pms in different section and world. + * Please do not call this function in your SDK application. + * + * @param uint32_t ibus_pms_sct2_attr : attr for section2 + * + * @param uint32_t ibus_pms_sct1_attr : attr for section1 + * + * @return None + */ +void Cache_Ibus_Pms_Set_Attr(uint32_t ibus_pms_sct2_attr, uint32_t ibus_pms_sct1_attr); + +/** + * @brief Set three dbus pms boundary address, which will determine pms reject section and section 1/2. + * Please do not call this function in your SDK application. + * + * @param uint32_t dbus_boundary0_addr : vaddress for split line0 + * + * @param uint32_t dbus_boundary1_addr : vaddress for split line1 + * + * @param uint32_t dbus_boundary2_addr : vaddress for split line2 + * + * @return int : ESP_ROM_ERR_INVALID_ARG for invalid address, 0 for success + */ +int Cache_Dbus_Pms_Set_Addr(uint32_t dbus_boundary0_addr, uint32_t dbus_boundary1_addr, uint32_t dbus_boundary2_addr); + +/** + * @brief Set three dbus pms attribute, which will determine pms in different section and world. + * Please do not call this function in your SDK application. + * + * @param uint32_t dbus_pms_sct2_attr : attr for section2 + * + * @param uint32_t dbus_pms_sct1_attr : attr for section1 + * + * @return None + */ +void Cache_Dbus_Pms_Set_Attr(uint32_t dbus_pms_sct2_attr, uint32_t dbus_pms_sct1_attr); + +/** + * @brief Used by SPI flash mmap + * + */ +uint32_t flash_instr_rodata_start_page(uint32_t bus); +uint32_t flash_instr_rodata_end_page(uint32_t bus); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_CACHE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/crc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/crc.h new file mode 100644 index 00000000..e683f4fd --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/crc.h @@ -0,0 +1,127 @@ +// Copyright 2020 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. + +#ifndef ROM_CRC_H +#define ROM_CRC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup crc_apis, uart configuration and communication related apis + * @brief crc apis + */ + +/** @addtogroup crc_apis + * @{ + */ + + +/* Standard CRC8/16/32 algorithms. */ +// CRC-8 x8+x2+x1+1 0x07 +// CRC16-CCITT x16+x12+x5+1 1021 ISO HDLC, ITU X.25, V.34/V.41/V.42, PPP-FCS +// CRC32: +//G(x) = x32 +x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x1 + 1 +//If your buf is not continuous, you can use the first result to be the second parameter. + +/** + * @brief Crc32 value that is in little endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc32 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_be(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc16 value that is in little endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc16 value that is in big endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_be(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc8 value that is in little endian. + * + * @param uint8_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc8 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_be(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/digital_signature.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/digital_signature.h new file mode 100644 index 00000000..54c01681 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/digital_signature.h @@ -0,0 +1,150 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define ETS_DS_MAX_BITS 3072 + +#define ETS_DS_IV_LEN 16 + +/* Length of parameter 'C' stored in flash (not including IV) + + Comprises encrypted Y, M, rinv, md (32), mprime (4), length (4), padding (8) + + Note that if ETS_DS_MAX_BITS<4096, 'C' needs to be split up when writing to hardware +*/ +#define ETS_DS_C_LEN ((ETS_DS_MAX_BITS * 3 / 8) + 32 + 8 + 8) + +/* Encrypted ETS data. Recommended to store in flash in this format. + */ +typedef struct { + /* RSA LENGTH register parameters + * (number of words in RSA key & operands, minus one). + * + * + * This value must match the length field encrypted and stored in 'c', + * or invalid results will be returned. (The DS peripheral will + * always use the value in 'c', not this value, so an attacker can't + * alter the DS peripheral results this way, it will just truncate or + * extend the message and the resulting signature in software.) + */ + unsigned rsa_length; + + /* IV value used to encrypt 'c' */ + uint8_t iv[ETS_DS_IV_LEN]; + + /* Encrypted Digital Signature parameters. Result of AES-CBC encryption + of plaintext values. Includes an encrypted message digest. + */ + uint8_t c[ETS_DS_C_LEN]; +} ets_ds_data_t; + +typedef enum { + ETS_DS_OK, + ETS_DS_INVALID_PARAM, /* Supplied parameters are invalid */ + ETS_DS_INVALID_KEY, /* HMAC peripheral failed to supply key */ + ETS_DS_INVALID_PADDING, /* 'c' decrypted with invalid padding */ + ETS_DS_INVALID_DIGEST, /* 'c' decrypted with invalid digest */ +} ets_ds_result_t; + +void ets_ds_enable(void); + +void ets_ds_disable(void); + + +/* + * @brief Start signing a message (or padded message digest) using the Digital Signature peripheral + * + * - @param message Pointer to message (or padded digest) containing the message to sign. Should be + * (data->rsa_length + 1)*4 bytes long. @param data Pointer to DS data. Can be a pointer to data + * in flash. + * + * Caller must have already called ets_ds_enable() and ets_hmac_calculate_downstream() before calling + * this function, and is responsible for calling ets_ds_finish_sign() and then + * ets_hmac_invalidate_downstream() afterwards. + * + * @return ETS_DS_OK if signature is in progress, ETS_DS_INVALID_PARAM if param is invalid, + * EST_DS_INVALID_KEY if key or HMAC peripheral is configured incorrectly. + */ +ets_ds_result_t ets_ds_start_sign(const void *message, const ets_ds_data_t *data); + + +/* + * @brief Returns true if the DS peripheral is busy following a call to ets_ds_start_sign() + * + * A result of false indicates that a call to ets_ds_finish_sign() will not block. + * + * Only valid if ets_ds_enable() has been called. + */ +bool ets_ds_is_busy(void); + + +/* @brief Finish signing a message using the Digital Signature peripheral + * + * Must be called after ets_ds_start_sign(). Can use ets_ds_busy() to wait until + * peripheral is no longer busy. + * + * - @param signature Pointer to buffer to contain the signature. Should be + * (data->rsa_length + 1)*4 bytes long. + * - @param data Should match the 'data' parameter passed to ets_ds_start_sign() + * + * @param ETS_DS_OK if signing succeeded, ETS_DS_INVALID_PARAM if param is invalid, + * ETS_DS_INVALID_DIGEST or ETS_DS_INVALID_PADDING if there is a problem with the + * encrypted data digest or padding bytes (in case of ETS_DS_INVALID_PADDING, a + * digest is produced anyhow.) + */ +ets_ds_result_t ets_ds_finish_sign(void *signature, const ets_ds_data_t *data); + + +/* Plaintext parameters used by Digital Signature. + + Not used for signing with DS peripheral, but can be encrypted + in-device by calling ets_ds_encrypt_params() +*/ +typedef struct { + uint32_t Y[ETS_DS_MAX_BITS / 32]; + uint32_t M[ETS_DS_MAX_BITS / 32]; + uint32_t Rb[ETS_DS_MAX_BITS / 32]; + uint32_t M_prime; + uint32_t length; +} ets_ds_p_data_t; + +typedef enum { + ETS_DS_KEY_HMAC, /* The HMAC key (as stored in efuse) */ + ETS_DS_KEY_AES, /* The AES key (as derived from HMAC key by HMAC peripheral in downstream mode) */ +} ets_ds_key_t; + +/* @brief Encrypt DS parameters suitable for storing and later use with DS peripheral + * + * @param data Output buffer to store encrypted data, suitable for later use generating signatures. + * @param iv Pointer to 16 byte IV buffer, will be copied into 'data'. Should be randomly generated bytes each time. + * @param p_data Pointer to input plaintext key data. The expectation is this data will be deleted after this process is done and 'data' is stored. + * @param key Pointer to 32 bytes of key data. Type determined by key_type parameter. The expectation is the corresponding HMAC key will be stored to efuse and then permanently erased. + * @param key_type Type of key stored in 'key' (either the AES-256 DS key, or an HMAC DS key from which the AES DS key is derived using HMAC peripheral) + * + * @return ETS_DS_INVALID_PARAM if any parameter is invalid, or ETS_DS_OK if 'data' is successfully generated from the input parameters. + */ +ets_ds_result_t ets_ds_encrypt_params(ets_ds_data_t *data, const void *iv, const ets_ds_p_data_t *p_data, const void *key, ets_ds_key_t key_type); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/efuse.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/efuse.h new file mode 100644 index 00000000..9da1525f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/efuse.h @@ -0,0 +1,392 @@ +// Copyright 2020 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. + +#ifndef _ROM_EFUSE_H_ +#define _ROM_EFUSE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +/** \defgroup efuse_APIs efuse APIs + * @brief ESP32 efuse read/write APIs + * @attention + * + */ + +/** @addtogroup efuse_APIs + * @{ + */ + +typedef enum { + ETS_EFUSE_KEY_PURPOSE_USER = 0, + ETS_EFUSE_KEY_PURPOSE_RESERVED = 1, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY = 4, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL = 5, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG = 6, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE = 7, + ETS_EFUSE_KEY_PURPOSE_HMAC_UP = 8, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0 = 9, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1 = 10, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2 = 11, + ETS_EFUSE_KEY_PURPOSE_MAX, +} ets_efuse_purpose_t; + +typedef enum { + ETS_EFUSE_BLOCK0 = 0, + ETS_EFUSE_MAC_SPI_SYS_0 = 1, + ETS_EFUSE_BLOCK_SYS_DATA = 2, + ETS_EFUSE_BLOCK_USR_DATA = 3, + ETS_EFUSE_BLOCK_KEY0 = 4, + ETS_EFUSE_BLOCK_KEY1 = 5, + ETS_EFUSE_BLOCK_KEY2 = 6, + ETS_EFUSE_BLOCK_KEY3 = 7, + ETS_EFUSE_BLOCK_KEY4 = 8, + ETS_EFUSE_BLOCK_KEY5 = 9, + ETS_EFUSE_BLOCK_KEY6 = 10, + ETS_EFUSE_BLOCK_MAX, +} ets_efuse_block_t; + +/** + * @brief set timing accroding the apb clock, so no read error or write error happens. + * + * @param clock: apb clock in HZ, only accept 5M(in FPGA), 10M(in FPGA), 20M, 40M, 80M. + * + * @return : 0 if success, others if clock not accepted + */ +int ets_efuse_set_timing(uint32_t clock); + +/** + * @brief Enable efuse subsystem. Called after reset. Doesn't need to be called again. + */ +void ets_efuse_start(void); + +/** + * @brief Efuse read operation: copies data from physical efuses to efuse read registers. + * + * @param null + * + * @return : 0 if success, others if apb clock is not accepted + */ +int ets_efuse_read(void); + +/** + * @brief Efuse write operation: Copies data from efuse write registers to efuse. Operates on a single block of efuses at a time. + * + * @note This function does not update read efuses, call ets_efuse_read() once all programming is complete. + * + * @return : 0 if success, others if apb clock is not accepted + */ +int ets_efuse_program(ets_efuse_block_t block); + +/** + * @brief Set all Efuse program registers to zero. + * + * Call this before writing new data to the program registers. + */ +void ets_efuse_clear_program_registers(void); + +/** + * @brief Program a block of key data to an efuse block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. Key block must be unused (@ref ets_efuse_key_block_unused). + * @param purpose Purpose to set for this key. Purpose must be already unset. + * @param data Pointer to data to write. + * @param data_len Length of data to write. + * + * @note This function also calls ets_efuse_program() for the specified block, and for block 0 (setting the purpose) + */ +int ets_efuse_write_key(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose, const void *data, size_t data_len); + + +/* @brief Return the address of a particular efuse block's first read register + * + * @param block Index of efuse block to look up + * + * @return 0 if block is invalid, otherwise a numeric read register address + * of the first word in the block. + */ +uint32_t ets_efuse_get_read_register_address(ets_efuse_block_t block); + +/** + * @brief Return the current purpose set for an efuse key block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. + */ +ets_efuse_purpose_t ets_efuse_get_key_purpose(ets_efuse_block_t key_block); + +/** + * @brief Find a key block with the particular purpose set + * + * @param purpose Purpose to search for. + * @param[out] key_block Pointer which will be set to the key block if found. Can be NULL, if only need to test the key block exists. + * @return true if found, false if not found. If false, value at key_block pointer is unchanged. + */ +bool ets_efuse_find_purpose(ets_efuse_purpose_t purpose, ets_efuse_block_t *key_block); + +/** + * Return true if the key block is unused, false otherwise. + * + * An unused key block is all zero content, not read or write protected, + * and has purpose 0 (ETS_EFUSE_KEY_PURPOSE_USER) + * + * @param key_block key block to check. + * + * @return true if key block is unused, false if key block or used + * or the specified block index is not a key block. + */ +bool ets_efuse_key_block_unused(ets_efuse_block_t key_block); + + +/** + * @brief Search for an unused key block and return the first one found. + * + * See @ref ets_efuse_key_block_unused for a description of an unused key block. + * + * @return First unused key block, or ETS_EFUSE_BLOCK_MAX if no unused key block is found. + */ +ets_efuse_block_t ets_efuse_find_unused_key_block(void); + +/** + * @brief Return the number of unused efuse key blocks (0-6) + */ +unsigned ets_efuse_count_unused_key_blocks(void); + +/** + * @brief Calculate Reed-Solomon Encoding values for a block of efuse data. + * + * @param data Pointer to data buffer (length 32 bytes) + * @param rs_values Pointer to write encoded data to (length 12 bytes) + */ +void ets_efuse_rs_calculate(const void *data, void *rs_values); + +/** + * @brief Read spi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - 1 for default HSPI pins. + * - Other values define a custom pin configuration mask. Pins are encoded as per the EFUSE_SPICONFIG_RET_SPICLK, + * EFUSE_SPICONFIG_RET_SPIQ, EFUSE_SPICONFIG_RET_SPID, EFUSE_SPICONFIG_RET_SPICS0, EFUSE_SPICONFIG_RET_SPIHD macros. + * WP pin (for quad I/O modes) is not saved in efuse and not returned by this function. + */ +uint32_t ets_efuse_get_spiconfig(void); + +/** + * @brief Read spi flash wp pad from Efuse + * + * @return + * - 0x3f for invalid. + * - 0~46 is valid. + */ +uint32_t ets_efuse_get_wp_pad(void); + +/** + * @brief Read opi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - Other values define a custom pin configuration mask. From the LSB, every 6 bits represent a GPIO number which stand for: + * DQS, D4, D5, D6, D7 accordingly. + */ +uint32_t ets_efuse_get_opiconfig(void); + +/** + * @brief Read if download mode disabled from Efuse + * + * @return + * - true for efuse disable download mode. + * - false for efuse doesn't disable download mode. + */ +bool ets_efuse_download_modes_disabled(void); + +/** + * @brief Read if legacy spi flash boot mode disabled from Efuse + * + * @return + * - true for efuse disable legacy spi flash boot mode. + * - false for efuse doesn't disable legacy spi flash boot mode. + */ +bool ets_efuse_legacy_spi_boot_mode_disabled(void); + +/** + * @brief Read if uart print control value from Efuse + * + * @return + * - 0 for uart force print. + * - 1 for uart print when GPIO8 is low when digital reset. + * 2 for uart print when GPIO8 is high when digital reset. + * 3 for uart force slient + */ +uint32_t ets_efuse_get_uart_print_control(void); + +/** + * @brief Read which channel will used by ROM to print + * + * @return + * - 0 for UART0. + * - 1 for UART1. + */ +uint32_t ets_efuse_get_uart_print_channel(void); + +/** + * @brief Read if usb download mode disabled from Efuse + * + * (Also returns true if security download mode is enabled, as this mode + * disables USB download.) + * + * @return + * - true for efuse disable usb download mode. + * - false for efuse doesn't disable usb download mode. + */ +bool ets_efuse_usb_download_mode_disabled(void); + +/** + * @brief Read if tiny basic mode disabled from Efuse + * + * @return + * - true for efuse disable tiny basic mode. + * - false for efuse doesn't disable tiny basic mode. + */ +bool ets_efuse_tiny_basic_mode_disabled(void); + +/** + * @brief Read if usb module disabled from Efuse + * + * @return + * - true for efuse disable usb module. + * - false for efuse doesn't disable usb module. + */ +bool ets_efuse_usb_module_disabled(void); + +/** + * @brief Read if security download modes enabled from Efuse + * + * @return + * - true for efuse enable security download mode. + * - false for efuse doesn't enable security download mode. + */ +bool ets_efuse_security_download_modes_enabled(void); + +/** + * @brief Return true if secure boot is enabled in EFuse + */ +bool ets_efuse_secure_boot_enabled(void); + +/** + * @brief Return true if secure boot aggressive revoke is enabled in EFuse + */ +bool ets_efuse_secure_boot_aggressive_revoke_enabled(void); + +/** + * @brief Return true if cache encryption (flash, etc) is enabled from boot via EFuse + */ +bool ets_efuse_cache_encryption_enabled(void); + +/** + * @brief Return true if EFuse indicates an external phy needs to be used for USB + */ +bool ets_efuse_usb_use_ext_phy(void); + +/** + * @brief Return true if EFuse indicates USB device persistence is disabled + */ +bool ets_efuse_usb_force_nopersist(void); + +/** + * @brief Return true if OPI pins GPIO33-37 are powered by VDDSPI, otherwise by VDD33CPU + */ +bool ets_efuse_flash_opi_5pads_power_sel_vddspi(void); + +/** + * @brief Return true if EFuse indicates an opi flash is attached. + */ +bool ets_efuse_flash_opi_mode(void); + +/** + * @brief Return true if EFuse indicates to send a flash resume command. + */ +bool ets_efuse_force_send_resume(void); + +/** + * @brief return the time in us ROM boot need wait flash to power on from Efuse + * + * @return + * - uint32_t the time in us. + */ +uint32_t ets_efuse_get_flash_delay_us(void); + +#define EFUSE_SPICONFIG_SPI_DEFAULTS 0 +#define EFUSE_SPICONFIG_HSPI_DEFAULTS 1 + +#define EFUSE_SPICONFIG_RET_SPICLK_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICLK_SHIFT 0 +#define EFUSE_SPICONFIG_RET_SPICLK(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICLK_SHIFT) & EFUSE_SPICONFIG_RET_SPICLK_MASK) + +#define EFUSE_SPICONFIG_RET_SPIQ_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIQ_SHIFT 6 +#define EFUSE_SPICONFIG_RET_SPIQ(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIQ_SHIFT) & EFUSE_SPICONFIG_RET_SPIQ_MASK) + +#define EFUSE_SPICONFIG_RET_SPID_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPID_SHIFT 12 +#define EFUSE_SPICONFIG_RET_SPID(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPID_SHIFT) & EFUSE_SPICONFIG_RET_SPID_MASK) + +#define EFUSE_SPICONFIG_RET_SPICS0_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICS0_SHIFT 18 +#define EFUSE_SPICONFIG_RET_SPICS0(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICS0_SHIFT) & EFUSE_SPICONFIG_RET_SPICS0_MASK) + + +#define EFUSE_SPICONFIG_RET_SPIHD_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIHD_SHIFT 24 +#define EFUSE_SPICONFIG_RET_SPIHD(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIHD_SHIFT) & EFUSE_SPICONFIG_RET_SPIHD_MASK) + +/** + * @brief Enable JTAG temporarily by writing a JTAG HMAC "key" into + * the JTAG_CTRL registers. + * + * Works if JTAG has been "soft" disabled by burning the EFUSE_SOFT_DIS_JTAG efuse. + * + * Will enable the HMAC module to generate a "downstream" HMAC value from a key already saved in efuse, and then write the JTAG HMAC "key" which will enable JTAG if the two keys match. + * + * @param jtag_hmac_key Pointer to a 32 byte array containing a valid key. Supplied by user. + * @param key_block Index of a key block containing the source for this key. + * + * @return ETS_FAILED if HMAC operation fails or invalid parameter, ETS_OK otherwise. ETS_OK doesn't necessarily mean that JTAG was enabled. + */ +int ets_jtag_enable_temporarily(const uint8_t *jtag_hmac_key, ets_efuse_block_t key_block); + +/** + * @brief A crc8 algorithm used for MAC addresses in efuse + * + * @param unsigned char const *p : Pointer to original data. + * + * @param unsigned int len : Data length in byte. + * + * @return unsigned char: Crc value. + */ +unsigned char esp_crc8(unsigned char const *p, unsigned int len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_EFUSE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/esp_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/esp_flash.h new file mode 100644 index 00000000..40e5872c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/esp_flash.h @@ -0,0 +1,54 @@ +// Copyright 2020 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. + +#pragma once + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Note: Most of esp_flash APIs in ROM are compatible with headers in ESP-IDF, this function + just adds ROM-specific parts +*/ + +struct spi_flash_chip_t; +typedef struct esp_flash_t esp_flash_t; + +/* Structure to wrap "global" data used by esp_flash in ROM */ +typedef struct { + /* Default SPI flash chip, ie main chip attached to the MCU + This chip is used if the 'chip' argument passed to esp_flash_xxx API functions is ever NULL + */ + esp_flash_t *default_chip; + + /* Global API OS notification start/end/chip_check functions + + These are used by ROM if no other host functions are configured. + */ + struct { + esp_err_t (*start)(esp_flash_t *chip); + esp_err_t (*end)(esp_flash_t *chip, esp_err_t err); + esp_err_t (*chip_check)(esp_flash_t **inout_chip); + } api_funcs; +} esp_flash_rom_global_data_t; + +/** Access a pointer to the global data used by the ROM spi_flash driver + */ +esp_flash_rom_global_data_t *esp_flash_get_rom_global_data(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/ets_sys.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/ets_sys.h new file mode 100644 index 00000000..b3780248 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/ets_sys.h @@ -0,0 +1,563 @@ +// Copyright 2020 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. + +#ifndef _ROM_ETS_SYS_H_ +#define _ROM_ETS_SYS_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup ets_sys_apis, ets system related apis + * @brief ets system apis + */ + +/** @addtogroup ets_sys_apis + * @{ + */ + +/************************************************************************ + * NOTE + * Many functions in this header files can't be run in FreeRTOS. + * Please see the comment of the Functions. + * There are also some functions that doesn't work on FreeRTOS + * without listed in the header, such as: + * xtos functions start with "_xtos_" in ld file. + * + *********************************************************************** + */ + +/** \defgroup ets_apis, Espressif Task Scheduler related apis + * @brief ets apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +typedef enum { + ETS_OK = 0, /**< return successful in ets*/ + ETS_FAILED = 1 /**< return failed in ets*/ +} ETS_STATUS; + +typedef ETS_STATUS ets_status_t; + +typedef uint32_t ETSSignal; +typedef uint32_t ETSParam; + +typedef struct ETSEventTag ETSEvent; /**< Event transmit/receive in ets*/ + +struct ETSEventTag { + ETSSignal sig; /**< Event signal, in same task, different Event with different signal*/ + ETSParam par; /**< Event parameter, sometimes without usage, then will be set as 0*/ +}; + +typedef void (*ETSTask)(ETSEvent *e); /**< Type of the Task processer*/ +typedef void (* ets_idle_cb_t)(void *arg); /**< Type of the system idle callback*/ + +/** + * @brief Start the Espressif Task Scheduler, which is an infinit loop. Please do not add code after it. + * + * @param none + * + * @return none + */ +void ets_run(void); + +/** + * @brief Set the Idle callback, when Tasks are processed, will call the callback before CPU goto sleep. + * + * @param ets_idle_cb_t func : The callback function. + * + * @param void *arg : Argument of the callback. + * + * @return None + */ +void ets_set_idle_cb(ets_idle_cb_t func, void *arg); + +/** + * @brief Init a task with processer, priority, queue to receive Event, queue length. + * + * @param ETSTask task : The task processer. + * + * @param uint8_t prio : Task priority, 0-31, bigger num with high priority, one priority with one task. + * + * @param ETSEvent *queue : Queue belongs to the task, task always receives Events, Queue is circular used. + * + * @param uint8_t qlen : Queue length. + * + * @return None + */ +void ets_task(ETSTask task, uint8_t prio, ETSEvent *queue, uint8_t qlen); + +/** + * @brief Post an event to an Task. + * + * @param uint8_t prio : Priority of the Task. + * + * @param ETSSignal sig : Event signal. + * + * @param ETSParam par : Event parameter + * + * @return ETS_OK : post successful + * @return ETS_FAILED : post failed + */ +ETS_STATUS ets_post(uint8_t prio, ETSSignal sig, ETSParam par); + +/** + * @} + */ + +/** \defgroup ets_boot_apis, Boot routing related apis + * @brief ets boot apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +extern const char *const exc_cause_table[40]; ///**< excption cause that defined by the core.*/ + +/** + * @brief Set Pro cpu Entry code, code can be called in PRO CPU when booting is not completed. + * When Pro CPU booting is completed, Pro CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the PRO Entry code address value in uint32_t + * + * @return None + */ +void ets_set_user_start(uint32_t start); + +/** + * @brief Set Pro cpu Startup code, code can be called when booting is not completed, or in Entry code. + * When Entry code completed, CPU will call the Startup code if not NULL, else call ets_run. + * + * @param uint32_t callback : the Startup code address value in uint32_t + * + * @return None : post successful + */ +void ets_set_startup_callback(uint32_t callback); + +/** + * @brief Set App cpu Entry code, code can be called in PRO CPU. + * When APP booting is completed, APP CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the APP Entry code address value in uint32_t, stored in register APPCPU_CTRL_REG_D. + * + * @return None + */ +void ets_set_appcpu_boot_addr(uint32_t start); + +/** + * @} + */ + +/** \defgroup ets_printf_apis, ets_printf related apis used in ets + * @brief ets printf apis + */ + +/** @addtogroup ets_printf_apis + * @{ + */ + +/** + * @brief Printf the strings to uart or other devices, similar with printf, simple than printf. + * Can not print float point data format, or longlong data format. + * So we maybe only use this in ROM. + * + * @param const char *fmt : See printf. + * + * @param ... : See printf. + * + * @return int : the length printed to the output device. + */ +int ets_printf(const char *fmt, ...); + +/** + * @brief Set the uart channel of ets_printf(uart_tx_one_char). + * ROM will set it base on the efuse and gpio setting, however, this can be changed after booting. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2. + * + * @return None + */ +void ets_set_printf_channel(uint8_t uart_no); + +/** + * @brief Get the uart channel of ets_printf(uart_tx_one_char). + * + * @return uint8_t uart channel used by ets_printf(uart_tx_one_char). + */ +uint8_t ets_get_printf_channel(void); + +/** + * @brief Output a char to uart, which uart to output(which is in uart module in ROM) is not in scope of the function. + * Can not print float point data format, or longlong data format + * + * @param char c : char to output. + * + * @return None + */ +void ets_write_char_uart(char c); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc1, which is defaulted installed as ets_write_char_uart in none silent boot mode, as NULL in silent mode. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc1(void (*p)(char c)); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc2, which is defaulted installed as NULL. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc2(void (*p)(char c)); + +/** + * @brief Install putc1 as ets_write_char_uart. + * In silent boot mode(to void interfere the UART attached MCU), we can call this function, after booting ok. + * + * @param None + * + * @return None + */ +void ets_install_uart_printf(void); + +#define ETS_PRINTF(...) ets_printf(...) + +#define ETS_ASSERT(v) do { \ + if (!(v)) { \ + ets_printf("%s %u \n", __FILE__, __LINE__); \ + while (1) {}; \ + } \ +} while (0); + +/** + * @} + */ + +/** \defgroup ets_timer_apis, ets_timer related apis used in ets + * @brief ets timer apis + */ + +/** @addtogroup ets_timer_apis + * @{ + */ +typedef void ETSTimerFunc(void *timer_arg);/**< timer handler*/ + +typedef struct _ETSTIMER_ { + struct _ETSTIMER_ *timer_next; /**< timer linker*/ + uint32_t timer_expire; /**< abstruct time when timer expire*/ + uint32_t timer_period; /**< timer period, 0 means timer is not periodic repeated*/ + ETSTimerFunc *timer_func; /**< timer handler*/ + void *timer_arg; /**< timer handler argument*/ +} ETSTimer; + +/** + * @brief Init ets timer, this timer range is 640 us to 429496 ms + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_init(void); + +/** + * @brief In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_deinit(void); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in ms, range is 1 to 429496. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm(ETSTimer *timer, uint32_t tmout, bool repeat); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in us, range is 1 to 429496729. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm_us(ETSTimer *ptimer, uint32_t us, bool repeat); + +/** + * @brief Disarm an ets timer. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_disarm(ETSTimer *timer); + +/** + * @brief Set timer callback and argument. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param ETSTimerFunc *pfunction : Timer callback. + * + * @param void *parg : Timer callback argument. + * + * @return None + */ +void ets_timer_setfn(ETSTimer *ptimer, ETSTimerFunc *pfunction, void *parg); + +/** + * @brief Unset timer callback and argument to NULL. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_done(ETSTimer *ptimer); + +/** + * @brief CPU do while loop for some time. + * In FreeRTOS task, please call FreeRTOS apis. + * + * @param uint32_t us : Delay time in us. + * + * @return None + */ +void ets_delay_us(uint32_t us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * Call this function when CPU frequency is changed. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency(uint32_t ticks_per_us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * + * @note This function only sets the tick rate for the current CPU. It is located in ROM, + * so the deep sleep stub can use it even if IRAM is not initialized yet. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency_rom(uint32_t ticks_per_us); + +/** + * @brief Get the real CPU ticks per us to the ets. + * This function do not return real CPU ticks per us, just the record in ets. It can be used to check with the real CPU frequency. + * + * @param None + * + * @return uint32_t : CPU ticks per us record in ets. + */ +uint32_t ets_get_cpu_frequency(void); + +/** + * @brief Get xtal_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if stored in efuse(not 0) + * clock = ets_efuse_get_xtal_freq() * 1000000; + * else if analog_8M in efuse + * clock = ets_get_xtal_scale() * 625 / 16 * ets_efuse_get_8M_clock(); + * else clock = 40M. + */ +uint32_t ets_get_xtal_freq(void); + +/** + * @brief Get the apb divior by xtal frequency. + * When any types of reset happen, the default value is 2. + * + * @param None + * + * @return uint32_t : 1 or 2. + */ +uint32_t ets_get_xtal_div(void); + +/** + * @brief Get apb_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if rtc store the value (RTC_STORE5 high 16 bits and low 16 bits with same value), read from rtc register. + * clock = (REG_READ(RTC_STORE5) & 0xffff) << 12; + * else store ets_get_detected_xtal_freq() in. + */ +uint32_t ets_get_apb_freq(void); + +/** + * @} + */ + +/** \defgroup ets_intr_apis, ets interrupt configure related apis + * @brief ets intr apis + */ + +/** @addtogroup ets_intr_apis + * @{ + */ + +typedef void (* ets_isr_t)(void *);/**< interrupt handler type*/ + +/** + * @brief Attach a interrupt handler to a CPU interrupt number. + * This function equals to _xtos_set_interrupt_handler_arg(i, func, arg). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param int i : CPU interrupt number. + * + * @param ets_isr_t func : Interrupt handler. + * + * @param void *arg : argument of the handler. + * + * @return None + */ +void ets_isr_attach(int i, ets_isr_t func, void *arg); + +/** + * @brief Mask the interrupts which show in mask bits. + * This function equals to _xtos_ints_off(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_mask(uint32_t mask); + +/** + * @brief Unmask the interrupts which show in mask bits. + * This function equals to _xtos_ints_on(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_unmask(uint32_t unmask); + +/** + * @brief Lock the interrupt to level 2. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_lock(void); + +/** + * @brief Unlock the interrupt to level 0. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_unlock(void); + +/** + * @brief Unlock the interrupt to level 0, and CPU will go into power save mode(wait interrupt). + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_waiti0(void); + +/** + * @brief Attach an CPU interrupt to a hardware source. + * We have 4 steps to use an interrupt: + * 1.Attach hardware interrupt source to CPU. intr_matrix_set(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM); + * 2.Set interrupt handler. xt_set_interrupt_handler(ETS_WMAC_INUM, func, NULL); + * 3.Enable interrupt for CPU. xt_ints_on(1 << ETS_WMAC_INUM); + * 4.Enable interrupt in the module. + * + * @param int cpu_no : The CPU which the interrupt number belongs. + * + * @param uint32_t model_num : The interrupt hardware source number, please see the interrupt hardware source table. + * + * @param uint32_t intr_num : The interrupt number CPU, please see the interrupt cpu using table. + * + * @return None + */ +void intr_matrix_set(int cpu_no, uint32_t model_num, uint32_t intr_num); + +/** + * @} + */ + +#ifndef MAC2STR +#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] +#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" +#endif + +#define ETS_MEM_BAR() asm volatile ( "" : : : "memory" ) + +typedef enum { + OK = 0, + FAIL, + PENDING, + BUSY, + CANCEL, +} STATUS; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_ETS_SYS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/gpio.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/gpio.h new file mode 100644 index 00000000..2969d14f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/gpio.h @@ -0,0 +1,311 @@ +// Copyright 2020 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. + +#ifndef _ROM_GPIO_H_ +#define _ROM_GPIO_H_ + +#include +#include + +#include "esp_attr.h" +#include "soc/gpio_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup gpio_apis, uart configuration and communication related apis + * @brief gpio apis + */ + +/** @addtogroup gpio_apis + * @{ + */ + +#define GPIO_REG_READ(reg) READ_PERI_REG(reg) +#define GPIO_REG_WRITE(reg, val) WRITE_PERI_REG(reg, val) +#define GPIO_ID_PIN0 0 +#define GPIO_ID_PIN(n) (GPIO_ID_PIN0+(n)) +#define GPIO_PIN_ADDR(i) (GPIO_PIN0_REG + i*4) + +#define GPIO_FUNC_IN_HIGH 0x38 +#define GPIO_FUNC_IN_LOW 0x3C + +#define GPIO_ID_IS_PIN_REGISTER(reg_id) \ + ((reg_id >= GPIO_ID_PIN0) && (reg_id <= GPIO_ID_PIN(GPIO_PIN_COUNT-1))) + +#define GPIO_REGID_TO_PINIDX(reg_id) ((reg_id) - GPIO_ID_PIN0) + +typedef enum { + GPIO_PIN_INTR_DISABLE = 0, + GPIO_PIN_INTR_POSEDGE = 1, + GPIO_PIN_INTR_NEGEDGE = 2, + GPIO_PIN_INTR_ANYEDGE = 3, + GPIO_PIN_INTR_LOLEVEL = 4, + GPIO_PIN_INTR_HILEVEL = 5 +} GPIO_INT_TYPE; + +#define GPIO_OUTPUT_SET(gpio_no, bit_value) \ + ((gpio_no < 32) ? gpio_output_set(bit_value<>gpio_no)&BIT0) : ((gpio_input_get_high()>>(gpio_no - 32))&BIT0)) + +/* GPIO interrupt handler, registered through gpio_intr_handler_register */ +typedef void (* gpio_intr_handler_fn_t)(uint32_t intr_mask, bool high, void *arg); + +/** + * @brief Initialize GPIO. This includes reading the GPIO Configuration DataSet + * to initialize "output enables" and pin configurations for each gpio pin. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_init(void); + +/** + * @brief Change GPIO(0-31) pin output by setting, clearing, or disabling pins, GPIO0<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Change GPIO(32-39) pin output by setting, clearing, or disabling pins, GPIO32<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set_high(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Sample the value of GPIO input pins(0-31) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO0. + */ +uint32_t gpio_input_get(void); + +/** + * @brief Sample the value of GPIO input pins(32-39) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO32. + */ +uint32_t gpio_input_get_high(void); + +/** + * @brief Register an application-specific interrupt handler for GPIO pin interrupts. + * Once the interrupt handler is called, it will not be called again until after a call to gpio_intr_ack. + * Please do not call this function in SDK. + * + * @param gpio_intr_handler_fn_t fn : gpio application-specific interrupt handler + * + * @param void *arg : gpio application-specific interrupt handler argument. + * + * @return None + */ +void gpio_intr_handler_register(gpio_intr_handler_fn_t fn, void *arg); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO0. + */ +uint32_t gpio_intr_pending(void); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO32. + */ +uint32_t gpio_intr_pending_high(void); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO0. + * + * @return None + */ +void gpio_intr_ack(uint32_t ack_mask); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO32. + * + * @return None + */ +void gpio_intr_ack_high(uint32_t ack_mask); + +/** + * @brief Set GPIO to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param uint32_t i: gpio number. + * + * @param GPIO_INT_TYPE intr_state : only GPIO_PIN_INTR_LOLEVEL\GPIO_PIN_INTR_HILEVEL can be used + * + * @return None + */ +void gpio_pin_wakeup_enable(uint32_t i, GPIO_INT_TYPE intr_state); + +/** + * @brief disable GPIOs to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_pin_wakeup_disable(void); + +/** + * @brief set gpio input to a signal, one gpio can input to several signals. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * gpio == 0x3C, input 0 to signal + * gpio == 0x3A, input nothing to signal + * gpio == 0x38, input 1 to signal + * + * @param uint32_t signal_idx : signal index. + * + * @param bool inv : the signal is inv or not + * + * @return None + */ +void gpio_matrix_in(uint32_t gpio, uint32_t signal_idx, bool inv); + +/** + * @brief set signal output to gpio, one signal can output to several gpios. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * + * @param uint32_t signal_idx : signal index. + * signal_idx == 0x100, cancel output put to the gpio + * + * @param bool out_inv : the signal output is invert or not + * + * @param bool oen_inv : the signal output enable is invert or not + * + * @return None + */ +void gpio_matrix_out(uint32_t gpio, uint32_t signal_idx, bool out_inv, bool oen_inv); + +/** + * @brief Select pad as a gpio function from IOMUX. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_select_gpio(uint32_t gpio_num); + +/** + * @brief Set pad driver capability. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @param uint32_t drv : 0-3 + * + * @return None + */ +void gpio_pad_set_drv(uint32_t gpio_num, uint32_t drv); + +/** + * @brief Pull up the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pullup(uint32_t gpio_num); + +/** + * @brief Pull down the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pulldown(uint32_t gpio_num); + +/** + * @brief Unhold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_unhold(uint32_t gpio_num); + +/** + * @brief Hold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_hold(uint32_t gpio_num); + +/** + * @brief enable gpio pad input. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_input_enable(uint32_t gpio_num); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_GPIO_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/hmac.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/hmac.h new file mode 100644 index 00000000..223fe884 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/hmac.h @@ -0,0 +1,63 @@ +// Copyright 2020 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. + +#ifndef _ROM_HMAC_H_ +#define _ROM_HMAC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "efuse.h" + +void ets_hmac_enable(void); + +void ets_hmac_disable(void); + +/* Use the "upstream" HMAC key (ETS_EFUSE_KEY_PURPOSE_HMAC_UP) + to digest a message. +*/ +int ets_hmac_calculate_message(ets_efuse_block_t key_block, const void *message, size_t message_len, uint8_t *hmac); + +/* Calculate a downstream HMAC message to temporarily enable JTAG, or + to generate a Digital Signature data decryption key. + + - purpose must be ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE + or ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG + + - key_block must be in range ETS_EFUSE_BLOCK_KEY0 toETS_EFUSE_BLOCK_KEY6. + This efuse block must have the corresponding purpose set in "purpose", or + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL. + + The result of this HMAC calculation is only made available "downstream" to the + corresponding hardware module, and cannot be accessed by software. +*/ +int ets_hmac_calculate_downstream(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose); + +/* Invalidate a downstream HMAC value previously calculated by ets_hmac_calculate_downstream(). + * + * - purpose must match a previous call to ets_hmac_calculate_downstream(). + * + * After this function is called, the corresponding internal operation (JTAG or DS) will no longer + * have access to the generated key. + */ +int ets_hmac_invalidate_downstream(ets_efuse_purpose_t purpose); + +#ifdef __cplusplus +} +#endif + +#endif // _ROM_HMAC_H_ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/libc_stubs.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/libc_stubs.h new file mode 100644 index 00000000..df78851c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/libc_stubs.h @@ -0,0 +1,104 @@ +// Copyright 2020 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. +#ifndef _ROM_LIBC_STUBS_H_ +#define _ROM_LIBC_STUBS_H_ + +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* +ESP32 ROM code contains implementations of some of C library functions. +Whenever a function in ROM needs to use a syscall, it calls a pointer to the corresponding syscall +implementation defined in the following struct. + +The table itself, by default, is not allocated in RAM. A global pointer syscall_table_ptr is used to +set the address + +So, before using any of the C library functions (except for pure functions and memcpy/memset functions), +application must allocate syscall table structure for each CPU being used, and populate it with pointers +to actual implementations of corresponding syscalls. +*/ + +struct syscall_stub_table +{ + struct _reent* (*__getreent)(void); + void* (*_malloc_r)(struct _reent *r, size_t); + void (*_free_r)(struct _reent *r, void*); + void* (*_realloc_r)(struct _reent *r, void*, size_t); + void* (*_calloc_r)(struct _reent *r, size_t, size_t); + void (*_abort)(void); + int (*_system_r)(struct _reent *r, const char*); + int (*_rename_r)(struct _reent *r, const char*, const char*); + clock_t (*_times_r)(struct _reent *r, struct tms *); + int (*_gettimeofday_r) (struct _reent *r, struct timeval *, void *); + void (*_raise_r)(struct _reent *r); + int (*_unlink_r)(struct _reent *r, const char*); + int (*_link_r)(struct _reent *r, const char*, const char*); + int (*_stat_r)(struct _reent *r, const char*, struct stat *); + int (*_fstat_r)(struct _reent *r, int, struct stat *); + void* (*_sbrk_r)(struct _reent *r, ptrdiff_t); + int (*_getpid_r)(struct _reent *r); + int (*_kill_r)(struct _reent *r, int, int); + void (*_exit_r)(struct _reent *r, int); + int (*_close_r)(struct _reent *r, int); + int (*_open_r)(struct _reent *r, const char *, int, int); + int (*_write_r)(struct _reent *r, int, const void *, int); + int (*_lseek_r)(struct _reent *r, int, int, int); + int (*_read_r)(struct _reent *r, int, void *, int); +#ifdef _RETARGETABLE_LOCKING + void (*_retarget_lock_init)(_LOCK_T *lock); + void (*_retarget_lock_init_recursive)(_LOCK_T *lock); + void (*_retarget_lock_close)(_LOCK_T lock); + void (*_retarget_lock_close_recursive)(_LOCK_T lock); + void (*_retarget_lock_acquire)(_LOCK_T lock); + void (*_retarget_lock_acquire_recursive)(_LOCK_T lock); + int (*_retarget_lock_try_acquire)(_LOCK_T lock); + int (*_retarget_lock_try_acquire_recursive)(_LOCK_T lock); + void (*_retarget_lock_release)(_LOCK_T lock); + void (*_retarget_lock_release_recursive)(_LOCK_T lock); +#else + void (*_lock_init)(_lock_t *lock); + void (*_lock_init_recursive)(_lock_t *lock); + void (*_lock_close)(_lock_t *lock); + void (*_lock_close_recursive)(_lock_t *lock); + void (*_lock_acquire)(_lock_t *lock); + void (*_lock_acquire_recursive)(_lock_t *lock); + int (*_lock_try_acquire)(_lock_t *lock); + int (*_lock_try_acquire_recursive)(_lock_t *lock); + void (*_lock_release)(_lock_t *lock); + void (*_lock_release_recursive)(_lock_t *lock); +#endif + int (*_printf_float)(struct _reent *data, void *pdata, FILE * fp, int (*pfunc) (struct _reent *, FILE *, const char *, size_t len), va_list * ap); + int (*_scanf_float) (struct _reent *rptr, void *pdata, FILE *fp, va_list *ap); + void (*__assert_func) (const char *file, int line, const char * func, const char *failedexpr) __attribute__((noreturn)); + void (*__sinit) (struct _reent *r); + void (*_cleanup_r) (struct _reent* r); +}; + +extern struct syscall_stub_table *syscall_table_ptr; + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /* _ROM_LIBC_STUBS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/lldesc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/lldesc.h new file mode 100644 index 00000000..d4c5d92a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/lldesc.h @@ -0,0 +1,176 @@ +// Copyright 2020 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. + +#ifndef _ROM_LLDESC_H_ +#define _ROM_LLDESC_H_ + +#include + +#include "sys/queue.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LLDESC_TX_MBLK_SIZE 268 /* */ +#define LLDESC_RX_SMBLK_SIZE 64 /* small block size, for small mgmt frame */ +#define LLDESC_RX_MBLK_SIZE 524 /* rx is large sinec we want to contain mgmt frame in one block*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_SIZE 64 /* it is a small buffer which is a cycle link*/ +#define LLDESC_RX_AMPDU_LEN_MBLK_SIZE 256 /*for ampdu entry*/ +#ifdef ESP_MAC_5 +#define LLDESC_TX_MBLK_NUM 116 /* 64K / 256 */ +#define LLDESC_RX_MBLK_NUM 82 /* 64K / 512 MAX 172*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 12 +#else +#ifdef SBUF_RXTX +#define LLDESC_TX_MBLK_NUM_MAX (2 * 48) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MAX (2 * 48) /* 23K / 524 */ +#define LLDESC_TX_MBLK_NUM_MIN (2 * 16) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MIN (2 * 16) /* 23K / 524 */ +#endif +#define LLDESC_TX_MBLK_NUM 10 //(2 * 32) /* 23K / 260 - 8 */ + +#ifdef IEEE80211_RX_AMPDU +#define LLDESC_RX_MBLK_NUM 30 +#else +#define LLDESC_RX_MBLK_NUM 10 +#endif /*IEEE80211_RX_AMPDU*/ + +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 8 +#endif /* !ESP_MAC_5 */ +/* + * SLC2 DMA Desc struct, aka lldesc_t + * + * -------------------------------------------------------------- + * | own | EoF | sub_sof | 5'b0 | length [11:0] | size [11:0] | + * -------------------------------------------------------------- + * | buf_ptr [31:0] | + * -------------------------------------------------------------- + * | next_desc_ptr [31:0] | + * -------------------------------------------------------------- + */ + +/* this bitfield is start from the LSB!!! */ +typedef struct lldesc_s { + volatile uint32_t size : 12, + length: 12, + offset: 5, /* h/w reserved 5bit, s/w use it as offset in buffer */ + sosf : 1, /* start of sub-frame */ + eof : 1, /* end of frame */ + owner : 1; /* hw or sw */ + volatile const uint8_t *buf; /* point to buffer data */ + union { + volatile uint32_t empty; + STAILQ_ENTRY(lldesc_s) qe; /* pointing to the next desc */ + }; +} lldesc_t; + +typedef struct tx_ampdu_entry_s { + uint32_t sub_len : 12, + dili_num : 7, + : 1, + null_byte: 2, + data : 1, + enc : 1, + seq : 8; +} tx_ampdu_entry_t; + +typedef struct lldesc_chain_s { + lldesc_t *head; + lldesc_t *tail; +} lldesc_chain_t; + +#ifdef SBUF_RXTX +enum sbuf_mask_s { + SBUF_MOVE_NO = 0, + SBUF_MOVE_TX2RX, + SBUF_MOVE_RX2TX, +} ; + +#define SBUF_MOVE_STEP 8 +#endif +#define LLDESC_SIZE sizeof(struct lldesc_s) + +/* SLC Descriptor */ +#define LLDESC_OWNER_MASK 0x80000000 +#define LLDESC_OWNER_SHIFT 31 +#define LLDESC_SW_OWNED 0 +#define LLDESC_HW_OWNED 1 + +#define LLDESC_EOF_MASK 0x40000000 +#define LLDESC_EOF_SHIFT 30 + +#define LLDESC_SOSF_MASK 0x20000000 +#define LLDESC_SOSF_SHIFT 29 + +#define LLDESC_LENGTH_MASK 0x00fff000 +#define LLDESC_LENGTH_SHIFT 12 + +#define LLDESC_SIZE_MASK 0x00000fff +#define LLDESC_SIZE_SHIFT 0 + +#define LLDESC_ADDR_MASK 0x000fffff + +void lldesc_build_chain(uint8_t *descptr, uint32_t desclen, uint8_t *mblkptr, uint32_t buflen, uint32_t blksz, uint8_t owner, + lldesc_t **head, +#ifdef TO_HOST_RESTART + lldesc_t **one_before_tail, +#endif + lldesc_t **tail); + +lldesc_t *lldesc_num2link(lldesc_t *head, uint16_t nblks); + +lldesc_t *lldesc_set_owner(lldesc_t *head, uint16_t nblks, uint8_t owner); + +static inline uint32_t lldesc_get_chain_length(lldesc_t *head) +{ + lldesc_t *ds = head; + uint32_t len = 0; + + while (ds) { + len += ds->length; + ds = STAILQ_NEXT(ds, qe); + } + + return len; +} + +static inline void lldesc_config(lldesc_t *ds, uint8_t owner, uint8_t eof, uint8_t sosf, uint16_t len) +{ + ds->owner = owner; + ds->eof = eof; + ds->sosf = sosf; + ds->length = len; +} + +#define LLDESC_CONFIG(_desc, _owner, _eof, _sosf, _len) do { \ + (_desc)->owner = (_owner); \ + (_desc)->eof = (_eof); \ + (_desc)->sosf = (_sosf); \ + (_desc)->length = (_len); \ +} while(0) + +#define LLDESC_FROM_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#define LLDESC_MAC_RX_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, (ds)->size) + +#define LLDESC_TO_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_LLDESC_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/md5_hash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/md5_hash.h new file mode 100644 index 00000000..63ce1585 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/md5_hash.h @@ -0,0 +1,38 @@ +/* + * MD5 internal definitions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#ifndef _ROM_MD5_HASH_H_ +#define _ROM_MD5_HASH_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); +void MD5Final(unsigned char digest[16], struct MD5Context *context); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_MD5_HASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/miniz.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/miniz.h new file mode 100644 index 00000000..4c8cb7a4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/miniz.h @@ -0,0 +1,760 @@ +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times, and the C run-time funcs that get/set times won't be called. +// The current downside is the times written to your archives will be from 1979. +#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +#define MINIZ_NO_MALLOC + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux +#define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +//Hardcoded options for Xtensa - JD +#define MINIZ_X86_OR_X64_CPU 0 +#define MINIZ_LITTLE_ENDIAN 1 +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_HAS_64BIT_REGISTERS 0 +#define TINFL_USE_64BIT_BITBUF 0 + + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s { + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum { + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct { + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct mz_zip_archive_tag { + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum { + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum { + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum { + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct { + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 1 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum { + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL +// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct { + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/newlib.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/newlib.h new file mode 100644 index 00000000..a852bdb7 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/newlib.h @@ -0,0 +1,50 @@ +// Copyright 2020 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. +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Global variables used by newlib in ROM + + Note that any of these symbols which are used by both ROM & IDF will have duplicate copies + in each "side" of the memory. However they're all pointers, and the pointers will be to the same + thing, so it's not a big memory waste and functionality is the same. + + Some variables which look like they should be here, but aren't: + + - __sf_fake_stdin, __sf_fake_stdout, __sf_fake_stderr - These are defined in ROM because ROM includes findfp.c, + but only used if _REENT_INIT or _REENT_INIT_PTR are ever called and ROM doesn't use these macros anywhere unless + printf() or similar is called without initializing reent first. ESP-IDF sets up its own minimal reent structures. + + - __lock___sinit_recursive_mutex, etc. - these are combined into common_recursive_mutex & common_mutex to save space +*/ +typedef struct { + _LOCK_T common_recursive_mutex; + _LOCK_T common_mutex; + struct _reent *global_reent; +} esp_rom_newlib_global_data_t; + +/* Called from IDF newlib component setup + to initialize common data shared between ROM and IDF +*/ +void esp_rom_newlib_init_global_data(const esp_rom_newlib_global_data_t *data); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rom_layout.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rom_layout.h new file mode 100644 index 00000000..cd1730c8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rom_layout.h @@ -0,0 +1,86 @@ +// Copyright 2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define SUPPORT_BTDM 1 +#define SUPPORT_WIFI 1 + +/* Structure and functions for returning ROM global layout + * + * This is for address symbols defined in the linker script, which may change during ECOs. + */ +typedef struct { + void *dram0_stack_shared_mem_start; + void *dram0_rtos_reserved_start; + void *stack_sentry; + void *stack; + void *stack_sentry_app; + void *stack_app; + + /* BTDM data */ + void *data_start_btdm; + void *data_end_btdm; + void *bss_start_btdm; + void *bss_end_btdm; + void *data_start_btdm_rom; + void *data_end_btdm_rom; + void *data_start_interface_btdm; + void *data_end_interface_btdm; + void *bss_start_interface_btdm; + void *bss_end_interface_btdm; + + /* Other DRAM ranges */ +#if SUPPORT_BTDM || SUPPORT_WIFI + void *dram_start_phyrom; + void *dram_end_phyrom; +#endif +#if SUPPORT_WIFI + void *dram_start_coexist; + void *dram_end_coexist; + void *dram_start_net80211; + void *dram_end_net80211; + void *dram_start_pp; + void *dram_end_pp; + void *data_start_interface_coexist; + void *data_end_interface_coexist; + void *bss_start_interface_coexist; + void *bss_end_interface_coexist; + void *data_start_interface_net80211; + void *data_end_interface_net80211; + void *bss_start_interface_net80211; + void *bss_end_interface_net80211; + void *data_start_interface_pp; + void *data_end_interface_pp; + void *bss_start_interface_pp; + void *bss_end_interface_pp; +#endif + void *dram_start_usbdev_rom; + void *dram_end_usbdev_rom; + void *dram_start_uart_rom; + void *dram_end_uart_rom; + +} ets_rom_layout_t; + +extern const ets_rom_layout_t * const ets_rom_layout_p; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rsa_pss.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rsa_pss.h new file mode 100644 index 00000000..4a838071 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rsa_pss.h @@ -0,0 +1,46 @@ +// Copyright 2020 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. + +#ifndef _ROM_RSA_PSS_H_ +#define _ROM_RSA_PSS_H_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ETS_SIG_LEN 384 /* Bytes */ +#define ETS_DIGEST_LEN 32 /* SHA-256, bytes */ + +typedef struct { + uint8_t n[384]; /* Public key modulus */ + uint32_t e; /* Public key exponent */ + uint8_t rinv[384]; + uint32_t mdash; +} ets_rsa_pubkey_t; + +bool ets_rsa_pss_verify(const ets_rsa_pubkey_t *key, const uint8_t *sig, const uint8_t *digest, uint8_t *verified_digest); + +void ets_mgf1_sha256(const uint8_t *mgfSeed, size_t seedLen, size_t maskLen, uint8_t *mask); + +bool ets_emsa_pss_verify(const uint8_t *encoded_message, const uint8_t *mhash); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rtc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rtc.h new file mode 100644 index 00000000..fcbfddc1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/rtc.h @@ -0,0 +1,239 @@ +// Copyright 2020 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. + +#ifndef _ROM_RTC_H_ +#define _ROM_RTC_H_ + +#include "ets_sys.h" + +#include +#include + +#include "soc/soc.h" +#include "soc/rtc_cntl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup rtc_apis, rtc registers and memory related apis + * @brief rtc apis + */ + +/** @addtogroup rtc_apis + * @{ + */ + +/************************************************************************************** + * Note: * + * Some Rtc memory and registers are used, in ROM or in internal library. * + * Please do not use reserved or used rtc memory or registers. * + * * + ************************************************************************************* + * RTC Memory & Store Register usage + ************************************************************************************* + * rtc memory addr type size usage + * 0x3f421000(0x50000000) Slow SIZE_CP Co-Processor code/Reset Entry + * 0x3f421000+SIZE_CP Slow 8192-SIZE_CP + * + * 0x3ff80000(0x40070000) Fast 8192 deep sleep entry code + * + ************************************************************************************* + * RTC store registers usage + * RTC_CNTL_STORE0_REG Reserved + * RTC_CNTL_STORE1_REG RTC_SLOW_CLK calibration value + * RTC_CNTL_STORE2_REG Boot time, low word + * RTC_CNTL_STORE3_REG Boot time, high word + * RTC_CNTL_STORE4_REG External XTAL frequency + * RTC_CNTL_STORE5_REG APB bus frequency + * RTC_CNTL_STORE6_REG FAST_RTC_MEMORY_ENTRY + * RTC_CNTL_STORE7_REG FAST_RTC_MEMORY_CRC + ************************************************************************************* + */ + +#define RTC_SLOW_CLK_CAL_REG RTC_CNTL_STORE1_REG +#define RTC_BOOT_TIME_LOW_REG RTC_CNTL_STORE2_REG +#define RTC_BOOT_TIME_HIGH_REG RTC_CNTL_STORE3_REG +#define RTC_XTAL_FREQ_REG RTC_CNTL_STORE4_REG +#define RTC_APB_FREQ_REG RTC_CNTL_STORE5_REG +#define RTC_ENTRY_ADDR_REG RTC_CNTL_STORE6_REG +#define RTC_RESET_CAUSE_REG RTC_CNTL_STORE6_REG +#define RTC_MEMORY_CRC_REG RTC_CNTL_STORE7_REG + +#define RTC_DISABLE_ROM_LOG ((1 << 0) | (1 << 16)) //!< Disable logging from the ROM code. + + +typedef enum { + AWAKE = 0, // +#include +#include "ets_sys.h" +#include "rsa_pss.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct ets_secure_boot_sig_block; +struct ets_secure_boot_signature_t; + +typedef struct ets_secure_boot_sig_block ets_secure_boot_sig_block_t; +typedef struct ets_secure_boot_signature ets_secure_boot_signature_t; +typedef struct ets_secure_boot_key_digests ets_secure_boot_key_digests_t; + +/* Anti-FI measure: use full words for success/fail, instead of + 0/non-zero +*/ +typedef enum { + SB_SUCCESS = 0x3A5A5AA5, + SB_FAILED = 0x7533885E, +} ets_secure_boot_status_t; + + +/* Verify and stage-load the bootloader image + (reconfigures cache to map, loads trusted key digests from efuse, + copies the bootloader into the staging buffer.) + + If allow_key_revoke is true and aggressive revoke efuse is set, + any failed signature has its associated key revoked in efuse. + + If result is SB_SUCCESS, the "simple hash" of the bootloader + is copied into verified_hash. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_stage_bootloader(uint8_t *verified_hash, bool allow_key_revoke); + +/* Verify bootloader image (reconfigures cache to map), + with key digests provided as parameters.) + + Can be used to verify secure boot status before enabling + secure boot permanently. + + If stage_load parameter is true, bootloader is copied into staging + buffer in RAM at the same time. + + If result is SB_SUCCESS, the "simple hash" of the bootloader is + copied into verified_hash. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_bootloader_with_keys(uint8_t *verified_hash, const ets_secure_boot_key_digests_t *trusted_keys, bool stage_load); + +/* Read key digests from efuse. Any revoked/missing digests will be + marked as NULL +*/ +ETS_STATUS ets_secure_boot_read_key_digests(ets_secure_boot_key_digests_t *trusted_keys); + +/* Verify supplied signature against supplied digest, using + supplied trusted key digests. + + Doesn't reconfigure cache or any other hardware access except for RSA peripheral. + + If result is SB_SUCCESS, the image_digest value is copied into verified_digest. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_signature(const ets_secure_boot_signature_t *sig, const uint8_t *image_digest, const ets_secure_boot_key_digests_t *trusted_keys, uint8_t *verified_digest); + +/* Revoke a public key digest in efuse. + @param index Digest to revoke. Must be 0, 1 or 2. + */ +void ets_secure_boot_revoke_public_key_digest(int index); + +#define CRC_SIGN_BLOCK_LEN 1196 +#define SIG_BLOCK_PADDING 4096 +#define ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC 0xE7 + +/* Secure Boot V2 signature block + + (Up to 3 in a signature sector are appended to the image) + */ +struct ets_secure_boot_sig_block { + uint8_t magic_byte; + uint8_t version; + uint8_t _reserved1; + uint8_t _reserved2; + uint8_t image_digest[32]; + ets_rsa_pubkey_t key; + uint8_t signature[384]; + uint32_t block_crc; + uint8_t _padding[16]; +}; + +_Static_assert(sizeof(ets_secure_boot_sig_block_t) == 1216, "invalid sig block size"); + +#define SECURE_BOOT_NUM_BLOCKS 3 + +/* V2 Secure boot signature sector (up to 3 blocks) */ +struct ets_secure_boot_signature { + ets_secure_boot_sig_block_t block[SECURE_BOOT_NUM_BLOCKS]; + uint8_t _padding[4096 - (sizeof(ets_secure_boot_sig_block_t) * SECURE_BOOT_NUM_BLOCKS)]; +}; + +_Static_assert(sizeof(ets_secure_boot_signature_t) == 4096, "invalid sig sector size"); + +#define MAX_KEY_DIGESTS 3 + +struct ets_secure_boot_key_digests { + const void *key_digests[MAX_KEY_DIGESTS]; + bool allow_key_revoke; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SECURE_BOOT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/sha.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/sha.h new file mode 100644 index 00000000..54b1b216 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/sha.h @@ -0,0 +1,61 @@ +// Copyright 2020 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. +#ifndef _ROM_SHA_H_ +#define _ROM_SHA_H_ + +#include +#include +#include "ets_sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SHA1 = 0, + SHA2_224, + SHA2_256, + SHA_TYPE_MAX +} SHA_TYPE; + +typedef struct SHAContext { + bool start; + bool in_hardware; // Is this context currently in peripheral? Needs to be manually cleared if multiple SHAs are interleaved + SHA_TYPE type; + uint32_t state[16]; // For SHA1/SHA224/SHA256, used 8, other used 16 + unsigned char buffer[128]; // For SHA1/SHA224/SHA256, used 64, other used 128 + uint32_t total_bits[4]; +} SHA_CTX; + +void ets_sha_enable(void); + +void ets_sha_disable(void); + +ets_status_t ets_sha_init(SHA_CTX *ctx, SHA_TYPE type); + +ets_status_t ets_sha_starts(SHA_CTX *ctx, uint16_t sha512_t); + +void ets_sha_get_state(SHA_CTX *ctx); + +void ets_sha_process(SHA_CTX *ctx, const unsigned char *input); + +void ets_sha_update(SHA_CTX *ctx, const unsigned char *input, uint32_t input_bytes, bool update_ctx); + +ets_status_t ets_sha_finish(SHA_CTX *ctx, unsigned char *output); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SHA_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/spi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/spi_flash.h new file mode 100644 index 00000000..b591d400 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/spi_flash.h @@ -0,0 +1,570 @@ +// Copyright 2020 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. + +#ifndef _ROM_SPI_FLASH_H_ +#define _ROM_SPI_FLASH_H_ + +#include +#include + +#include "esp_attr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup spi_flash_apis, spi flash operation related apis + * @brief spi_flash apis + */ + +/** @addtogroup spi_flash_apis + * @{ + */ + +#define PERIPHS_SPI_FLASH_CMD SPI_MEM_CMD_REG(1) +#define PERIPHS_SPI_FLASH_ADDR SPI_MEM_ADDR_REG(1) +#define PERIPHS_SPI_FLASH_CTRL SPI_MEM_CTRL_REG(1) +#define PERIPHS_SPI_FLASH_CTRL1 SPI_MEM_CTRL1_REG(1) +#define PERIPHS_SPI_FLASH_STATUS SPI_MEM_RD_STATUS_REG(1) +#define PERIPHS_SPI_FLASH_USRREG SPI_MEM_USER_REG(1) +#define PERIPHS_SPI_FLASH_USRREG1 SPI_MEM_USER1_REG(1) +#define PERIPHS_SPI_FLASH_USRREG2 SPI_MEM_USER2_REG(1) +#define PERIPHS_SPI_FLASH_C0 SPI_MEM_W0_REG(1) +#define PERIPHS_SPI_FLASH_C1 SPI_MEM_W1_REG(1) +#define PERIPHS_SPI_FLASH_C2 SPI_MEM_W2_REG(1) +#define PERIPHS_SPI_FLASH_C3 SPI_MEM_W3_REG(1) +#define PERIPHS_SPI_FLASH_C4 SPI_MEM_W4_REG(1) +#define PERIPHS_SPI_FLASH_C5 SPI_MEM_W5_REG(1) +#define PERIPHS_SPI_FLASH_C6 SPI_MEM_W6_REG(1) +#define PERIPHS_SPI_FLASH_C7 SPI_MEM_W7_REG(1) +#define PERIPHS_SPI_FLASH_TX_CRC SPI_MEM_TX_CRC_REG(1) + +#define SPI0_R_QIO_DUMMY_CYCLELEN 5 +#define SPI0_R_QIO_ADDR_BITSLEN 23 +#define SPI0_R_FAST_DUMMY_CYCLELEN 7 +#define SPI0_R_DIO_DUMMY_CYCLELEN 3 +#define SPI0_R_FAST_ADDR_BITSLEN 23 +#define SPI0_R_SIO_ADDR_BITSLEN 23 + +#define SPI1_R_QIO_DUMMY_CYCLELEN 5 +#define SPI1_R_QIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_DUMMY_CYCLELEN 7 +#define SPI1_R_DIO_DUMMY_CYCLELEN 3 +#define SPI1_R_DIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_ADDR_BITSLEN 23 +#define SPI1_R_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_W_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_TWO_BYTE_STATUS_EN SPI_MEM_WRSR_2B + +//SPI address register +#define ESP_ROM_SPIFLASH_BYTES_LEN 24 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_WRITE_NUM 32 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM 16 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_BITS 0xf + +//SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 + +#define FLASH_ID_GD25LQ32C 0xC86016 + +typedef enum { + ESP_ROM_SPIFLASH_QIO_MODE = 0, + ESP_ROM_SPIFLASH_QOUT_MODE, + ESP_ROM_SPIFLASH_DIO_MODE, + ESP_ROM_SPIFLASH_DOUT_MODE, + ESP_ROM_SPIFLASH_FASTRD_MODE, + ESP_ROM_SPIFLASH_SLOWRD_MODE +} esp_rom_spiflash_read_mode_t; + +typedef enum { + ESP_ROM_SPIFLASH_RESULT_OK, + ESP_ROM_SPIFLASH_RESULT_ERR, + ESP_ROM_SPIFLASH_RESULT_TIMEOUT +} esp_rom_spiflash_result_t; + +typedef struct { + uint32_t device_id; + uint32_t chip_size; // chip size in bytes + uint32_t block_size; + uint32_t sector_size; + uint32_t page_size; + uint32_t status_mask; +} esp_rom_spiflash_chip_t; + +typedef struct { + uint8_t data_length; + uint8_t read_cmd0; + uint8_t read_cmd1; + uint8_t write_cmd; + uint16_t data_mask; + uint16_t data; +} esp_rom_spiflash_common_cmd_t; + +/** + * @brief Fix the bug in SPI hardware communication with Flash/Ext-SRAM in High Speed. + * Please do not call this function in SDK. + * + * @param uint8_t spi: 0 for SPI0(Cache Access), 1 for SPI1(Flash read/write). + * + * @param uint8_t freqdiv: Pll is 80M, 4 for 20M, 3 for 26.7M, 2 for 40M, 1 for 80M. + * + * @return None + */ +void esp_rom_spiflash_fix_dummylen(uint8_t spi, uint8_t freqdiv); + +/** + * @brief Select SPI Flash to QIO mode when WP pad is read from Flash. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_qiomode(uint8_t wp_gpio_num, uint32_t ishspi); + +/** + * @brief Set SPI Flash pad drivers. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t *drvs: drvs[0]-bit[3:0] for cpiclk, bit[7:4] for spiq, drvs[1]-bit[3:0] for spid, drvs[1]-bit[7:4] for spid + * drvs[2]-bit[3:0] for spihd, drvs[2]-bit[7:4] for spiwp. + * Values usually read from falsh by rom code, function usually callde by rom code. + * if value with bit(3) set, the value is valid, bit[2:0] is the real value. + * + * @return None + */ +void esp_rom_spiflash_set_drvs(uint8_t wp_gpio_num, uint32_t ishspi, uint8_t *drvs); + +/** + * @brief Select SPI Flash function for pads. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_padsfunc(uint32_t ishspi); + +/** + * @brief SPI Flash init, clock divisor is 4, use 1 line Slow read mode. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t legacy: In legacy mode, more SPI command is used in line. + * + * @return None + */ +void esp_rom_spiflash_attach(uint32_t ishspi, bool legacy); + +/** + * @brief SPI Read Flash status register. We use CMD 0x05 (RDSR). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_status(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief SPI Read Flash status register bits 8-15. We use CMD 0x35 (RDSR2). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_statushigh(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief Write status to Falsh status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t status_value : Value to . + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_status(esp_rom_spiflash_chip_t *spi, uint32_t status_value); + +/** + * @brief Use a command to Read Flash status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t*status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_user_cmd(uint32_t *status, uint8_t cmd); + +/** + * @brief Config SPI Flash read mode when init. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_read_mode_t mode : QIO/QOUT/DIO/DOUT/FastRD/SlowRD. + * + * This function does not try to set the QIO Enable bit in the status register, caller is responsible for this. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_readmode(esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Config SPI Flash clock divisor. + * Please do not call this function in SDK. + * + * @param uint8_t freqdiv: clock divisor. + * + * @param uint8_t spi: 0 for SPI0, 1 for SPI1. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_clk(uint8_t freqdiv, uint8_t spi); + +/** + * @brief Send CommonCmd to Flash so that is can go into QIO mode, some Flash use different CMD. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_common_cmd_t *cmd : A struct to show the action of a command. + * + * @return uint16_t 0 : do not send command any more. + * 1 : go to the next command. + * n > 1 : skip (n - 1) commands. + */ +uint16_t esp_rom_spiflash_common_cmd(esp_rom_spiflash_common_cmd_t *cmd); + +/** + * @brief Unlock SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Unlock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Unlock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Unlock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_unlock(void); + +/** + * @brief SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Lock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Lock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Lock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_lock(void); + +/** + * @brief Update SPI Flash parameter. + * Please do not call this function in SDK. + * + * @param uint32_t deviceId : Device ID read from SPI, the low 32 bit. + * + * @param uint32_t chip_size : The Flash size. + * + * @param uint32_t block_size : The Flash block size. + * + * @param uint32_t sector_size : The Flash sector size. + * + * @param uint32_t page_size : The Flash page size. + * + * @param uint32_t status_mask : The Mask used when read status from Flash(use single CMD). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Update OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Update error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Update timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_param(uint32_t deviceId, uint32_t chip_size, uint32_t block_size, + uint32_t sector_size, uint32_t page_size, uint32_t status_mask); + +/** + * @brief Erase whole flash chip. + * Please do not call this function in SDK. + * + * @param None + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_chip(void); + +/** + * @brief Erase a 64KB block of flash + * Uses SPI flash command D8H. + * Please do not call this function in SDK. + * + * @param uint32_t block_num : Which block to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_block(uint32_t block_num); + +/** + * @brief Erase a sector of flash. + * Uses SPI flash command 20H. + * Please do not call this function in SDK. + * + * @param uint32_t sector_num : Which sector to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_sector(uint32_t sector_num); + +/** + * @brief Erase some sectors. + * Please do not call this function in SDK. + * + * @param uint32_t start_addr : Start addr to erase, should be sector aligned. + * + * @param uint32_t area_len : Length to erase, should be sector aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_area(uint32_t start_addr, uint32_t area_len); + +/** + * @brief Write Data to Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t dest_addr : Address to write, should be 4 bytes aligned. + * + * @param const uint32_t *src : The pointer to data which is to write. + * + * @param uint32_t len : Length to write, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write(uint32_t dest_addr, const uint32_t *src, int32_t len); + +/** + * @brief Read Data from Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t src_addr : Address to read, should be 4 bytes aligned. + * + * @param uint32_t *dest : The buf to read the data. + * + * @param uint32_t len : Length to read, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read(uint32_t src_addr, uint32_t *dest, int32_t len); + +/** + * @brief SPI1 go into encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_enable(void); + +/** + * @brief Prepare 32 Bytes data to encrpto writing, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 bytes aligned. + * + * @param uint32_t *data : The pointer to data which is to write. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Prepare OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Prepare error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Prepare timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_prepare_encrypted_data(uint32_t flash_addr, uint32_t *data); + +/** + * @brief SPI1 go out of encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_disable(void); + +/** + * @brief Write data to flash with transparent encryption. + * @note Sectors to be written should already be erased. + * + * @note Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 byte aligned. + * + * @param uint32_t *data : The pointer to data to write. Note, this pointer must + * be 32 bit aligned and the content of the data will be + * modified by the encryption function. + * + * @param uint32_t len : Length to write, should be 32 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Data written successfully. + * ESP_ROM_SPIFLASH_RESULT_ERR : Encryption write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Encrypto write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_encrypted(uint32_t flash_addr, uint32_t *data, uint32_t len); + + +/* TODO: figure out how to map these to their new names */ +typedef enum { + SPI_ENCRYPT_DESTINATION_FLASH, +} SpiEncryptDest; + +typedef esp_rom_spiflash_result_t SpiFlashOpResult; + +SpiFlashOpResult SPI_Encrypt_Write(uint32_t flash_addr, const void *data, uint32_t len); +SpiFlashOpResult SPI_Encrypt_Write_Dest(SpiEncryptDest dest, uint32_t flash_addr, const void *data, uint32_t len); +void SPI_Write_Encrypt_Enable(void); +void SPI_Write_Encrypt_Disable(void); + +/** @brief Wait until SPI flash write operation is complete + * + * @note Please do not call this function in SDK. + * + * Reads the Write In Progress bit of the SPI flash status register, + * repeats until this bit is zero (indicating write complete). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write is complete + * ESP_ROM_SPIFLASH_RESULT_ERR : Error while reading status. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_wait_idle(esp_rom_spiflash_chip_t *spi); + + +/** @brief Enable Quad I/O pin functions + * + * @note Please do not call this function in SDK. + * + * Sets the HD & WP pin functions for Quad I/O modes, based on the + * efuse SPI pin configuration. + * + * @param wp_gpio_num - Number of the WP pin to reconfigure for quad I/O. + * + * @param spiconfig - Pin configuration, as returned from ets_efuse_get_spiconfig(). + * - If this parameter is 0, default SPI pins are used and wp_gpio_num parameter is ignored. + * - If this parameter is 1, default HSPI pins are used and wp_gpio_num parameter is ignored. + * - For other values, this parameter encodes the HD pin number and also the CLK pin number. CLK pin selection is used + * to determine if HSPI or SPI peripheral will be used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). + * Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral. + */ +void esp_rom_spiflash_select_qio_pins(uint8_t wp_gpio_num, uint32_t spiconfig); + + +typedef void (* spi_flash_func_t)(void); +typedef SpiFlashOpResult (* spi_flash_op_t)(void); +typedef SpiFlashOpResult (* spi_flash_erase_t)(uint32_t); +typedef SpiFlashOpResult (* spi_flash_rd_t)(uint32_t, uint32_t*, int); +typedef SpiFlashOpResult (* spi_flash_wr_t)(uint32_t, const uint32_t*, int); +typedef SpiFlashOpResult (* spi_flash_ewr_t)(uint32_t, const void*, uint32_t); +typedef SpiFlashOpResult (* spi_flash_wren_t)(void*); + +typedef struct { + uint32_t read_sub_len; + uint32_t write_sub_len; + spi_flash_op_t unlock; + spi_flash_erase_t erase_sector; + spi_flash_erase_t erase_block; + spi_flash_rd_t read; + spi_flash_wr_t write; + spi_flash_ewr_t encrypt_write; + spi_flash_func_t check_sus; + spi_flash_wren_t wren; + spi_flash_op_t wait_idle; +} spiflash_legacy_funcs_t; + + +extern const spiflash_legacy_funcs_t *rom_spiflash_legacy_funcs; + +/** @brief Global ROM spiflash data, as used by legacy + SPI flash functions +*/ +typedef struct { + esp_rom_spiflash_chip_t chip; + uint8_t dummy_len_plus[3]; + uint8_t sig_matrix; +} spiflash_legacy_data_t; + +extern spiflash_legacy_data_t *rom_spiflash_legacy_data; + +/* Defines to make the C3 ROM legacvy data access compatible with previous chips */ +#define g_rom_flashchip (rom_spiflash_legacy_data->chip) +#define g_rom_spiflash_dummy_len_plus (rom_spiflash_legacy_data->dummy_len_plus) + +/** + * @brief Clear WEL bit unconditionally. + * + * @return always ESP_ROM_SPIFLASH_RESULT_OK + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_disable(void); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SPI_FLASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/tjpgd.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/tjpgd.h new file mode 100644 index 00000000..80d346a1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/tjpgd.h @@ -0,0 +1,99 @@ +/*----------------------------------------------------------------------------/ +/ TJpgDec - Tiny JPEG Decompressor include file (C)ChaN, 2012 +/----------------------------------------------------------------------------*/ +#ifndef _TJPGDEC +#define _TJPGDEC +/*---------------------------------------------------------------------------*/ +/* System Configurations */ + +#define JD_SZBUF 512 /* Size of stream input buffer */ +#define JD_FORMAT 0 /* Output pixel format 0:RGB888 (3 BYTE/pix), 1:RGB565 (1 WORD/pix) */ +#define JD_USE_SCALE 1 /* Use descaling feature for output */ +#define JD_TBLCLIP 1 /* Use table for saturation (might be a bit faster but increases 1K bytes of code size) */ + +/*---------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/* These types must be 16-bit, 32-bit or larger integer */ +typedef int INT; +typedef unsigned int UINT; + +/* These types must be 8-bit integer */ +typedef char CHAR; +typedef unsigned char UCHAR; +typedef unsigned char BYTE; + +/* These types must be 16-bit integer */ +typedef short SHORT; +typedef unsigned short USHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types must be 32-bit integer */ +typedef long LONG; +typedef unsigned long ULONG; +typedef unsigned long DWORD; + + +/* Error code */ +typedef enum { + JDR_OK = 0, /* 0: Succeeded */ + JDR_INTR, /* 1: Interrupted by output function */ + JDR_INP, /* 2: Device error or wrong termination of input stream */ + JDR_MEM1, /* 3: Insufficient memory pool for the image */ + JDR_MEM2, /* 4: Insufficient stream input buffer */ + JDR_PAR, /* 5: Parameter error */ + JDR_FMT1, /* 6: Data format error (may be damaged data) */ + JDR_FMT2, /* 7: Right format but not supported */ + JDR_FMT3 /* 8: Not supported JPEG standard */ +} JRESULT; + + + +/* Rectangular structure */ +typedef struct { + WORD left, right, top, bottom; +} JRECT; + + + +/* Decompressor object structure */ +typedef struct JDEC JDEC; +struct JDEC { + UINT dctr; /* Number of bytes available in the input buffer */ + BYTE *dptr; /* Current data read ptr */ + BYTE *inbuf; /* Bit stream input buffer */ + BYTE dmsk; /* Current bit in the current read byte */ + BYTE scale; /* Output scaling ratio */ + BYTE msx, msy; /* MCU size in unit of block (width, height) */ + BYTE qtid[3]; /* Quantization table ID of each component */ + SHORT dcv[3]; /* Previous DC element of each component */ + WORD nrst; /* Restart inverval */ + UINT width, height; /* Size of the input image (pixel) */ + BYTE *huffbits[2][2]; /* Huffman bit distribution tables [id][dcac] */ + WORD *huffcode[2][2]; /* Huffman code word tables [id][dcac] */ + BYTE *huffdata[2][2]; /* Huffman decoded data tables [id][dcac] */ + LONG *qttbl[4]; /* Dequaitizer tables [id] */ + void *workbuf; /* Working buffer for IDCT and RGB output */ + BYTE *mcubuf; /* Working buffer for the MCU */ + void *pool; /* Pointer to available memory pool */ + UINT sz_pool; /* Size of momory pool (bytes available) */ + UINT (*infunc)(JDEC *, BYTE *, UINT); /* Pointer to jpeg stream input function */ + void *device; /* Pointer to I/O device identifiler for the session */ +}; + + + +/* TJpgDec API functions */ +JRESULT jd_prepare (JDEC *, UINT(*)(JDEC *, BYTE *, UINT), void *, UINT, void *); +JRESULT jd_decomp (JDEC *, UINT(*)(JDEC *, void *, JRECT *), BYTE); + + +#ifdef __cplusplus +} +#endif + +#endif /* _TJPGDEC */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/uart.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/uart.h new file mode 100644 index 00000000..adbae64d --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32c3/rom/uart.h @@ -0,0 +1,440 @@ +// Copyright 2020 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. + +#ifndef _ROM_UART_H_ +#define _ROM_UART_H_ + +#include "esp_types.h" +#include "esp_attr.h" +#include "ets_sys.h" +#include "soc/soc.h" +#include "soc/uart_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + +#define RX_BUFF_SIZE 0x400 +#define TX_BUFF_SIZE 100 + +//uart int enalbe register ctrl bits +#define UART_RCV_INTEN BIT0 +#define UART_TRX_INTEN BIT1 +#define UART_LINE_STATUS_INTEN BIT2 + +//uart int identification ctrl bits +#define UART_INT_FLAG_MASK 0x0E + +//uart fifo ctrl bits +#define UART_CLR_RCV_FIFO BIT1 +#define UART_CLR_TRX_FIFO BIT2 +#define UART_RCVFIFO_TRG_LVL_BITS BIT6 + +//uart line control bits +#define UART_DIV_LATCH_ACCESS_BIT BIT7 + +//uart line status bits +#define UART_RCV_DATA_RDY_FLAG BIT0 +#define UART_RCV_OVER_FLOW_FLAG BIT1 +#define UART_RCV_PARITY_ERR_FLAG BIT2 +#define UART_RCV_FRAME_ERR_FLAG BIT3 +#define UART_BRK_INT_FLAG BIT4 +#define UART_TRX_FIFO_EMPTY_FLAG BIT5 +#define UART_TRX_ALL_EMPTY_FLAG BIT6 // include fifo and shift reg +#define UART_RCV_ERR_FLAG BIT7 + +//send and receive message frame head +#define FRAME_FLAG 0x7E + +typedef enum { + UART_LINE_STATUS_INT_FLAG = 0x06, + UART_RCV_FIFO_INT_FLAG = 0x04, + UART_RCV_TMOUT_INT_FLAG = 0x0C, + UART_TXBUFF_EMPTY_INT_FLAG = 0x02 +} UartIntType; //consider bit0 for int_flag + +typedef enum { + RCV_ONE_BYTE = 0x0, + RCV_FOUR_BYTE = 0x1, + RCV_EIGHT_BYTE = 0x2, + RCV_FOURTEEN_BYTE = 0x3 +} UartRcvFifoTrgLvl; + +typedef enum { + FIVE_BITS = 0x0, + SIX_BITS = 0x1, + SEVEN_BITS = 0x2, + EIGHT_BITS = 0x3 +} UartBitsNum4Char; + +typedef enum { + ONE_STOP_BIT = 1, + ONE_HALF_STOP_BIT = 2, + TWO_STOP_BIT = 3 +} UartStopBitsNum; + +typedef enum { + NONE_BITS = 0, + ODD_BITS = 2, + EVEN_BITS = 3 + +} UartParityMode; + +typedef enum { + STICK_PARITY_DIS = 0, + STICK_PARITY_EN = 2 +} UartExistParity; + +typedef enum { + BIT_RATE_9600 = 9600, + BIT_RATE_19200 = 19200, + BIT_RATE_38400 = 38400, + BIT_RATE_57600 = 57600, + BIT_RATE_115200 = 115200, + BIT_RATE_230400 = 230400, + BIT_RATE_460800 = 460800, + BIT_RATE_921600 = 921600 +} UartBautRate; + +typedef enum { + NONE_CTRL, + HARDWARE_CTRL, + XON_XOFF_CTRL +} UartFlowCtrl; + +typedef enum { + EMPTY, + UNDER_WRITE, + WRITE_OVER +} RcvMsgBuffState; + +typedef struct { + uint8_t *pRcvMsgBuff; + uint8_t *pWritePos; + uint8_t *pReadPos; + uint8_t TrigLvl; + RcvMsgBuffState BuffState; +} RcvMsgBuff; + +typedef struct { + uint32_t TrxBuffSize; + uint8_t *pTrxBuff; +} TrxMsgBuff; + +typedef enum { + BAUD_RATE_DET, + WAIT_SYNC_FRM, + SRCH_MSG_HEAD, + RCV_MSG_BODY, + RCV_ESC_CHAR, +} RcvMsgState; + +typedef struct { + UartBautRate baut_rate; + UartBitsNum4Char data_bits; + UartExistParity exist_parity; + UartParityMode parity; // chip size in byte + UartStopBitsNum stop_bits; + UartFlowCtrl flow_ctrl; + uint8_t buff_uart_no; //indicate which uart use tx/rx buffer + RcvMsgBuff rcv_buff; +// TrxMsgBuff trx_buff; + RcvMsgState rcv_state; + int received; +} UartDevice; + +/** + * @brief Init uart device struct value and reset uart0/uart1 rx. + * Please do not call this function in SDK. + * + * @param rxBuffer, must be a pointer to RX_BUFF_SIZE bytes or NULL + * + * @return None + */ +void uartAttach(void *rxBuffer); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, else for UART1. + * + * @param uint32_t clock : clock used by uart module, to adjust baudrate. + * + * @return None + */ +void Uart_Init(uint8_t uart_no, uint32_t clock); + +/** + * @brief Modify uart baudrate. + * This function will reset RX/TX fifo for uart. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint32_t DivLatchValue : (clock << 4)/baudrate. + * + * @return None + */ +void uart_div_modify(uint8_t uart_no, uint32_t DivLatchValue); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint8_t is_sync : 0, only one UART module, easy to detect, wait until detected; + * 1, two UART modules, hard to detect, detect and return. + * + * @return None + */ +int uart_baudrate_detect(uint8_t uart_no, uint8_t is_sync); + +/** + * @brief Switch printf channel of uart_tx_one_char. + * Please do not call this function when printf. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_tx_switch(uint8_t uart_no); + +/** + * @brief Switch message exchange channel for UART download booting. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_buff_switch(uint8_t uart_no); + +/** + * @brief Output a char to printf channel, wait until fifo not full. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char(uint8_t TxChar); + +/** + * @brief Output a char to message exchange channel, wait until fifo not full. + * Please do not call this function in SDK. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char2(uint8_t TxChar); + +/** + * @brief Wait until uart tx full empty. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None. + */ +void uart_tx_flush(uint8_t uart_no); + +/** + * @brief Wait until uart tx full empty and the last char send ok. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2 + * + * The function defined in ROM code has a bug, so we define the correct version + * here for compatibility. + */ +void uart_tx_wait_idle(uint8_t uart_no); + +/** + * @brief Get an input char from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pRxChar : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_one_char(uint8_t *pRxChar); + +/** + * @brief Get an input char from message channel, wait until successful. + * Please do not call this function in SDK. + * + * @param None + * + * @return char : input char value. + */ +char uart_rx_one_char_block(void); + +/** + * @brief Get an input string line from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pString : the pointer to store the string. + * + * @param uint8_t MaxStrlen : the max string length, incude '\0'. + * + * @return OK. + */ +STATUS UartRxString(uint8_t *pString, uint8_t MaxStrlen); + +/** + * @brief Process uart recevied information in the interrupt handler. + * Please do not call this function in SDK. + * + * @param void *para : the message receive buffer. + * + * @return None + */ +void uart_rx_intr_handler(void *para); + +/** + * @brief Get an char from receive buffer. + * Please do not call this function in SDK. + * + * @param RcvMsgBuff *pRxBuff : the pointer to the struct that include receive buffer. + * + * @param uint8_t *pRxByte : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_readbuff( RcvMsgBuff *pRxBuff, uint8_t *pRxByte); + +/** + * @brief Get all chars from receive buffer. + * Please do not call this function in SDK. + * + * @param uint8_t *pCmdLn : the pointer to store the string. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS UartGetCmdLn(uint8_t *pCmdLn); + +/** + * @brief Get uart configuration struct. + * Please do not call this function in SDK. + * + * @param None + * + * @return UartDevice * : uart configuration struct pointer. + */ +UartDevice *GetUartDevice(void); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to output string. + * + * @param int len : the string length. + * + * @return None. + */ +void send_packet(uint8_t *p, int len); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to input string. + * + * @param int len : If string length > len, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return int : the length of the string. + */ +int recv_packet(uint8_t *p, int len, uint8_t is_sync); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t DataLen : the string length. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS SendMsg(uint8_t *pData, uint16_t DataLen); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t MaxDataLen : If string length > MaxDataLen, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS RcvMsg(uint8_t *pData, uint16_t MaxDataLen, uint8_t is_sync); + +/** + * @brief Check if this UART is in download connection. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return ETS_NO_BOOT = 0 for no. + * SEL_UART_BOOT = BIT(1) for yes. + */ +uint8_t UartConnCheck(uint8_t uart_no); + +/** + * @brief Initialize the USB ACM UART + * Needs to be fed a buffer of at least 128 bytes, plus any rx buffer you may want to have. + * + * @param cdc_acm_work_mem Pointer to work mem for CDC-ACM code + * @param cdc_acm_work_mem_len Length of work mem + */ +void Uart_Init_USB(void *cdc_acm_work_mem, int cdc_acm_work_mem_len); + + +/** + * @brief Install handler to reset the chip when a RTS change has been detected on the CDC-ACM 'UART'. + */ +void uart_usb_enable_reset_on_rts(void); + + +extern UartDevice UartDev; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_UART_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/aes.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/aes.h new file mode 100644 index 00000000..9350e251 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/aes.h @@ -0,0 +1,62 @@ +/* + ROM functions for hardware AES support. + + It is not recommended to use these functions directly, + use the wrapper functions in hwcrypto/aes.h instead. + + */ +// Copyright 2015-2016 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define AES_BLOCK_SIZE 16 + +enum AES_TYPE { + AES_ENC, + AES_DEC, +}; + +enum AES_BITS { + AES128, + AES192, + AES256 +}; + +void ets_aes_enable(void); + +void ets_aes_disable(void); + +void ets_aes_set_endian(bool key_word_swap, bool key_byte_swap, + bool in_word_swap, bool in_byte_swap, + bool out_word_swap, bool out_byte_swap); + +int ets_aes_setkey(enum AES_TYPE type, const void *key, enum AES_BITS bits); + +int ets_aes_setkey_enc(const void *key, enum AES_BITS bits); + +int ets_aes_setkey_dec(const void *key, enum AES_BITS bits); + +void ets_aes_block(const void *input, void *output); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/bigint.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/bigint.h new file mode 100644 index 00000000..eee19d46 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/bigint.h @@ -0,0 +1,50 @@ +/* + ROM functions for hardware bigint support. + + It is not recommended to use these functions directly, + use the wrapper functions in hwcrypto/mpi.h instead. + + */ +// Copyright 2015-2016 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. + +#ifndef _ROM_BIGINT_H_ +#define _ROM_BIGINT_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void ets_bigint_enable(void); + +void ets_bigint_disable(void); + +int ets_bigint_multiply(const uint32_t *x, const uint32_t *y, uint32_t len_words); + +int ets_bigint_modmult(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, uint32_t len_words); + +int ets_bigint_modexp(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, bool constant_time, uint32_t len_words); + +void ets_bigint_wait_finish(void); + +int ets_bigint_getz(uint32_t *z, uint32_t len_words); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_BIGINT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/cache.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/cache.h new file mode 100644 index 00000000..cc85512f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/cache.h @@ -0,0 +1,947 @@ +// Copyright 2015-2016 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. + +#ifndef _ROM_CACHE_H_ +#define _ROM_CACHE_H_ + + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup cache_apis, cache operation related apis + * @brief cache apis + */ + +/** @addtogroup cache_apis + * @{ + */ + +#define MIN_CACHE_SIZE 8192 +#define MAX_CACHE_SIZE 16384 +#define MIN_CACHE_WAYS 4 +#define MAX_CACHE_WAYS 4 +#define MIN_CACHE_LINE_SIZE 16 +//normally should be (MAX_CACHE_SIZE / MIN_CACHE_WAYS / MIN_CACHE_LINE_SIZE), however, the items not all in one tag memory block. +#define MAX_TAG_BLOCK_ITEMS (MAX_CACHE_SIZE / 8 / MIN_CACHE_LINE_SIZE) +#define TAG_SIZE 4 +#define MAX_TAG_BLOCK_SIZE (MAX_TAG_BLOCK_ITEMS * TAG_SIZE) + +#define INVALID_PHY_PAGE 0xffff +#define ESP_CACHE_TEMP_ADDR DROM0_ADDRESS_LOW +#define CACHE_MAX_OPERATION_SIZE BUS_ADDR_SIZE + + +typedef enum { + CACHE_DCACHE = 0, + CACHE_ICACHE = 1, +} cache_t; + +typedef enum { + CACHE_MEMORY_INVALID = 0, + CACHE_MEMORY_ICACHE_LOW = 1<<0, + CACHE_MEMORY_ICACHE_HIGH = 1<<1, + CACHE_MEMORY_DCACHE_LOW = 1<<2, + CACHE_MEMORY_DCACHE_HIGH = 1<<3, +} cache_layout_t; + +#define CACHE_SIZE_8KB CACHE_SIZE_HALF +#define CACHE_SIZE_16KB CACHE_SIZE_FULL +typedef enum { + CACHE_SIZE_HALF = 0, /*!< 8KB for icache and dcache */ + CACHE_SIZE_FULL = 1, /*!< 16KB for icache and dcache */ +} cache_size_t; + +typedef enum { + CACHE_4WAYS_ASSOC = 0, /*!< 4 way associated cache */ +} cache_ways_t; + +typedef enum { + CACHE_LINE_SIZE_16B = 0, /*!< 16 Byte cache line size */ + CACHE_LINE_SIZE_32B = 1, /*!< 32 Byte cache line size */ +} cache_line_size_t; + +typedef enum { + CACHE_AUTOLOAD_POSITIVE = 0, /*!< cache autoload step is positive */ + CACHE_AUTOLOAD_NEGATIVE = 1, /*!< cache autoload step is negative */ +} cache_autoload_order_t; + +#define CACHE_AUTOLOAD_STEP(i) ((i) - 1) + +typedef enum { + CACHE_AUTOLOAD_MISS_TRIGGER = 0, /*!< autoload only triggered by cache miss */ + CACHE_AUTOLOAD_HIT_TRIGGER = 1, /*!< autoload only triggered by cache hit */ + CACHE_AUTOLOAD_BOTH_TRIGGER = 2, /*!< autoload triggered both by cache miss and hit */ +} cache_autoload_trigger_t; + +struct cache_mode { + uint32_t cache_size; /*!< cache size in byte */ + uint16_t cache_line_size; /*!< cache line size in byte */ + uint8_t cache_ways; /*!< cache ways, always 4 */ + uint8_t icache; /*!< the cache index, 0 for dcache, 1 for icache */ +}; + +struct tag_item { + uint32_t dirty:1; /*!< the cache line value is dirty or not */ + uint32_t tag:14; /*!< the tag is the high part of the cache address, however is only 16MB range, and with out low part */ + uint32_t valid:1; /*!< the tag item is valid or not */ + uint32_t fifo_cnt:3; /*!< fifo cnt, 0 ~ 3 for 4 ways cache, 0 ~ 7 for 8 ways cache */ + uint32_t lock:1; /*!< the cache line is locked or not */ + uint32_t attr:3; /*!< the attribute of the external memory physical address */ + uint32_t access:1; /*!< software accessable, used by hardware */ + uint32_t reserved:8; +}; + +struct autoload_config { + uint8_t order; /*!< autoload step is positive or negative */ + uint8_t trigger; /*!< autoload trigger */ + uint8_t ena0; /*!< autoload region0 enable */ + uint8_t ena1; /*!< autoload region1 enable */ + uint32_t addr0; /*!< autoload region0 start address */ + uint32_t size0; /*!< autoload region0 size */ + uint32_t addr1; /*!< autoload region1 start address */ + uint32_t size1; /*!< autoload region1 size */ +}; + +struct tag_group_info { + struct cache_mode mode; /*!< cache and cache mode */ + uint32_t filter_addr; /*!< the address that used to generate the struct */ + uint32_t vaddr_offset; /*!< virtual address offset of the cache ways */ + uint32_t tag_addr[MAX_CACHE_WAYS]; /*!< tag memory address, only [0~mode.ways-1] is valid to use */ + uint32_t cache_memory_offset[MAX_CACHE_WAYS]; /*!< cache memory address, only [0~mode.ways-1] is valid to use */ +}; + +struct lock_config { + uint32_t addr; /*!< manual lock address*/ + uint16_t size; /*!< manual lock size*/ + uint16_t group; /*!< manual lock group, 0 or 1*/ +}; + +#define ESP_ROM_ERR_INVALID_ARG 1 +#define MMU_SET_ADDR_ALIGNED_ERROR 2 +#define MMU_SET_PASE_SIZE_ERROR 3 +#define MMU_SET_VADDR_OUT_RANGE 4 + +/** + * @brief Initialise cache mmu, mark all entries as invalid. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_MMU_Init(void); + +/** + * @brief Set ICache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be Iram0,Iram1,Irom0,Drom0 and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of ICache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + * + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Ibus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Set DCache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be DRam0, DRam1, DRom0, DPort and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of DCache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Dbus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Count the pages in the bus room address which map to Flash. + * Please do not call this function in your SDK application. + * + * @param uint32_t bus : the bus to count with. + * + * @param uint32_t * page0_mapped : value should be initial by user, 0 for not mapped, other for mapped count. + * + * return uint32_t : the number of pages which map to Flash. + */ +uint32_t Cache_Count_Flash_Pages(uint32_t bus, uint32_t * page0_mapped); + +/** + * @brief Copy Instruction or rodata from Flash to SPIRAM, and remap to SPIRAM. + * Please do not call this function in your SDK application. + * + * @param uint32_t bus : the bus which need to copy to SPIRAM. + * + * @param uint32_t bus_start_addr : the start virtual address for the bus. + * + * @param uint32_t start_page : the start (64KB) page number in SPIRAM. + * + * @param uint32_t * page0_page : the flash page0 in SPIRAM page number, 0xffff for invalid. + * + * return uint32_t : the next start page number for SPIRAM not mapped. + */ +uint32_t Cache_Flash_To_SPIRAM_Copy(uint32_t bus, uint32_t bus_start_addr, uint32_t start_page, uint32_t * page0_page); + + +/** + * @brief allocate memory to used by ICache and DCache. + * Please do not call this function in your SDK application. + * + * @param cache_layout_t sram0_layout : the usage of first 8KB internal memory block, can be CACHE_MEMORY_INVALID, CACHE_MEMORY_ICACHE_LOW, CACHE_MEMORY_ICACHE_HIGH, CACHE_MEMORY_DCACHE_LOW and CACHE_MEMORY_DCACHE_HIGH + * + * @param cache_layout_t sram1_layout : the usage of second 8KB internal memory block + * + * @param cache_layout_t sram2_layout : the usage of third 8KB internal memory block + * + * @param cache_layout_t sram3_layout : the usage of forth 8KB internal memory block + * + * return none + */ +void Cache_Allocate_SRAM(cache_layout_t sram0_layout, cache_layout_t sram1_layout, cache_layout_t sram2_layout, cache_layout_t sram3_layout); + +/** + * @brief Get cache mode of ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the pointer of cache mode struct, caller should set the icache field + * + * return none + */ +void Cache_Get_Mode(struct cache_mode * mode); + +/** + * @brief set ICache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_HALF and CACHE_SIZE_FULL + * + * @param cache_ways_t ways : the associate ways of cache, can only be CACHE_4WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B + * + * return none + */ +void Cache_Set_ICache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief set DCache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_HALF and CACHE_SIZE_FULL + * + * @param cache_ways_t ways : the associate ways of cache, can only be CACHE_4WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B + * + * return none + */ +void Cache_Set_DCache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief check if the address is accessed through ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through ICache, 0 if not. + */ +uint32_t Cache_Address_Through_ICache(uint32_t addr); + +/** + * @brief check if the address is accessed through DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through DCache, 0 if not. + */ +uint32_t Cache_Address_Through_DCache(uint32_t addr); + +/** + * @brief Invalidate the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to invalidate + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Invalidate_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Invalidate the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to invalidate + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Invalidate_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Clean the dirty bit of cache Items of DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to Clean + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Clean_Items(uint32_t addr, uint32_t items); + +/** + * @brief Write back the cache items of DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to write back + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_WriteBack_Items(uint32_t addr, uint32_t items); + +/** + * @brief Invalidate the Cache items in the region from ICache or DCache. + * If the region is not in Cache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : invalidated region start address. + * + * @param uint32_t size : invalidated region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Invalidate_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Clean the dirty bit of Cache items in the region from DCache. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : cleaned region start address. + * + * @param uint32_t size : cleaned region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Clean_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Writeback the Cache items(also clean the dirty bit) in the region from DCache. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : writeback region start address. + * + * @param uint32_t size : writeback region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_WriteBack_Addr(uint32_t addr, uint32_t size); + + +/** + * @brief Invalidate all cache items in ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Invalidate_ICache_All(void); + +/** + * @brief Invalidate all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Invalidate_DCache_All(void); + +/** + * @brief Clean the dirty bit of all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Clean_All(void); + +/** + * @brief WriteBack all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_WriteBack_All(void); + +/** + * @brief Mask all buses through ICache and DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Mask_All(void); + +/** + * @brief UnMask DRom0 bus through ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_UnMask_Drom0(void); + +/** + * @brief Suspend ICache auto preload operation, then you can resume it after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache not auto preload before suspend. + */ +uint32_t Cache_Suspend_ICache_Autoload(void); + +/** + * @brief Resume ICache auto preload operation after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before suspend. + * + * @return None. + */ +void Cache_Resume_ICache_Autoload(uint32_t autoload); + +/** + * @brief Suspend DCache auto preload operation, then you can resume it after some DCache operations. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for DCache not auto preload before suspend. + */ +uint32_t Cache_Suspend_DCache_Autoload(void); + +/** + * @brief Resume DCache auto preload operation after some DCache operations. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for DCache not auto preload before suspend. + * + * @return None. + */ +void Cache_Resume_DCache_Autoload(uint32_t autoload); + +/** + * @brief Start an ICache manual preload, will suspend auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of the preload region. + * + * @param uint32_t size : size of the preload region, should not exceed the size of ICache. + * + * @param uint32_t order : the preload order, 0 for positive, other for negative + * + * @return uint32_t : 0 for ICache not auto preload before manual preload. + */ +uint32_t Cache_Start_ICache_Preload(uint32_t addr, uint32_t size, uint32_t order); + +/** + * @brief Return if the ICache manual preload done. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache manual preload not done. + */ +uint32_t Cache_ICache_Preload_Done(void); + +/** + * @brief End the ICache manual preload to resume auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before manual preload. + * + * @return None + */ +void Cache_End_ICache_Preload(uint32_t autoload); + +/** + * @brief Start an DCache manual preload, will suspend auto preload of DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of the preload region. + * + * @param uint32_t size : size of the preload region, should not exceed the size of DCache. + * + * @param uint32_t order : the preload order, 0 for positive, other for negative + * + * @return uint32_t : 0 for DCache not auto preload before manual preload. + */ +uint32_t Cache_Start_DCache_Preload(uint32_t addr, uint32_t size, uint32_t order); + +/** + * @brief Return if the DCache manual preload done. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for DCache manual preload not done. + */ +uint32_t Cache_DCache_Preload_Done(void); + +/** + * @brief End the DCache manual preload to resume auto preload of DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for DCache not auto preload before manual preload. + * + * @return None + */ +void Cache_End_DCache_Preload(uint32_t autoload); + +/** + * @brief Config autoload parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct autoload_config * config : autoload parameters. + * + * @return None + */ +void Cache_Config_ICache_Autoload(const struct autoload_config * config); + +/** + * @brief Enable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Enable_ICache_Autoload(void); + +/** + * @brief Disable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Disable_ICache_Autoload(void); + +/** + * @brief Config autoload parameters of DCache. + * Please do not call this function in your SDK application. + * + * @param struct autoload_config * config : autoload parameters. + * + * @return None + */ +void Cache_Config_DCache_Autoload(const struct autoload_config * config); + +/** + * @brief Enable auto preload for DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Enable_DCache_Autoload(void); + +/** + * @brief Disable auto preload for DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Disable_DCache_Autoload(void); + +/** + * @brief Config a group of prelock parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct lock_config * config : a group of lock parameters. + * + * @return None + */ + +void Cache_Enable_ICache_PreLock(const struct lock_config *config); + +/** + * @brief Disable a group of prelock parameters for ICache. + * However, the locked data will not be released. + * Please do not call this function in your SDK application. + * + * @param uint16_t group : 0 for group0, 1 for group1. + * + * @return None + */ +void Cache_Disable_ICache_PreLock(uint16_t group); + +/** + * @brief Lock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to lock + * + * @param uint32_t items: cache lines to lock, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Lock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Unlock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to unlock + * + * @param uint32_t items: cache lines to unlock, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Unlock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Config a group of prelock parameters of DCache. + * Please do not call this function in your SDK application. + * + * @param struct lock_config * config : a group of lock parameters. + * + * @return None + */ +void Cache_Enable_DCache_PreLock(const struct lock_config *config); + +/** + * @brief Disable a group of prelock parameters for DCache. + * However, the locked data will not be released. + * Please do not call this function in your SDK application. + * + * @param uint16_t group : 0 for group0, 1 for group1. + * + * @return None + */ +void Cache_Disable_DCache_PreLock(uint16_t group); + +/** + * @brief Lock the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to lock + * + * @param uint32_t items: cache lines to lock, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Lock_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Unlock the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to unlock + * + * @param uint32_t items: cache lines to unlock, items * cache_line_size should not exceed the bus address size(4MB) + * + * @return None + */ +void Cache_Unlock_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Lock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of lock region. + * + * @param uint32_t size : size of lock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Lock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Unlock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of unlock region. + * + * @param uint32_t size : size of unlock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Unlock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Disable ICache access for the cpu. + * This operation will make all ICache tag memory invalid, CPU can't access ICache, ICache will keep idle. + * Please do not call this function in your SDK application. + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Disable_ICache(void); + +/** + * @brief Enable ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Enable_ICache(uint32_t autoload); + +/** + * @brief Disable DCache access for the cpu. + * This operation will make all DCache tag memory invalid, CPU can't access DCache, DCache will keep idle + * Please do not call this function in your SDK application. + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Disable_DCache(void); + +/** + * @brief Enable DCache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : DCache will preload then. + * + * @return None + */ +void Cache_Enable_DCache(uint32_t autoload); + +/** + * @brief Suspend ICache access for the cpu. + * The ICache tag memory is still there, CPU can't access ICache, ICache will keep idle. + * Please do not change MMU, cache mode or tag memory(tag memory can be changed in some special case). + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Suspend_ICache(void); + +/** + * @brief Resume ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Resume_ICache(uint32_t autoload); + +/** + * @brief Suspend DCache access for the cpu. + * The ICache tag memory is still there, CPU can't access DCache, DCache will keep idle. + × Please do not change MMU, cache mode or tag memory(tag memory can be changed in some special case). + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Suspend_DCache(void); + +/** + * @brief Resume DCache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : DCache will preload then. + * + * @return None + */ +void Cache_Resume_DCache(uint32_t autoload); + +/** + * @brief Get ICache cache line size + * + * @param None + * + * @return uint32_t: 16, 32 Byte + */ +uint32_t Cache_Get_ICache_Line_Size(void); + +/** + * @brief Get DCache cache line size + * + * @param None + * + * @return uint32_t: 16, 32 Byte + */ +uint32_t Cache_Get_DCache_Line_Size(void); + +/** + * @brief Set default mode from boot, 8KB ICache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Set_Default_Mode(void); + +/** + * @brief Set default mode from boot, 8KB DCache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Enable_Defalut_DCache_Mode(void); + +/** + * @brief Travel tag memory to run a call back function. + * ICache and DCache are suspend when doing this. + * The callback will get the parameter tag_group_info, which will include a group of tag memory addresses and cache memory addresses. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to check and the cache mode. + * + * @param uint32_t filter_addr : only the cache lines which may include the filter_address will be returned to the call back function. + * 0 for do not filter, all cache lines will be returned. + * + * @param void (* process)(struct tag_group_info *) : call back function, which may be called many times, a group(the addresses in the group are in the same position in the cache ways) a time. + * + * @return None + */ +void Cache_Travel_Tag_Memory(struct cache_mode * mode, uint32_t filter_addr, void (* process)(struct tag_group_info *)); + +/** + * @brief Get the virtual address from cache mode, cache tag and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t tag : the tag part fo a tag item, 12-14 bits. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Virtual_Addr(struct cache_mode *mode, uint32_t tag, uint32_t vaddr_offset); + +/** + * @brief Get cache memory block base address. + * Please do not call this function in your SDK application. + * + * @param uint32_t icache : 0 for dcache, other for icache. + * + * @param uint32_t high : 0 for low part block, 1 for high part block. + * + * @return uint32_t : the cache memory block base address, 0 if the block not used. + */ +uint32_t Cache_Get_Memory_BaseAddr(uint32_t icache, uint32_t high); + +/** + * @brief Get the cache memory address from cache mode, cache memory offset and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t cache_memory_offset : the cache memory offset of the whole cache (ICache or DCache) for the cache line. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Memory_Addr(struct cache_mode *mode, uint32_t cache_memory_offset, uint32_t vaddr_offset); + +/** + * @brief Get the cache memory value by DRAM address. + * Please do not call this function in your SDK application. + * + * @param uint32_t cache_memory_addr : DRAM address for the cache memory. + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_Memory_value(uint32_t cache_memory_addr); +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_CACHE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/crc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/crc.h new file mode 100644 index 00000000..0d139795 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/crc.h @@ -0,0 +1,88 @@ +// Copyright 2015-2016 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. + +#ifndef ROM_CRC_H +#define ROM_CRC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup crc_apis, uart configuration and communication related apis + * @brief crc apis + */ + +/** @addtogroup crc_apis + * @{ + */ + + +/* Standard CRC8/16/32 algorithms. */ +// CRC-8 x8+x2+x1+1 0x07 +// CRC16-CCITT x16+x12+x5+1 1021 ISO HDLC, ITU X.25, V.34/V.41/V.42, PPP-FCS +// CRC32: +//G(x) = x32 +x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x1 + 1 +//If your buf is not continuous, you can use the first result to be the second parameter. + +/** + * @brief Crc32 value that is in little endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc16 value that is in little endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc8 value that is in little endian. + * + * @param uint8_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/digital_signature.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/digital_signature.h new file mode 100644 index 00000000..9f23a5d6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/digital_signature.h @@ -0,0 +1,147 @@ +/* + ROM functions for hardware Digital Signature peripheral verification +*/ +// Copyright 2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define ETS_DS_IV_LEN 16 + +/* Length of parameter 'C' stored in flash */ +#define ETS_DS_C_LEN (12672 / 8) + +/* Encrypted ETS data. Recommended to store in flash in this format. + */ +typedef struct { + /* RSA LENGTH register parameters + * (number of words in RSA key & operands, minus one). + * + * Max value 127 (for RSA 4096). + * + * This value must match the length field encrypted and stored in 'c', + * or invalid results will be returned. (The DS peripheral will + * always use the value in 'c', not this value, so an attacker can't + * alter the DS peripheral results this way, it will just truncate or + * extend the message and the resulting signature in software.) + */ + unsigned rsa_length; + + /* IV value used to encrypt 'c' */ + uint8_t iv[ETS_DS_IV_LEN]; + + /* Encrypted Digital Signature parameters. Result of AES-CBC encryption + of plaintext values. Includes an encrypted message digest. + */ + uint8_t c[ETS_DS_C_LEN]; +} ets_ds_data_t; + +typedef enum { + ETS_DS_OK, + ETS_DS_INVALID_PARAM, /* Supplied parameters are invalid */ + ETS_DS_INVALID_KEY, /* HMAC peripheral failed to supply key */ + ETS_DS_INVALID_PADDING, /* 'c' decrypted with invalid padding */ + ETS_DS_INVALID_DIGEST, /* 'c' decrypted with invalid digest */ +} ets_ds_result_t; + +void ets_ds_enable(void); + +void ets_ds_disable(void); + + +/* + * @brief Start signing a message (or padded message digest) using the Digital Signature peripheral + * + * - @param message Pointer to message (or padded digest) containing the message to sign. Should be + * (data->rsa_length + 1)*4 bytes long. @param data Pointer to DS data. Can be a pointer to data + * in flash. + * + * Caller must have already called ets_ds_enable() and ets_hmac_calculate_downstream() before calling + * this function, and is responsible for calling ets_ds_finish_sign() and then + * ets_hmac_invalidate_downstream() afterwards. + * + * @return ETS_DS_OK if signature is in progress, ETS_DS_INVALID_PARAM if param is invalid, + * EST_DS_INVALID_KEY if key or HMAC peripheral is configured incorrectly. + */ +ets_ds_result_t ets_ds_start_sign(const void *message, const ets_ds_data_t *data); + + +/* + * @brief Returns true if the DS peripheral is busy following a call to ets_ds_start_sign() + * + * A result of false indicates that a call to ets_ds_finish_sign() will not block. + * + * Only valid if ets_ds_enable() has been called. + */ +bool ets_ds_is_busy(void); + + +/* @brief Finish signing a message using the Digital Signature peripheral + * + * Must be called after ets_ds_start_sign(). Can use ets_ds_busy() to wait until + * peripheral is no longer busy. + * + * - @param signature Pointer to buffer to contain the signature. Should be + * (data->rsa_length + 1)*4 bytes long. + * - @param data Should match the 'data' parameter passed to ets_ds_start_sign() + * + * @param ETS_DS_OK if signing succeeded, ETS_DS_INVALID_PARAM if param is invalid, + * ETS_DS_INVALID_DIGEST or ETS_DS_INVALID_PADDING if there is a problem with the + * encrypted data digest or padding bytes (in case of ETS_DS_INVALID_PADDING, a + * digest is produced anyhow.) + */ +ets_ds_result_t ets_ds_finish_sign(void *signature, const ets_ds_data_t *data); + + +/* Plaintext parameters used by Digital Signature. + + Not used for signing with DS peripheral, but can be encrypted + in-device by calling ets_ds_encrypt_params() +*/ +typedef struct { + uint32_t Y[4096/32]; + uint32_t M[4096/32]; + uint32_t Rb[4096/32]; + uint32_t M_prime; + uint32_t length; +} ets_ds_p_data_t; + +typedef enum { + ETS_DS_KEY_HMAC, /* The HMAC key (as stored in efuse) */ + ETS_DS_KEY_AES, /* The AES key (as derived from HMAC key by HMAC peripheral in downstream mode) */ +} ets_ds_key_t; + +/* @brief Encrypt DS parameters suitable for storing and later use with DS peripheral + * + * @param data Output buffer to store encrypted data, suitable for later use generating signatures. + * @param iv Pointer to 16 byte IV buffer, will be copied into 'data'. Should be randomly generated bytes each time. + * @param p_data Pointer to input plaintext key data. The expectation is this data will be deleted after this process is done and 'data' is stored. + * @param key Pointer to 32 bytes of key data. Type determined by key_type parameter. The expectation is the corresponding HMAC key will be stored to efuse and then permanently erased. + * @param key_type Type of key stored in 'key' (either the AES-256 DS key, or an HMAC DS key from which the AES DS key is derived using HMAC peripheral) + * + * @return ETS_DS_INVALID_PARAM if any parameter is invalid, or ETS_DS_OK if 'data' is successfully generated from the input parameters. + */ +ets_ds_result_t ets_ds_encrypt_params(ets_ds_data_t *data, const void *iv, const ets_ds_p_data_t *p_data, const void *key, ets_ds_key_t key_type); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/efuse.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/efuse.h new file mode 100644 index 00000000..ae887278 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/efuse.h @@ -0,0 +1,393 @@ +// Copyright 2015-2018 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. + +#ifndef _ROM_EFUSE_H_ +#define _ROM_EFUSE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +/** \defgroup efuse_APIs efuse APIs + * @brief ESP32 efuse read/write APIs + * @attention + * + */ + +/** @addtogroup efuse_APIs + * @{ + */ + +typedef enum { + ETS_EFUSE_KEY_PURPOSE_USER = 0, + ETS_EFUSE_KEY_PURPOSE_RESERVED = 1, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_1 = 2, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_2 = 3, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY = 4, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL = 5, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG = 6, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE = 7, + ETS_EFUSE_KEY_PURPOSE_HMAC_UP = 8, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0 = 9, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1 = 10, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2 = 11, + ETS_EFUSE_KEY_PURPOSE_MAX, +} ets_efuse_purpose_t; + +typedef enum { + ETS_EFUSE_BLOCK0 = 0, + ETS_EFUSE_MAC_SPI_SYS_0 = 1, + ETS_EFUSE_BLOCK_SYS_DATA = 2, + ETS_EFUSE_BLOCK_USR_DATA = 3, + ETS_EFUSE_BLOCK_KEY0 = 4, + ETS_EFUSE_BLOCK_KEY1 = 5, + ETS_EFUSE_BLOCK_KEY2 = 6, + ETS_EFUSE_BLOCK_KEY3 = 7, + ETS_EFUSE_BLOCK_KEY4 = 8, + ETS_EFUSE_BLOCK_KEY5 = 9, + ETS_EFUSE_BLOCK_KEY6 = 10, + ETS_EFUSE_BLOCK_MAX, +} ets_efuse_block_t; + +/** + * @brief set timing accroding the apb clock, so no read error or write error happens. + * + * @param clock: apb clock in HZ, only accept 20M, 40M, 80M. + * + * @return : 0 if success, others if clock not accepted + */ +int ets_efuse_set_timing(uint32_t clock); + +/** + * @brief Enable efuse subsystem. Called after reset. Doesn't need to be called again. + */ +void ets_efuse_start(void); + +/** + * @brief Efuse read operation: copies data from physical efuses to efuse read registers. + * + * @param null + * + * @return : 0 is success, others if apb clock is not accepted + */ +int ets_efuse_read(void); + +/** + * @brief Efuse write operation: Copies data from efuse write registers to efuse. Operates on a single block of efuses at a time. + * + * @note This function does not update read efuses, call ets_efuse_read() once all programming is complete. + * + * @return : 0 is success, others if apb clock is not accepted + */ +int ets_efuse_program(ets_efuse_block_t block); + +/** + * @brief Set all Efuse program registers to zero. + * + * Call this before writing new data to the program registers. + */ +void ets_efuse_clear_program_registers(void); + +/** + * @brief Program a block of key data to an efuse block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. Key block must be unused (@ref ets_efuse_key_block_unused). + * @param purpose Purpose to set for this key. Purpose must be already unset. + * @param data Pointer to data to write. + * @param data_len Length of data to write. + * + * @note This function also calls ets_efuse_program() for the specified block, and for block 0 (setting the purpose) + */ +int ets_efuse_write_key(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose, const void *data, size_t data_len); + + +/* @brief Return the address of a particular efuse block's first read register + * + * @param block Index of efuse block to look up + * + * @return 0 if block is invalid, otherwise a numeric read register address + * of the first word in the block. + */ +uint32_t ets_efuse_get_read_register_address(ets_efuse_block_t block); + +/** + * @brief Return the current purpose set for an efuse key block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. + */ +ets_efuse_purpose_t ets_efuse_get_key_purpose(ets_efuse_block_t key_block); + +/** + * @brief Find a key block with the particular purpose set + * + * @param purpose Purpose to search for. + * @param[out] key_block Pointer which will be set to the key block if found. Can be NULL, if only need to test the key block exists. + * @return true if found, false if not found. If false, value at key_block pointer is unchanged. + */ +bool ets_efuse_find_purpose(ets_efuse_purpose_t purpose, ets_efuse_block_t *key_block); + +/** + * Return true if the key block is unused, false otherwise. + * + * An unused key block is all zero content, not read or write protected, + * and has purpose 0 (ETS_EFUSE_KEY_PURPOSE_USER) + * + * @param key_block key block to check. + * + * @return true if key block is unused, false if key block or used + * or the specified block index is not a key block. + */ +bool ets_efuse_key_block_unused(ets_efuse_block_t key_block); + + +/** + * @brief Search for an unused key block and return the first one found. + * + * See @ref ets_efuse_key_block_unused for a description of an unused key block. + * + * @return First unused key block, or ETS_EFUSE_BLOCK_MAX if no unused key block is found. + */ +ets_efuse_block_t ets_efuse_find_unused_key_block(void); + +/** + * @brief Return the number of unused efuse key blocks (0-6) + */ +unsigned ets_efuse_count_unused_key_blocks(void); + +/** + * @brief Calculate Reed-Solomon Encoding values for a block of efuse data. + * + * @param data Pointer to data buffer (length 32 bytes) + * @param rs_values Pointer to write encoded data to (length 12 bytes) + */ +void ets_efuse_rs_calculate(const void *data, void *rs_values); + +/** + * @brief Read spi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - 1 for default HSPI pins. + * - Other values define a custom pin configuration mask. Pins are encoded as per the EFUSE_SPICONFIG_RET_SPICLK, + * EFUSE_SPICONFIG_RET_SPIQ, EFUSE_SPICONFIG_RET_SPID, EFUSE_SPICONFIG_RET_SPICS0, EFUSE_SPICONFIG_RET_SPIHD macros. + * WP pin (for quad I/O modes) is not saved in efuse and not returned by this function. + */ +uint32_t ets_efuse_get_spiconfig(void); + +/** + * @brief Read spi flash wp pad from Efuse + * + * @return + * - 0x3f for invalid. + * - 0~46 is valid. + */ +uint32_t ets_efuse_get_wp_pad(void); + +/** + * @brief Read opi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - Other values define a custom pin configuration mask. From the LSB, every 6 bits represent a GPIO number which stand for: + * DQS, D4, D5, D6, D7 accordingly. + */ +uint32_t ets_efuse_get_opiconfig(void); + +/** + * @brief Read if download mode disabled from Efuse + * + * @return + * - true for efuse disable download mode. + * - false for efuse doesn't disable download mode. + */ +bool ets_efuse_download_modes_disabled(void); + +/** + * @brief Read if legacy spi flash boot mode disabled from Efuse + * + * @return + * - true for efuse disable legacy spi flash boot mode. + * - false for efuse doesn't disable legacy spi flash boot mode. + */ +bool ets_efuse_legacy_spi_boot_mode_disabled(void); + +/** + * @brief Read if uart print control value from Efuse + * + * @return + * - 0 for uart force print. + * - 1 for uart print when GPIO46 is low when digital reset. + * 2 for uart print when GPIO46 is high when digital reset. + * 3 for uart force slient + */ +uint32_t ets_efuse_get_uart_print_control(void); + +/** + * @brief Read which channel will used by ROM to print + * + * @return + * - 0 for UART0. + * - 1 for UART1. + */ +uint32_t ets_efuse_get_uart_print_channel(void); + +/** + * @brief Read if usb download mode disabled from Efuse + * + * (Also returns true if security download mode is enabled, as this mode + * disables USB download.) + * + * @return + * - true for efuse disable usb download mode. + * - false for efuse doesn't disable usb download mode. + */ +bool ets_efuse_usb_download_mode_disabled(void); + +/** + * @brief Read if tiny basic mode disabled from Efuse + * + * @return + * - true for efuse disable tiny basic mode. + * - false for efuse doesn't disable tiny basic mode. + */ +bool ets_efuse_tiny_basic_mode_disabled(void); + +/** + * @brief Read if usb module disabled from Efuse + * + * @return + * - true for efuse disable usb module. + * - false for efuse doesn't disable usb module. + */ +bool ets_efuse_usb_module_disabled(void); + +/** + * @brief Read if security download modes enabled from Efuse + * + * @return + * - true for efuse enable security download mode. + * - false for efuse doesn't enable security download mode. + */ +bool ets_efuse_security_download_modes_enabled(void); + +/** + * @brief Return true if secure boot is enabled in EFuse + */ +bool ets_efuse_secure_boot_enabled(void); + +/** + * @brief Return true if secure boot aggressive revoke is enabled in EFuse + */ +bool ets_efuse_secure_boot_aggressive_revoke_enabled(void); + +/** + * @brief Return true if cache encryption (flash, PSRAM, etc) is enabled from boot via EFuse + */ +bool ets_efuse_cache_encryption_enabled(void); + +/** + * @brief Return true if EFuse indicates an external phy needs to be used for USB + */ +bool ets_efuse_usb_use_ext_phy(void); + +/** + * @brief Return true if EFuse indicates USB device persistence is disabled + */ +bool ets_efuse_usb_force_nopersist(void); + +/** + * @brief Return true if OPI pins GPIO33-37 are powered by VDDSPI, otherwise by VDD33CPU + */ +bool ets_efuse_flash_opi_5pads_power_sel_vddspi(void); + +/** + * @brief Return true if EFuse indicates an opi flash is attached. + */ +bool ets_efuse_flash_opi_mode(void); + +/** + * @brief Return true if EFuse indicates to send a flash resume command. + */ +bool ets_efuse_force_send_resume(void); + +/** + * @brief return the time in us ROM boot need wait flash to power on from Efuse + * + * @return + * - uint32_t the time in us. + */ +uint32_t ets_efuse_get_flash_delay_us(void); + +#define EFUSE_SPICONFIG_SPI_DEFAULTS 0 +#define EFUSE_SPICONFIG_HSPI_DEFAULTS 1 + +#define EFUSE_SPICONFIG_RET_SPICLK_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICLK_SHIFT 0 +#define EFUSE_SPICONFIG_RET_SPICLK(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICLK_SHIFT) & EFUSE_SPICONFIG_RET_SPICLK_MASK) + +#define EFUSE_SPICONFIG_RET_SPIQ_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIQ_SHIFT 6 +#define EFUSE_SPICONFIG_RET_SPIQ(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIQ_SHIFT) & EFUSE_SPICONFIG_RET_SPIQ_MASK) + +#define EFUSE_SPICONFIG_RET_SPID_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPID_SHIFT 12 +#define EFUSE_SPICONFIG_RET_SPID(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPID_SHIFT) & EFUSE_SPICONFIG_RET_SPID_MASK) + +#define EFUSE_SPICONFIG_RET_SPICS0_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICS0_SHIFT 18 +#define EFUSE_SPICONFIG_RET_SPICS0(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICS0_SHIFT) & EFUSE_SPICONFIG_RET_SPICS0_MASK) + + +#define EFUSE_SPICONFIG_RET_SPIHD_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIHD_SHIFT 24 +#define EFUSE_SPICONFIG_RET_SPIHD(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIHD_SHIFT) & EFUSE_SPICONFIG_RET_SPIHD_MASK) + +/** + * @brief Enable JTAG temporarily by writing a JTAG HMAC "key" into + * the JTAG_CTRL registers. + * + * Works if JTAG has been "soft" disabled by burning the EFUSE_SOFT_DIS_JTAG efuse. + * + * Will enable the HMAC module to generate a "downstream" HMAC value from a key already saved in efuse, and then write the JTAG HMAC "key" which will enable JTAG if the two keys match. + * + * @param jtag_hmac_key Pointer to a 32 byte array containing a valid key. Supplied by user. + * @param key_block Index of a key block containing the source for this key. + * + * @return ETS_FAILED if HMAC operation fails or invalid parameter, ETS_OK otherwise. ETS_OK doesn't necessarily mean that JTAG was enabled. + */ +int ets_jtag_enable_temporarily(const uint8_t *jtag_hmac_key, ets_efuse_block_t key_block); + +/** + * @brief A crc8 algorithm used for MAC addresses in efuse + * + * @param unsigned char const *p : Pointer to original data. + * + * @param unsigned int len : Data length in byte. + * + * @return unsigned char: Crc value. + */ +unsigned char esp_crc8(unsigned char const *p, unsigned int len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_EFUSE_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/ets_sys.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/ets_sys.h new file mode 100644 index 00000000..1d4763db --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/ets_sys.h @@ -0,0 +1,658 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_ETS_SYS_H_ +#define _ROM_ETS_SYS_H_ + +#include +#include + +#include "soc/soc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup ets_sys_apis, ets system related apis + * @brief ets system apis + */ + +/** @addtogroup ets_sys_apis + * @{ + */ + +/************************************************************************ + * NOTE + * Many functions in this header files can't be run in FreeRTOS. + * Please see the comment of the Functions. + * There are also some functions that doesn't work on FreeRTOS + * without listed in the header, such as: + * xtos functions start with "_xtos_" in ld file. + * + *********************************************************************** + */ + +/** \defgroup ets_apis, Espressif Task Scheduler related apis + * @brief ets apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +typedef enum { + ETS_OK = 0, /**< return successful in ets*/ + ETS_FAILED = 1 /**< return failed in ets*/ +} ETS_STATUS; + +typedef ETS_STATUS ets_status_t; + +typedef uint32_t ETSSignal; +typedef uint32_t ETSParam; + +typedef struct ETSEventTag ETSEvent; /**< Event transmit/receive in ets*/ + +struct ETSEventTag { + ETSSignal sig; /**< Event signal, in same task, different Event with different signal*/ + ETSParam par; /**< Event parameter, sometimes without usage, then will be set as 0*/ +}; + +typedef void (*ETSTask)(ETSEvent *e); /**< Type of the Task processer*/ +typedef void (* ets_idle_cb_t)(void *arg); /**< Type of the system idle callback*/ + +/** + * @brief Start the Espressif Task Scheduler, which is an infinit loop. Please do not add code after it. + * + * @param none + * + * @return none + */ +void ets_run(void); + +/** + * @brief Set the Idle callback, when Tasks are processed, will call the callback before CPU goto sleep. + * + * @param ets_idle_cb_t func : The callback function. + * + * @param void *arg : Argument of the callback. + * + * @return None + */ +void ets_set_idle_cb(ets_idle_cb_t func, void *arg); + +/** + * @brief Init a task with processer, priority, queue to receive Event, queue length. + * + * @param ETSTask task : The task processer. + * + * @param uint8_t prio : Task priority, 0-31, bigger num with high priority, one priority with one task. + * + * @param ETSEvent *queue : Queue belongs to the task, task always receives Events, Queue is circular used. + * + * @param uint8_t qlen : Queue length. + * + * @return None + */ +void ets_task(ETSTask task, uint8_t prio, ETSEvent *queue, uint8_t qlen); + +/** + * @brief Post an event to an Task. + * + * @param uint8_t prio : Priority of the Task. + * + * @param ETSSignal sig : Event signal. + * + * @param ETSParam par : Event parameter + * + * @return ETS_OK : post successful + * @return ETS_FAILED : post failed + */ +ETS_STATUS ets_post(uint8_t prio, ETSSignal sig, ETSParam par); + +/** + * @} + */ + +/** \defgroup ets_boot_apis, Boot routing related apis + * @brief ets boot apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +extern const char *const exc_cause_table[40]; ///**< excption cause that defined by the core.*/ + +/** + * @brief Set Pro cpu Entry code, code can be called in PRO CPU when booting is not completed. + * When Pro CPU booting is completed, Pro CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the PRO Entry code address value in uint32_t + * + * @return None + */ +void ets_set_user_start(uint32_t start); + +/** + * @brief Set Pro cpu Startup code, code can be called when booting is not completed, or in Entry code. + * When Entry code completed, CPU will call the Startup code if not NULL, else call ets_run. + * + * @param uint32_t callback : the Startup code address value in uint32_t + * + * @return None : post successful + */ +void ets_set_startup_callback(uint32_t callback); + +/** + * @brief Set App cpu Entry code, code can be called in PRO CPU. + * When APP booting is completed, APP CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the APP Entry code address value in uint32_t, stored in register APPCPU_CTRL_REG_D. + * + * @return None + */ +void ets_set_appcpu_boot_addr(uint32_t start); + +/** + * @} + */ + +/** \defgroup ets_printf_apis, ets_printf related apis used in ets + * @brief ets printf apis + */ + +/** @addtogroup ets_printf_apis + * @{ + */ + +/** + * @brief Printf the strings to uart or other devices, similar with printf, simple than printf. + * Can not print float point data format, or longlong data format. + * So we maybe only use this in ROM. + * + * @param const char *fmt : See printf. + * + * @param ... : See printf. + * + * @return int : the length printed to the output device. + */ +int ets_printf(const char *fmt, ...); + +/** + * @brief Set the uart channel of ets_printf(uart_tx_one_char). + * ROM will set it base on the efuse and gpio setting, however, this can be changed after booting. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2. + * + * @return None + */ +void ets_set_printf_channel(uint8_t uart_no); + +/** + * @brief Get the uart channel of ets_printf(uart_tx_one_char). + * + * @return uint8_t uart channel used by ets_printf(uart_tx_one_char). + */ +uint8_t ets_get_printf_channel(void); + +/** + * @brief Output a char to uart, which uart to output(which is in uart module in ROM) is not in scope of the function. + * Can not print float point data format, or longlong data format + * + * @param char c : char to output. + * + * @return None + */ +void ets_write_char_uart(char c); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc1, which is defaulted installed as ets_write_char_uart in none silent boot mode, as NULL in silent mode. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc1(void (*p)(char c)); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc2, which is defaulted installed as NULL. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc2(void (*p)(char c)); + +/** + * @brief Install putc1 as ets_write_char_uart. + * In silent boot mode(to void interfere the UART attached MCU), we can call this function, after booting ok. + * + * @param None + * + * @return None + */ +void ets_install_uart_printf(void); + +#define ETS_PRINTF(...) ets_printf(...) + +#define ETS_ASSERT(v) do { \ + if (!(v)) { \ + ets_printf("%s %u \n", __FILE__, __LINE__); \ + while (1) {}; \ + } \ +} while (0); + +/** + * @} + */ + +/** \defgroup ets_timer_apis, ets_timer related apis used in ets + * @brief ets timer apis + */ + +/** @addtogroup ets_timer_apis + * @{ + */ +typedef void ETSTimerFunc(void *timer_arg);/**< timer handler*/ + +typedef struct _ETSTIMER_ { + struct _ETSTIMER_ *timer_next; /**< timer linker*/ + uint32_t timer_expire; /**< abstruct time when timer expire*/ + uint32_t timer_period; /**< timer period, 0 means timer is not periodic repeated*/ + ETSTimerFunc *timer_func; /**< timer handler*/ + void *timer_arg; /**< timer handler argument*/ +} ETSTimer; + +/** + * @brief Init ets timer, this timer range is 640 us to 429496 ms + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_init(void); + +/** + * @brief In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_deinit(void); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in ms, range is 1 to 429496. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm(ETSTimer *timer, uint32_t tmout, bool repeat); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in us, range is 1 to 429496729. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm_us(ETSTimer *ptimer, uint32_t us, bool repeat); + +/** + * @brief Disarm an ets timer. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_disarm(ETSTimer *timer); + +/** + * @brief Set timer callback and argument. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param ETSTimerFunc *pfunction : Timer callback. + * + * @param void *parg : Timer callback argument. + * + * @return None + */ +void ets_timer_setfn(ETSTimer *ptimer, ETSTimerFunc *pfunction, void *parg); + +/** + * @brief Unset timer callback and argument to NULL. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_done(ETSTimer *ptimer); + +/** + * @brief CPU do while loop for some time. + * In FreeRTOS task, please call FreeRTOS apis. + * + * @param uint32_t us : Delay time in us. + * + * @return None + */ +void ets_delay_us(uint32_t us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * Call this function when CPU frequency is changed. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency(uint32_t ticks_per_us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * + * @note This function only sets the tick rate for the current CPU. It is located in ROM, + * so the deep sleep stub can use it even if IRAM is not initialized yet. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency_rom(uint32_t ticks_per_us); + +/** + * @brief Get the real CPU ticks per us to the ets. + * This function do not return real CPU ticks per us, just the record in ets. It can be used to check with the real CPU frequency. + * + * @param None + * + * @return uint32_t : CPU ticks per us record in ets. + */ +uint32_t ets_get_cpu_frequency(void); + +/** + * @brief Get xtal_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if stored in efuse(not 0) + * clock = ets_efuse_get_xtal_freq() * 1000000; + * else if analog_8M in efuse + * clock = ets_get_xtal_scale() * 625 / 16 * ets_efuse_get_8M_clock(); + * else clock = 40M. + */ +uint32_t ets_get_xtal_freq(void); + +/** + * @brief Get the apb divisor. The xtal frequency gets divided + * by this value to generate the APB clock. + * When any types of reset happens, the default value is 2. + * + * @param None + * + * @return uint32_t : 1 or 2. + */ +uint32_t ets_get_xtal_div(void); + + +/** + * @brief Modifies the apb divisor. The xtal frequency gets divided by this to + * generate the APB clock. + * + * @note The xtal frequency divisor is 2 by default as the glitch detector + * doesn't properly stop glitches when it is 1. Please do not set the + * divisor to 1 before the PLL is active without being aware that you + * may be introducing a security risk. + * + * @param div Divisor. 1 = xtal freq, 2 = 1/2th xtal freq. + */ +void ets_set_xtal_div(int div); + + +/** + * @brief Get apb_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if rtc store the value (RTC_STORE5 high 16 bits and low 16 bits with same value), read from rtc register. + * clock = (REG_READ(RTC_STORE5) & 0xffff) << 12; + * else store ets_get_detected_xtal_freq() in. + */ +uint32_t ets_get_apb_freq(void); + +/** + * @} + */ + +/** \defgroup ets_intr_apis, ets interrupt configure related apis + * @brief ets intr apis + */ + +/** @addtogroup ets_intr_apis + * @{ + */ + +typedef void (* ets_isr_t)(void *);/**< interrupt handler type*/ + +/** + * @brief Attach a interrupt handler to a CPU interrupt number. + * This function equals to _xtos_set_interrupt_handler_arg(i, func, arg). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param int i : CPU interrupt number. + * + * @param ets_isr_t func : Interrupt handler. + * + * @param void *arg : argument of the handler. + * + * @return None + */ +void ets_isr_attach(int i, ets_isr_t func, void *arg); + +/** + * @brief Mask the interrupts which show in mask bits. + * This function equals to _xtos_ints_off(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_mask(uint32_t mask); + +/** + * @brief Unmask the interrupts which show in mask bits. + * This function equals to _xtos_ints_on(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_unmask(uint32_t unmask); + +/** + * @brief Lock the interrupt to level 2. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_lock(void); + +/** + * @brief Unlock the interrupt to level 0. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_unlock(void); + +/** + * @brief Unlock the interrupt to level 0, and CPU will go into power save mode(wait interrupt). + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_waiti0(void); + +/** + * @brief Attach an CPU interrupt to a hardware source. + * We have 4 steps to use an interrupt: + * 1.Attach hardware interrupt source to CPU. intr_matrix_set(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM); + * 2.Set interrupt handler. xt_set_interrupt_handler(ETS_WMAC_INUM, func, NULL); + * 3.Enable interrupt for CPU. xt_ints_on(1 << ETS_WMAC_INUM); + * 4.Enable interrupt in the module. + * + * @param int cpu_no : The CPU which the interrupt number belongs. + * + * @param uint32_t model_num : The interrupt hardware source number, please see the interrupt hardware source table. + * + * @param uint32_t intr_num : The interrupt number CPU, please see the interrupt cpu using table. + * + * @return None + */ +void intr_matrix_set(int cpu_no, uint32_t model_num, uint32_t intr_num); + +#define _ETSTR(v) # v +#define _ETS_SET_INTLEVEL(intlevel) ({ unsigned __tmp; \ + __asm__ __volatile__( "rsil %0, " _ETSTR(intlevel) "\n" \ + : "=a" (__tmp) : : "memory" ); \ + }) + +#ifdef CONFIG_NONE_OS +#define ETS_INTR_LOCK() \ + ets_intr_lock() + +#define ETS_INTR_UNLOCK() \ + ets_intr_unlock() + +#define ETS_ISR_ATTACH \ + ets_isr_attach + +#define ETS_INTR_ENABLE(inum) \ + ets_isr_unmask((1< +#include + +#include "esp_attr.h" +#include "soc/gpio_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup gpio_apis, uart configuration and communication related apis + * @brief gpio apis + */ + +/** @addtogroup gpio_apis + * @{ + */ + +#define GPIO_REG_READ(reg) READ_PERI_REG(reg) +#define GPIO_REG_WRITE(reg, val) WRITE_PERI_REG(reg, val) +#define GPIO_ID_PIN0 0 +#define GPIO_ID_PIN(n) (GPIO_ID_PIN0+(n)) +#define GPIO_PIN_ADDR(i) (GPIO_PIN0_REG + i*4) + +#define GPIO_FUNC_IN_HIGH 0x38 +#define GPIO_FUNC_IN_LOW 0x3C + +#define GPIO_ID_IS_PIN_REGISTER(reg_id) \ + ((reg_id >= GPIO_ID_PIN0) && (reg_id <= GPIO_ID_PIN(GPIO_PIN_COUNT-1))) + +#define GPIO_REGID_TO_PINIDX(reg_id) ((reg_id) - GPIO_ID_PIN0) + +typedef enum { + GPIO_PIN_INTR_DISABLE = 0, + GPIO_PIN_INTR_POSEDGE = 1, + GPIO_PIN_INTR_NEGEDGE = 2, + GPIO_PIN_INTR_ANYEDGE = 3, + GPIO_PIN_INTR_LOLEVEL = 4, + GPIO_PIN_INTR_HILEVEL = 5 +} GPIO_INT_TYPE; + +#define GPIO_OUTPUT_SET(gpio_no, bit_value) \ + ((gpio_no < 32) ? gpio_output_set(bit_value<>gpio_no)&BIT0) : ((gpio_input_get_high()>>(gpio_no - 32))&BIT0)) + +/* GPIO interrupt handler, registered through gpio_intr_handler_register */ +typedef void (* gpio_intr_handler_fn_t)(uint32_t intr_mask, bool high, void *arg); + +/** + * @brief Initialize GPIO. This includes reading the GPIO Configuration DataSet + * to initialize "output enables" and pin configurations for each gpio pin. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_init(void); + +/** + * @brief Change GPIO(0-31) pin output by setting, clearing, or disabling pins, GPIO0<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Change GPIO(32-39) pin output by setting, clearing, or disabling pins, GPIO32<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set_high(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Sample the value of GPIO input pins(0-31) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO0. + */ +uint32_t gpio_input_get(void); + +/** + * @brief Sample the value of GPIO input pins(32-39) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO32. + */ +uint32_t gpio_input_get_high(void); + +/** + * @brief Register an application-specific interrupt handler for GPIO pin interrupts. + * Once the interrupt handler is called, it will not be called again until after a call to gpio_intr_ack. + * Please do not call this function in SDK. + * + * @param gpio_intr_handler_fn_t fn : gpio application-specific interrupt handler + * + * @param void *arg : gpio application-specific interrupt handler argument. + * + * @return None + */ +void gpio_intr_handler_register(gpio_intr_handler_fn_t fn, void *arg); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO0. + */ +uint32_t gpio_intr_pending(void); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO32. + */ +uint32_t gpio_intr_pending_high(void); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO0. + * + * @return None + */ +void gpio_intr_ack(uint32_t ack_mask); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO32. + * + * @return None + */ +void gpio_intr_ack_high(uint32_t ack_mask); + +/** + * @brief Set GPIO to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param uint32_t i: gpio number. + * + * @param GPIO_INT_TYPE intr_state : only GPIO_PIN_INTR_LOLEVEL\GPIO_PIN_INTR_HILEVEL can be used + * + * @return None + */ +void gpio_pin_wakeup_enable(uint32_t i, GPIO_INT_TYPE intr_state); + +/** + * @brief disable GPIOs to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_pin_wakeup_disable(void); + +/** + * @brief set gpio input to a signal, one gpio can input to several signals. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * gpio == 0x3C, input 0 to signal + * gpio == 0x3A, input nothing to signal + * gpio == 0x38, input 1 to signal + * + * @param uint32_t signal_idx : signal index. + * + * @param bool inv : the signal is inv or not + * + * @return None + */ +void gpio_matrix_in(uint32_t gpio, uint32_t signal_idx, bool inv); + +/** + * @brief set signal output to gpio, one signal can output to several gpios. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * + * @param uint32_t signal_idx : signal index. + * signal_idx == 0x100, cancel output put to the gpio + * + * @param bool out_inv : the signal output is invert or not + * + * @param bool oen_inv : the signal output enable is invert or not + * + * @return None + */ +void gpio_matrix_out(uint32_t gpio, uint32_t signal_idx, bool out_inv, bool oen_inv); + +/** + * @brief Select pad as a gpio function from IOMUX. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_select_gpio(uint32_t gpio_num); + +/** + * @brief Set pad driver capability. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @param uint32_t drv : 0-3 + * + * @return None + */ +void gpio_pad_set_drv(uint32_t gpio_num, uint32_t drv); + +/** + * @brief Pull up the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pullup(uint32_t gpio_num); + +/** + * @brief Pull down the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pulldown(uint32_t gpio_num); + +/** + * @brief Unhold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_unhold(uint32_t gpio_num); + +/** + * @brief Hold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_hold(uint32_t gpio_num); + +/** + * @brief enable gpio pad input. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_input_enable(uint32_t gpio_num); + +/** + * @brief disable gpio pad input. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_input_disable(uint32_t gpio_num); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_GPIO_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/hmac.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/hmac.h new file mode 100644 index 00000000..f5f82d5b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/hmac.h @@ -0,0 +1,63 @@ +// Copyright 2018 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. + +#ifndef _ROM_HMAC_H_ +#define _ROM_HMAC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "efuse.h" + +void ets_hmac_enable(void); + +void ets_hmac_disable(void); + +/* Use the "upstream" HMAC key (ETS_EFUSE_KEY_PURPOSE_HMAC_UP) + to digest a message. +*/ +int ets_hmac_calculate_message(ets_efuse_block_t key_block, const void *message, size_t message_len, uint8_t *hmac); + +/* Calculate a downstream HMAC message to temporarily enable JTAG, or + to generate a Digital Signature data decryption key. + + - purpose must be ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE + or ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG + + - key_block must be in range ETS_EFUSE_BLOCK_KEY0 toETS_EFUSE_BLOCK_KEY6. + This efuse block must have the corresponding purpose set in "purpose", or + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL. + + The result of this HMAC calculation is only made available "downstream" to the + corresponding hardware module, and cannot be accessed by software. +*/ +int ets_hmac_calculate_downstream(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose); + +/* Invalidate a downstream HMAC value previously calculated by ets_hmac_calculate_downstream(). + * + * - purpose must match a previous call to ets_hmac_calculate_downstream(). + * + * After this function is called, the corresponding internal operation (JTAG or DS) will no longer + * have access to the generated key. + */ +int ets_hmac_invalidate_downstream(ets_efuse_purpose_t purpose); + +#ifdef __cplusplus +} +#endif + +#endif // _ROM_HMAC_H_ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/libc_stubs.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/libc_stubs.h new file mode 100644 index 00000000..5e514e18 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/libc_stubs.h @@ -0,0 +1,88 @@ +// Copyright 2015-2019 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. +#ifndef _ROM_LIBC_STUBS_H_ +#define _ROM_LIBC_STUBS_H_ + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* +ESP32-S2 ROM code contains implementations of some of C library functions. +Whenever a function in ROM needs to use a syscall, it calls a pointer to the corresponding syscall +implementation defined in the following struct. + +The table itself, by default, is not allocated in RAM. There is a pointer, `syscall_table_ptr_pro`, +which can be set to point to the locations of syscall tables of CPU 0 (aka PRO CPU). +Location of this pointer in .bss segment of ROM code is defined in linker script. + +So, before using any of the C library functions (except for pure functions and memcpy/memset functions), +application must allocate syscall table structure for each CPU being used, and populate it with pointers +to actual implementations of corresponding syscalls. +*/ + +struct syscall_stub_table +{ + struct _reent* (*__getreent)(void); + void* (*_malloc_r)(struct _reent *r, size_t); + void (*_free_r)(struct _reent *r, void*); + void* (*_realloc_r)(struct _reent *r, void*, size_t); + void* (*_calloc_r)(struct _reent *r, size_t, size_t); + void (*_abort)(void); + int (*_system_r)(struct _reent *r, const char*); + int (*_rename_r)(struct _reent *r, const char*, const char*); + clock_t (*_times_r)(struct _reent *r, struct tms *); + int (*_gettimeofday_r) (struct _reent *r, struct timeval *, void *); + void (*_raise_r)(struct _reent *r); + int (*_unlink_r)(struct _reent *r, const char*); + int (*_link_r)(struct _reent *r, const char*, const char*); + int (*_stat_r)(struct _reent *r, const char*, struct stat *); + int (*_fstat_r)(struct _reent *r, int, struct stat *); + void* (*_sbrk_r)(struct _reent *r, ptrdiff_t); + int (*_getpid_r)(struct _reent *r); + int (*_kill_r)(struct _reent *r, int, int); + void (*_exit_r)(struct _reent *r, int); + int (*_close_r)(struct _reent *r, int); + int (*_open_r)(struct _reent *r, const char *, int, int); + int (*_write_r)(struct _reent *r, int, const void *, int); + int (*_lseek_r)(struct _reent *r, int, int, int); + int (*_read_r)(struct _reent *r, int, void *, int); + void (*_lock_init)(_lock_t *lock); + void (*_lock_init_recursive)(_lock_t *lock); + void (*_lock_close)(_lock_t *lock); + void (*_lock_close_recursive)(_lock_t *lock); + void (*_lock_acquire)(_lock_t *lock); + void (*_lock_acquire_recursive)(_lock_t *lock); + int (*_lock_try_acquire)(_lock_t *lock); + int (*_lock_try_acquire_recursive)(_lock_t *lock); + void (*_lock_release)(_lock_t *lock); + void (*_lock_release_recursive)(_lock_t *lock); + int (*_printf_float)(struct _reent *data, void *pdata, FILE * fp, int (*pfunc) (struct _reent *, FILE *, const char *, size_t len), va_list * ap); + int (*_scanf_float) (struct _reent *rptr, void *pdata, FILE *fp, va_list *ap); +}; + +extern struct syscall_stub_table* syscall_table_ptr_pro; + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /* _ROM_LIBC_STUBS_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/lldesc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/lldesc.h new file mode 100644 index 00000000..a11be376 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/lldesc.h @@ -0,0 +1,176 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_LLDESC_H_ +#define _ROM_LLDESC_H_ + +#include + +#include "sys/queue.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LLDESC_TX_MBLK_SIZE 268 /* */ +#define LLDESC_RX_SMBLK_SIZE 64 /* small block size, for small mgmt frame */ +#define LLDESC_RX_MBLK_SIZE 524 /* rx is large sinec we want to contain mgmt frame in one block*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_SIZE 64 /* it is a small buffer which is a cycle link*/ +#define LLDESC_RX_AMPDU_LEN_MBLK_SIZE 256 /*for ampdu entry*/ +#ifdef ESP_MAC_5 +#define LLDESC_TX_MBLK_NUM 116 /* 64K / 256 */ +#define LLDESC_RX_MBLK_NUM 82 /* 64K / 512 MAX 172*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 12 +#else +#ifdef SBUF_RXTX +#define LLDESC_TX_MBLK_NUM_MAX (2 * 48) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MAX (2 * 48) /* 23K / 524 */ +#define LLDESC_TX_MBLK_NUM_MIN (2 * 16) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MIN (2 * 16) /* 23K / 524 */ +#endif +#define LLDESC_TX_MBLK_NUM 10 //(2 * 32) /* 23K / 260 - 8 */ + +#ifdef IEEE80211_RX_AMPDU +#define LLDESC_RX_MBLK_NUM 30 +#else +#define LLDESC_RX_MBLK_NUM 10 +#endif /*IEEE80211_RX_AMPDU*/ + +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 8 +#endif /* !ESP_MAC_5 */ +/* + * SLC2 DMA Desc struct, aka lldesc_t + * + * -------------------------------------------------------------- + * | own | EoF | sub_sof | 5'b0 | length [11:0] | size [11:0] | + * -------------------------------------------------------------- + * | buf_ptr [31:0] | + * -------------------------------------------------------------- + * | next_desc_ptr [31:0] | + * -------------------------------------------------------------- + */ + +/* this bitfield is start from the LSB!!! */ +typedef struct lldesc_s { + volatile uint32_t size :12, + length:12, + offset: 5, /* h/w reserved 5bit, s/w use it as offset in buffer */ + sosf : 1, /* start of sub-frame */ + eof : 1, /* end of frame */ + owner : 1; /* hw or sw */ + volatile const uint8_t *buf; /* point to buffer data */ + union{ + volatile uint32_t empty; + STAILQ_ENTRY(lldesc_s) qe; /* pointing to the next desc */ + }; +} lldesc_t; + +typedef struct tx_ampdu_entry_s{ + uint32_t sub_len :12, + dili_num : 7, + : 1, + null_byte: 2, + data : 1, + enc : 1, + seq : 8; +} tx_ampdu_entry_t; + +typedef struct lldesc_chain_s { + lldesc_t *head; + lldesc_t *tail; +} lldesc_chain_t; + +#ifdef SBUF_RXTX +enum sbuf_mask_s { + SBUF_MOVE_NO = 0, + SBUF_MOVE_TX2RX, + SBUF_MOVE_RX2TX, +} ; + +#define SBUF_MOVE_STEP 8 +#endif +#define LLDESC_SIZE sizeof(struct lldesc_s) + +/* SLC Descriptor */ +#define LLDESC_OWNER_MASK 0x80000000 +#define LLDESC_OWNER_SHIFT 31 +#define LLDESC_SW_OWNED 0 +#define LLDESC_HW_OWNED 1 + +#define LLDESC_EOF_MASK 0x40000000 +#define LLDESC_EOF_SHIFT 30 + +#define LLDESC_SOSF_MASK 0x20000000 +#define LLDESC_SOSF_SHIFT 29 + +#define LLDESC_LENGTH_MASK 0x00fff000 +#define LLDESC_LENGTH_SHIFT 12 + +#define LLDESC_SIZE_MASK 0x00000fff +#define LLDESC_SIZE_SHIFT 0 + +#define LLDESC_ADDR_MASK 0x000fffff + +void lldesc_build_chain(uint8_t *descptr, uint32_t desclen, uint8_t * mblkptr, uint32_t buflen, uint32_t blksz, uint8_t owner, + lldesc_t **head, +#ifdef TO_HOST_RESTART + lldesc_t ** one_before_tail, +#endif + lldesc_t **tail); + +lldesc_t *lldesc_num2link(lldesc_t * head, uint16_t nblks); + +lldesc_t *lldesc_set_owner(lldesc_t * head, uint16_t nblks, uint8_t owner); + +static inline uint32_t lldesc_get_chain_length(lldesc_t *head) +{ + lldesc_t *ds = head; + uint32_t len = 0; + + while (ds) { + len += ds->length; + ds = STAILQ_NEXT(ds, qe); + } + + return len; +} + +static inline void lldesc_config(lldesc_t *ds, uint8_t owner, uint8_t eof, uint8_t sosf, uint16_t len) +{ + ds->owner = owner; + ds->eof = eof; + ds->sosf = sosf; + ds->length = len; +} + +#define LLDESC_CONFIG(_desc, _owner, _eof, _sosf, _len) do { \ + (_desc)->owner = (_owner); \ + (_desc)->eof = (_eof); \ + (_desc)->sosf = (_sosf); \ + (_desc)->length = (_len); \ +} while(0) + +#define LLDESC_FROM_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#define LLDESC_MAC_RX_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, (ds)->size) + +#define LLDESC_TO_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_LLDESC_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/md5_hash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/md5_hash.h new file mode 100644 index 00000000..f116f1e6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/md5_hash.h @@ -0,0 +1,38 @@ +/* + * MD5 internal definitions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#ifndef _ROM_MD5_HASH_H_ +#define _ROM_MD5_HASH_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); +void MD5Final(unsigned char digest[16], struct MD5Context *context); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_MD5_HASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/miniz.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/miniz.h new file mode 100644 index 00000000..b9b9202a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/miniz.h @@ -0,0 +1,776 @@ +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times, and the C run-time funcs that get/set times won't be called. +// The current downside is the times written to your archives will be from 1979. +#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +#define MINIZ_NO_MALLOC + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) + // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux + #define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) + #include +#endif + +//Hardcoded options for Xtensa - JD +#define MINIZ_X86_OR_X64_CPU 0 +#define MINIZ_LITTLE_ENDIAN 1 +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_HAS_64BIT_REGISTERS 0 +#define TINFL_USE_64BIT_BITBUF 0 + + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s +{ + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; + #define Z_NULL 0 + #define Z_NO_FLUSH MZ_NO_FLUSH + #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH + #define Z_SYNC_FLUSH MZ_SYNC_FLUSH + #define Z_FULL_FLUSH MZ_FULL_FLUSH + #define Z_FINISH MZ_FINISH + #define Z_BLOCK MZ_BLOCK + #define Z_OK MZ_OK + #define Z_STREAM_END MZ_STREAM_END + #define Z_NEED_DICT MZ_NEED_DICT + #define Z_ERRNO MZ_ERRNO + #define Z_STREAM_ERROR MZ_STREAM_ERROR + #define Z_DATA_ERROR MZ_DATA_ERROR + #define Z_MEM_ERROR MZ_MEM_ERROR + #define Z_BUF_ERROR MZ_BUF_ERROR + #define Z_VERSION_ERROR MZ_VERSION_ERROR + #define Z_PARAM_ERROR MZ_PARAM_ERROR + #define Z_NO_COMPRESSION MZ_NO_COMPRESSION + #define Z_BEST_SPEED MZ_BEST_SPEED + #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION + #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION + #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY + #define Z_FILTERED MZ_FILTERED + #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY + #define Z_RLE MZ_RLE + #define Z_FIXED MZ_FIXED + #define Z_DEFLATED MZ_DEFLATED + #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + #define alloc_func mz_alloc_func + #define free_func mz_free_func + #define internal_state mz_internal_state + #define z_stream mz_stream + #define deflateInit mz_deflateInit + #define deflateInit2 mz_deflateInit2 + #define deflateReset mz_deflateReset + #define deflate mz_deflate + #define deflateEnd mz_deflateEnd + #define deflateBound mz_deflateBound + #define compress mz_compress + #define compress2 mz_compress2 + #define compressBound mz_compressBound + #define inflateInit mz_inflateInit + #define inflateInit2 mz_inflateInit2 + #define inflate mz_inflate + #define inflateEnd mz_inflateEnd + #define uncompress mz_uncompress + #define crc32 mz_crc32 + #define adler32 mz_adler32 + #define MAX_WBITS 15 + #define MAX_MEM_LEVEL 9 + #define zError mz_error + #define ZLIB_VERSION MZ_VERSION + #define ZLIB_VERNUM MZ_VERNUM + #define ZLIB_VER_MAJOR MZ_VER_MAJOR + #define ZLIB_VER_MINOR MZ_VER_MINOR + #define ZLIB_VER_REVISION MZ_VER_REVISION + #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + #define zlibVersion mz_version + #define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct +{ + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct mz_zip_archive_tag +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 1 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum +{ + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL +// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/opi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/opi_flash.h new file mode 100644 index 00000000..c985810b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/opi_flash.h @@ -0,0 +1,300 @@ +/* + * copyright (c) Espressif System 2019 + * + */ + +#ifndef _ROM_OPI_FLASH_H_ +#define _ROM_OPI_FLASH_H_ +#include +#include +#include +#include "spi_flash.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint16_t cmd; /*!< Command value */ + uint16_t cmdBitLen; /*!< Command byte length*/ + uint32_t *addr; /*!< Point to address value*/ + uint32_t addrBitLen; /*!< Address byte length*/ + uint32_t *txData; /*!< Point to send data buffer*/ + uint32_t txDataBitLen; /*!< Send data byte length.*/ + uint32_t *rxData; /*!< Point to recevie data buffer*/ + uint32_t rxDataBitLen; /*!< Recevie Data byte length.*/ + uint32_t dummyBitLen; +} esp_rom_spi_cmd_t; + +#define ESP_ROM_OPIFLASH_MUX_TAKE() +#define ESP_ROM_OPIFLASH_MUX_GIVE() +#define ESP_ROM_OPIFLASH_SEL_CS0 (BIT(0)) +#define ESP_ROM_OPIFLASH_SEL_CS1 (BIT(1)) + +// Definition of MX25UM25645G Octa Flash +// SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 +#define ESP_ROM_SPIFLASH_BP_MASK_ISSI (BIT7 | BIT5 | BIT4 | BIT3 | BIT2) + +#define FLASH_OP_MODE_RDCMD_DOUT 0x3B +#define ESP_ROM_FLASH_SECTOR_SIZE 0x1000 +#define ESP_ROM_FLASH_BLOCK_SIZE_64K 0x10000 +#define ESP_ROM_FLASH_PAGE_SIZE 256 + +// FLASH commands +#define ROM_FLASH_CMD_RDID 0x9F +#define ROM_FLASH_CMD_WRSR 0x01 +#define ROM_FLASH_CMD_WRSR2 0x31 /* Not all SPI flash uses this command */ +#define ROM_FLASH_CMD_WREN 0x06 +#define ROM_FLASH_CMD_WRDI 0x04 +#define ROM_FLASH_CMD_RDSR 0x05 +#define ROM_FLASH_CMD_RDSR2 0x35 /* Not all SPI flash uses this command */ +#define ROM_FLASH_CMD_ERASE_SEC 0x20 +#define ROM_FLASH_CMD_ERASE_BLK_32K 0x52 +#define ROM_FLASH_CMD_ERASE_BLK_64K 0xD8 +#define ROM_FLASH_CMD_OTPEN 0x3A /* Enable OTP mode, not all SPI flash uses this command */ +#define ROM_FLASH_CMD_RSTEN 0x66 +#define ROM_FLASH_CMD_RST 0x99 + +#define ROM_FLASH_CMD_SE4B 0x21 +#define ROM_FLASH_CMD_SE4B_OCT 0xDE21 +#define ROM_FLASH_CMD_BE4B 0xDC +#define ROM_FLASH_CMD_BE4B_OCT 0x23DC +#define ROM_FLASH_CMD_RSTEN_OCT 0x9966 +#define ROM_FLASH_CMD_RST_OCT 0x6699 + +#define ROM_FLASH_CMD_FSTRD4B_STR 0x13EC +#define ROM_FLASH_CMD_FSTRD4B_DTR 0x11EE +#define ROM_FLASH_CMD_FSTRD4B 0x0C +#define ROM_FLASH_CMD_PP4B 0x12 +#define ROM_FLASH_CMD_PP4B_OCT 0xED12 + +#define ROM_FLASH_CMD_RDID_OCT 0x609F +#define ROM_FLASH_CMD_WREN_OCT 0xF906 +#define ROM_FLASH_CMD_RDSR_OCT 0xFA05 +#define ROM_FLASH_CMD_RDCR2 0x71 +#define ROM_FLASH_CMD_RDCR2_OCT 0x8E71 +#define ROM_FLASH_CMD_WRCR2 0x72 +#define ROM_FLASH_CMD_WRCR2_OCT 0x8D72 + +// Definitions for GigaDevice GD25LX256E Flash +#define ROM_FLASH_CMD_RDFSR_GD 0x70 +#define ROM_FLASH_CMD_RD_GD 0x03 +#define ROM_FLASH_CMD_RD4B_GD 0x13 +#define ROM_FLASH_CMD_FSTRD_GD 0x0B +#define ROM_FLASH_CMD_FSTRD4B_GD 0x0C +#define ROM_FLASH_CMD_FSTRD_OOUT_GD 0x8B +#define ROM_FLASH_CMD_FSTRD4B_OOUT_GD 0x7C +#define ROM_FLASH_CMD_FSTRD_OIOSTR_GD 0xCB +#define ROM_FLASH_CMD_FSTRD4B_OIOSTR_GD 0xCC +#define ROM_FLASH_CMD_FSTRD4B_OIODTR_GD 0xFD + +#define ROM_FLASH_CMD_PP_GD 0x02 +#define ROM_FLASH_CMD_PP4B_GD 0x12 +#define ROM_FLASH_CMD_PP_OOUT_GD 0x82 +#define ROM_FLASH_CMD_PP4B_OOUT_GD 0x84 +#define ROM_FLASH_CMD_PP_OIO_GD 0xC2 +#define ROM_FLASH_CMD_PP4B_OIOSTR_GD 0x8E + +#define ROM_FLASH_CMD_SE_GD 0x20 +#define ROM_FLASH_CMD_SE4B_GD 0x21 +#define ROM_FLASH_CMD_BE32K_GD 0x52 +#define ROM_FLASH_CMD_BE32K4B_GD 0x5C +#define ROM_FLASH_CMD_BE64K_GD 0xD8 +#define ROM_FLASH_CMD_BE64K4B_GD 0xDC + +#define ROM_FLASH_CMD_EN4B_GD 0xB7 +#define ROM_FLASH_CMD_DIS4B_GD 0xE9 + +// spi user mode command config + +/** + * @brief Config the spi user command + * @param spi_num spi port + * @param pcmd pointer to accept the spi command struct + */ +void esp_rom_spi_cmd_config(int spi_num, esp_rom_spi_cmd_t* pcmd); + +/** + * @brief Start a spi user command sequence + * @param spi_num spi port + * @param rx_buf buffer pointer to receive data + * @param rx_len receive data length in byte + * @param cs_en_mask decide which cs to use, 0 for cs0, 1 for cs1 + * @param is_write_erase to indicate whether this is a write or erase operation, since the CPU would check permission + */ +void esp_rom_spi_cmd_start(int spi_num, uint8_t* rx_buf, uint16_t rx_len, uint8_t cs_en_mask, bool is_write_erase); + +/** + * @brief Config opi flash pads according to efuse settings. + */ +void esp_rom_opiflash_pin_config(void); + +// set SPI read/write mode +/** + * @brief Set SPI operation mode + * @param spi_num spi port + * @param mode Flash Read Mode + */ +void esp_rom_spi_set_op_mode(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Set data swap mode in DTR(DDR) mode + * @param spi_num spi port + * @param wr_swap to decide whether to swap fifo data in dtr write operation + * @param rd_swap to decide whether to swap fifo data in dtr read operation + */ +void esp_rom_spi_set_dtr_swap_mode(int spi, bool wr_swap, bool rd_swap); + + +/** + * @brief to send reset command in spi/opi-str/opi-dtr mode(for MX25UM25645G) + * @param spi_num spi port + */ +void esp_rom_opiflash_mode_reset(int spi_num); + +#if 0 +// MX25UM25645G opi flash interface +/** + * @brief To execute a flash operation command + * @param spi_num spi port + * @param mode Flash Read Mode + * @param cmd data to send in command field + * @param cmd_bit_len bit length of command field + * @param addr data to send in address field + * @param addr_bit_len bit length of address field + * @param dummy_bits bit length of dummy field + * @param mosi_data data buffer to be sent in mosi field + * @param mosi_bit_len bit length of data buffer to be sent in mosi field + * @param miso_data data buffer to accept data in miso field + * @param miso_bit_len bit length of data buffer to accept data in miso field + * @param cs_mark decide which cs pin to use. 0: cs0, 1: cs1 + * @param is_write_erase_operation to indicate whether this a write or erase flash operation + */ +void esp_rom_opiflash_exec_cmd(int spi_num, esp_rom_spiflash_read_mode_t mode, + uint32_t cmd, int cmd_bit_len, + uint32_t addr, int addr_bit_len, + int dummy_bits, + uint8_t* mosi_data, int mosi_bit_len, + uint8_t* miso_data, int miso_bit_len, + uint32_t cs_mask, + bool is_write_erase_operation); + +/** + * @brief send reset command to opi flash + * @param spi_num spi port + * @param mode Flash Operation Mode + */ +void esp_rom_opiflash_soft_reset(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read opi flash ID(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @return opi flash id + */ +uint32_t esp_rom_opiflash_read_id(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read opi flash status register(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @return opi flash status value + */ +uint8_t esp_rom_opiflash_rdsr(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief wait opi flash status register to be idle + * @param spi_num spi port + * @param mode Flash Operation Mode + */ +void esp_rom_opiflash_wait_idle(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read the config register2(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @param addr the address of configure register + * @return value of config register2 + */ +uint8_t esp_rom_opiflash_rdcr2(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t addr); + +/** + * @brief to write the config register2(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @param addr the address of config register + * @param val the value to write + */ +void esp_rom_opiflash_wrcr2(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t addr, uint8_t val); + +/** + * @brief to erase flash sector(for MX25UM25645G) + * @param spi_num spi port + * @param address the sector address to be erased + * @param mode Flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_sector(int spi_num, uint32_t address, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to erase flash block(for MX25UM25645G) + * @param spi_num spi port + * @param address the block address to be erased + * @param mode Flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_block_64k(int spi_num, uint32_t address, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to erase a flash area define by start address and length(for MX25UM25645G) + * @param spi_num spi port + * @param start_addr the start address to be erased + * @param area_len the erea length to be erased + * @param mode flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_area(int spi_num, uint32_t start_addr, uint32_t area_len, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read data from opi flash(for MX25UM25645G) + * @param spi_num spi port + * @param mode flash operation mode + * @param flash_addr flash address to read data from + * @param data_addr data buffer to accept the data + * @param len data length to be read + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_read(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t flash_addr, uint8_t *data_addr, int len); + +/** + * @brief to write data to opi flash(for MX25UM25645G) + * @param spi_num spi port + * @param mode flash operation mode + * @param flash_addr flash address to write data to + * @param data_addr data buffer to write to flash + * @param len data length to write + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_write(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t flash_addr, uint8_t *data_addr, uint32_t len); + +/** + * @brief to set opi flash operation mode(for MX25UM25645G) + * @param spi_num spi port + * @param cur_mode current operation mode + * @param target the target operation mode to be set + */ +void esp_rom_opiflash_set_mode(int spi_num, esp_rom_spiflash_read_mode_t cur_mode, esp_rom_spiflash_read_mode_t target_mode); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rsa_pss.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rsa_pss.h new file mode 100644 index 00000000..bfbaeb6a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rsa_pss.h @@ -0,0 +1,45 @@ +// Copyright 2015-2018 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. + +#ifndef _ROM_RSA_PSS_H_ +#define _ROM_RSA_PSS_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ETS_SIG_LEN 384 /* Bytes */ +#define ETS_DIGEST_LEN 32 /* SHA-256, bytes */ + +typedef struct { + uint8_t n[384]; /* Public key modulus */ + uint32_t e; /* Public key exponent */ + uint8_t rinv[384]; + uint32_t mdash; +} ets_rsa_pubkey_t; + +bool ets_rsa_pss_verify(const ets_rsa_pubkey_t *key, const uint8_t *sig, const uint8_t *digest, uint8_t *verified_digest); + +void ets_mgf1_sha256(const uint8_t *mgfSeed, size_t seedLen, size_t maskLen, uint8_t *mask); + +bool ets_emsa_pss_verify(const uint8_t *encoded_message, const uint8_t *mhash); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rtc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rtc.h new file mode 100644 index 00000000..509b6fd4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/rtc.h @@ -0,0 +1,238 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_RTC_H_ +#define _ROM_RTC_H_ + +#include "ets_sys.h" + +#include +#include + +#include "soc/soc.h" +#include "soc/rtc_cntl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup rtc_apis, rtc registers and memory related apis + * @brief rtc apis + */ + +/** @addtogroup rtc_apis + * @{ + */ + +/************************************************************************************** + * Note: * + * Some Rtc memory and registers are used, in ROM or in internal library. * + * Please do not use reserved or used rtc memory or registers. * + * * + ************************************************************************************* + * RTC Memory & Store Register usage + ************************************************************************************* + * rtc memory addr type size usage + * 0x3f421000(0x50000000) Slow SIZE_CP Co-Processor code/Reset Entry + * 0x3f421000+SIZE_CP Slow 8192-SIZE_CP + * + * 0x3ff80000(0x40070000) Fast 8192 deep sleep entry code + * + ************************************************************************************* + * RTC store registers usage + * RTC_CNTL_STORE0_REG Reserved + * RTC_CNTL_STORE1_REG RTC_SLOW_CLK calibration value + * RTC_CNTL_STORE2_REG Boot time, low word + * RTC_CNTL_STORE3_REG Boot time, high word + * RTC_CNTL_STORE4_REG External XTAL frequency + * RTC_CNTL_STORE5_REG APB bus frequency + * RTC_CNTL_STORE6_REG FAST_RTC_MEMORY_ENTRY + * RTC_CNTL_STORE7_REG FAST_RTC_MEMORY_CRC + ************************************************************************************* + */ + +#define RTC_SLOW_CLK_CAL_REG RTC_CNTL_STORE1_REG +#define RTC_BOOT_TIME_LOW_REG RTC_CNTL_STORE2_REG +#define RTC_BOOT_TIME_HIGH_REG RTC_CNTL_STORE3_REG +#define RTC_XTAL_FREQ_REG RTC_CNTL_STORE4_REG +#define RTC_APB_FREQ_REG RTC_CNTL_STORE5_REG +#define RTC_ENTRY_ADDR_REG RTC_CNTL_STORE6_REG +#define RTC_RESET_CAUSE_REG RTC_CNTL_STORE6_REG +#define RTC_MEMORY_CRC_REG RTC_CNTL_STORE7_REG + +#define RTC_DISABLE_ROM_LOG ((1 << 0) | (1 << 16)) //!< Disable logging from the ROM code. + +typedef enum { + AWAKE = 0, // +#include "ets_sys.h" +#include "rsa_pss.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct ets_secure_boot_sig_block; +struct ets_secure_boot_signature_t; + +typedef struct ets_secure_boot_sig_block ets_secure_boot_sig_block_t; +typedef struct ets_secure_boot_signature ets_secure_boot_signature_t; +typedef struct ets_secure_boot_key_digests ets_secure_boot_key_digests_t; + +/* Anti-FI measure: use full words for success/fail, instead of + 0/non-zero +*/ +typedef enum { + SB_SUCCESS = 0x3A5A5AA5, + SB_FAILED = 0x7533885E, +} ets_secure_boot_status_t; + + +/* Verify and stage-load the bootloader image + (reconfigures cache to map, loads trusted key digests from efuse, + copies the bootloader into the staging buffer.) + + If allow_key_revoke is true and aggressive revoke efuse is set, + any failed signature has its associated key revoked in efuse. + + If result is SB_SUCCESS, the "simple hash" of the bootloader + is copied into verified_hash. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_stage_bootloader(uint8_t *verified_hash, bool allow_key_revoke); + +/* Verify bootloader image (reconfigures cache to map), + with key digests provided as parameters.) + + Can be used to verify secure boot status before enabling + secure boot permanently. + + If stage_load parameter is true, bootloader is copied into staging + buffer in RAM at the same time. + + If result is SB_SUCCESS, the "simple hash" of the bootloader is + copied into verified_hash. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_bootloader_with_keys(uint8_t *verified_hash, const ets_secure_boot_key_digests_t *trusted_keys, bool stage_load); + +/* Read key digests from efuse. Any revoked/missing digests will be + marked as NULL +*/ +ETS_STATUS ets_secure_boot_read_key_digests(ets_secure_boot_key_digests_t *trusted_keys); + +/* Verify supplied signature against supplied digest, using + supplied trusted key digests. + + Doesn't reconfigure cache or any other hardware access except for RSA peripheral. + + If result is SB_SUCCESS, the image_digest value is copied into verified_digest. +*/ +ets_secure_boot_status_t ets_secure_boot_verify_signature(const ets_secure_boot_signature_t *sig, const uint8_t *image_digest, const ets_secure_boot_key_digests_t *trusted_keys, uint8_t *verified_digest); + +/* Revoke a public key digest in efuse. + @param index Digest to revoke. Must be 0, 1 or 2. + */ +void ets_secure_boot_revoke_public_key_digest(int index); + +#define CRC_SIGN_BLOCK_LEN 1196 +#define SIG_BLOCK_PADDING 4096 +#define ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC 0xE7 + +/* Secure Boot V2 signature block + + (Up to 3 in a signature sector are appended to the image) + */ +struct ets_secure_boot_sig_block { + uint8_t magic_byte; + uint8_t version; + uint8_t _reserved1; + uint8_t _reserved2; + uint8_t image_digest[32]; + ets_rsa_pubkey_t key; + uint8_t signature[384]; + uint32_t block_crc; + uint8_t _padding[16]; +}; + +_Static_assert(sizeof(ets_secure_boot_sig_block_t) == 1216, "invalid sig block size"); + +#define SECURE_BOOT_NUM_BLOCKS 3 + +/* V2 Secure boot signature sector (up to 3 blocks) */ +struct ets_secure_boot_signature { + ets_secure_boot_sig_block_t block[SECURE_BOOT_NUM_BLOCKS]; + uint8_t _padding[4096 - (sizeof(ets_secure_boot_sig_block_t) * SECURE_BOOT_NUM_BLOCKS)]; +}; + +_Static_assert(sizeof(ets_secure_boot_signature_t) == 4096, "invalid sig sector size"); + +#define MAX_KEY_DIGESTS 3 + +struct ets_secure_boot_key_digests { + const void *key_digests[MAX_KEY_DIGESTS]; + bool allow_key_revoke; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SECURE_BOOT_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/sha.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/sha.h new file mode 100644 index 00000000..f04e9aec --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/sha.h @@ -0,0 +1,74 @@ +/* + ROM functions for hardware SHA support. + + It is not recommended to use these functions directly. If using + them from esp-idf then use the esp_sha_lock_engine() and + esp_sha_lock_memory_block() functions in hwcrypto/sha.h to ensure + exclusive access. + */ +// Copyright 2015-2016 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. +#ifndef _ROM_SHA_H_ +#define _ROM_SHA_H_ + +#include +#include +#include "ets_sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SHA1 = 0, + SHA2_224, + SHA2_256, + SHA2_384, + SHA2_512, + SHA2_512224, + SHA2_512256, + SHA2_512T, + SHA_TYPE_MAX +} SHA_TYPE; + +typedef struct SHAContext { + bool start; + bool in_hardware; // Is this context currently in peripheral? Needs to be manually cleared if multiple SHAs are interleaved + SHA_TYPE type; + uint32_t state[16]; // For SHA1/SHA224/SHA256, used 8, other used 16 + unsigned char buffer[128]; // For SHA1/SHA224/SHA256, used 64, other used 128 + uint32_t total_bits[4]; +} SHA_CTX; + +void ets_sha_enable(void); + +void ets_sha_disable(void); + +ets_status_t ets_sha_init(SHA_CTX *ctx, SHA_TYPE type); + +ets_status_t ets_sha_starts(SHA_CTX *ctx, uint16_t sha512_t); + +void ets_sha_get_state(SHA_CTX *ctx); + +void ets_sha_process(SHA_CTX *ctx, const unsigned char *input); + +void ets_sha_update(SHA_CTX *ctx, const unsigned char *input, uint32_t input_bytes, bool update_ctx); + +ets_status_t ets_sha_finish(SHA_CTX *ctx, unsigned char *output); + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SHA_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/spi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/spi_flash.h new file mode 100644 index 00000000..c93b4e27 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/spi_flash.h @@ -0,0 +1,579 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_SPI_FLASH_H_ +#define _ROM_SPI_FLASH_H_ + +#ifndef CONFIG_IDF_TARGET_ESP32S2 +#error This file should only be included for ESP32-S2 target +#endif + +#include +#include + +#include "esp_attr.h" +#include "soc/spi_mem_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup spi_flash_apis, spi flash operation related apis + * @brief spi_flash apis + */ + +/** @addtogroup spi_flash_apis + * @{ + */ + +/************************************************************* + * Note + ************************************************************* + * 1. ESP32 chip have 4 SPI slave/master, however, SPI0 is + * used as an SPI master to access Flash and ext-SRAM by + * Cache module. It will support Decryto read for Flash, + * read/write for ext-SRAM. And SPI1 is also used as an + * SPI master for Flash read/write and ext-SRAM read/write. + * It will support Encrypto write for Flash. + * 2. As an SPI master, SPI support Highest clock to 80M, + * however, Flash with 80M Clock should be configured + * for different Flash chips. If you want to use 80M + * clock We should use the SPI that is certified by + * Espressif. However, the certification is not started + * at the time, so please use 40M clock at the moment. + * 3. SPI Flash can use 2 lines or 4 lines mode. If you + * use 2 lines mode, you can save two pad SPIHD and + * SPIWP for gpio. ESP32 support configured SPI pad for + * Flash, the configuration is stored in efuse and flash. + * However, the configurations of pads should be certified + * by Espressif. If you use this function, please use 40M + * clock at the moment. + * 4. ESP32 support to use Common SPI command to configure + * Flash to QIO mode, if you failed to configure with fix + * command. With Common SPI Command, ESP32 can also provide + * a way to use same Common SPI command groups on different + * Flash chips. + * 5. This functions are not protected by packeting, Please use the + ************************************************************* + */ + +#define PERIPHS_SPI_FLASH_CMD SPI_MEM_CMD_REG(1) +#define PERIPHS_SPI_FLASH_ADDR SPI_MEM_ADDR_REG(1) +#define PERIPHS_SPI_FLASH_CTRL SPI_MEM_CTRL_REG(1) +#define PERIPHS_SPI_FLASH_CTRL1 SPI_MEM_CTRL1_REG(1) +#define PERIPHS_SPI_FLASH_STATUS SPI_MEM_RD_STATUS_REG(1) +#define PERIPHS_SPI_FLASH_USRREG SPI_MEM_USER_REG(1) +#define PERIPHS_SPI_FLASH_USRREG1 SPI_MEM_USER1_REG(1) +#define PERIPHS_SPI_FLASH_USRREG2 SPI_MEM_USER2_REG(1) +#define PERIPHS_SPI_FLASH_C0 SPI_MEM_W0_REG(1) +#define PERIPHS_SPI_FLASH_C1 SPI_MEM_W1_REG(1) +#define PERIPHS_SPI_FLASH_C2 SPI_MEM_W2_REG(1) +#define PERIPHS_SPI_FLASH_C3 SPI_MEM_W3_REG(1) +#define PERIPHS_SPI_FLASH_C4 SPI_MEM_W4_REG(1) +#define PERIPHS_SPI_FLASH_C5 SPI_MEM_W5_REG(1) +#define PERIPHS_SPI_FLASH_C6 SPI_MEM_W6_REG(1) +#define PERIPHS_SPI_FLASH_C7 SPI_MEM_W7_REG(1) +#define PERIPHS_SPI_FLASH_TX_CRC SPI_MEM_TX_CRC_REG(1) + +#define SPI0_R_QIO_DUMMY_CYCLELEN 5 +#define SPI0_R_QIO_ADDR_BITSLEN 23 +#define SPI0_R_FAST_DUMMY_CYCLELEN 7 +#define SPI0_R_DIO_DUMMY_CYCLELEN 3 +#define SPI0_R_FAST_ADDR_BITSLEN 23 +#define SPI0_R_SIO_ADDR_BITSLEN 23 + +#define SPI1_R_QIO_DUMMY_CYCLELEN 5 +#define SPI1_R_QIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_DUMMY_CYCLELEN 7 +#define SPI1_R_DIO_DUMMY_CYCLELEN 3 +#define SPI1_R_DIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_ADDR_BITSLEN 23 +#define SPI1_R_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_W_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_TWO_BYTE_STATUS_EN SPI_MEM_WRSR_2B + +//SPI address register +#define ESP_ROM_SPIFLASH_BYTES_LEN 24 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_WRITE_NUM 32 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM 16 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_BITS 0xf + +//SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 +#define ESP_ROM_SPIFLASH_BP_MASK_ISSI (BIT7 | BIT5 | BIT4 | BIT3 | BIT2) + +#define FLASH_ID_GD25LQ32C 0xC86016 + +typedef enum { + ESP_ROM_SPIFLASH_QIO_MODE = 0, + ESP_ROM_SPIFLASH_QOUT_MODE, + ESP_ROM_SPIFLASH_DIO_MODE, + ESP_ROM_SPIFLASH_DOUT_MODE, + ESP_ROM_SPIFLASH_FASTRD_MODE, + ESP_ROM_SPIFLASH_SLOWRD_MODE, + ESP_ROM_SPIFLASH_OPI_STR_MODE, + ESP_ROM_SPIFLASH_OPI_DTR_MODE, + ESP_ROM_SPIFLASH_OOUT_MODE, + ESP_ROM_SPIFLASH_OIO_STR_MODE, + ESP_ROM_SPIFLASH_OIO_DTR_MODE, +} esp_rom_spiflash_read_mode_t; + +typedef enum { + ESP_ROM_SPIFLASH_RESULT_OK, + ESP_ROM_SPIFLASH_RESULT_ERR, + ESP_ROM_SPIFLASH_RESULT_TIMEOUT +} esp_rom_spiflash_result_t; + +typedef struct { + uint32_t device_id; + uint32_t chip_size; // chip size in bytes + uint32_t block_size; + uint32_t sector_size; + uint32_t page_size; + uint32_t status_mask; +} esp_rom_spiflash_chip_t; + +typedef struct { + uint8_t data_length; + uint8_t read_cmd0; + uint8_t read_cmd1; + uint8_t write_cmd; + uint16_t data_mask; + uint16_t data; +} esp_rom_spiflash_common_cmd_t; + +/** + * @brief Fix the bug in SPI hardware communication with Flash/Ext-SRAM in High Speed. + * Please do not call this function in SDK. + * + * @param uint8_t spi: 0 for SPI0(Cache Access), 1 for SPI1(Flash read/write). + * + * @param uint8_t freqdiv: Pll is 80M, 4 for 20M, 3 for 26.7M, 2 for 40M, 1 for 80M. + * + * @return None + */ +void esp_rom_spiflash_fix_dummylen(uint8_t spi, uint8_t freqdiv); + +/** + * @brief Select SPI Flash to QIO mode when WP pad is read from Flash. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_qiomode(uint8_t wp_gpio_num, uint32_t ishspi); + +/** + * @brief Set SPI Flash pad drivers. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t *drvs: drvs[0]-bit[3:0] for cpiclk, bit[7:4] for spiq, drvs[1]-bit[3:0] for spid, drvs[1]-bit[7:4] for spid + * drvs[2]-bit[3:0] for spihd, drvs[2]-bit[7:4] for spiwp. + * Values usually read from falsh by rom code, function usually callde by rom code. + * if value with bit(3) set, the value is valid, bit[2:0] is the real value. + * + * @return None + */ +void esp_rom_spiflash_set_drvs(uint8_t wp_gpio_num, uint32_t ishspi, uint8_t *drvs); + +/** + * @brief Select SPI Flash function for pads. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_padsfunc(uint32_t ishspi); + +/** + * @brief SPI Flash init, clock divisor is 4, use 1 line Slow read mode. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t legacy: In legacy mode, more SPI command is used in line. + * + * @return None + */ +void esp_rom_spiflash_attach(uint32_t ishspi, bool legacy); + +/** + * @brief SPI Read Flash status register. We use CMD 0x05 (RDSR). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_status(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief SPI Read Flash status register bits 8-15. We use CMD 0x35 (RDSR2). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_statushigh(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief Write status to Falsh status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t status_value : Value to . + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_status(esp_rom_spiflash_chip_t *spi, uint32_t status_value); + +/** + * @brief Use a command to Read Flash status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t*status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_user_cmd(uint32_t *status, uint8_t cmd); + +/** + * @brief Config SPI Flash read mode when init. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_read_mode_t mode : QIO/QOUT/DIO/DOUT/FastRD/SlowRD. + * + * This function does not try to set the QIO Enable bit in the status register, caller is responsible for this. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_readmode(esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Config SPI Flash clock divisor. + * Please do not call this function in SDK. + * + * @param uint8_t freqdiv: clock divisor. + * + * @param uint8_t spi: 0 for SPI0, 1 for SPI1. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_clk(uint8_t freqdiv, uint8_t spi); + +/** + * @brief Send CommonCmd to Flash so that is can go into QIO mode, some Flash use different CMD. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_common_cmd_t *cmd : A struct to show the action of a command. + * + * @return uint16_t 0 : do not send command any more. + * 1 : go to the next command. + * n > 1 : skip (n - 1) commands. + */ +uint16_t esp_rom_spiflash_common_cmd(esp_rom_spiflash_common_cmd_t *cmd); + +/** + * @brief Unlock SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Unlock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Unlock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Unlock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_unlock(void); + +/** + * @brief SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Lock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Lock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Lock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_lock(void); + +/** + * @brief Update SPI Flash parameter. + * Please do not call this function in SDK. + * + * @param uint32_t deviceId : Device ID read from SPI, the low 32 bit. + * + * @param uint32_t chip_size : The Flash size. + * + * @param uint32_t block_size : The Flash block size. + * + * @param uint32_t sector_size : The Flash sector size. + * + * @param uint32_t page_size : The Flash page size. + * + * @param uint32_t status_mask : The Mask used when read status from Flash(use single CMD). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Update OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Update error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Update timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_param(uint32_t deviceId, uint32_t chip_size, uint32_t block_size, + uint32_t sector_size, uint32_t page_size, uint32_t status_mask); + +/** + * @brief Erase whole flash chip. + * Please do not call this function in SDK. + * + * @param None + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_chip(void); + +/** + * @brief Erase a 64KB block of flash + * Uses SPI flash command D8H. + * Please do not call this function in SDK. + * + * @param uint32_t block_num : Which block to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_block(uint32_t block_num); + +/** + * @brief Erase a sector of flash. + * Uses SPI flash command 20H. + * Please do not call this function in SDK. + * + * @param uint32_t sector_num : Which sector to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_sector(uint32_t sector_num); + +/** + * @brief Erase some sectors. + * Please do not call this function in SDK. + * + * @param uint32_t start_addr : Start addr to erase, should be sector aligned. + * + * @param uint32_t area_len : Length to erase, should be sector aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_area(uint32_t start_addr, uint32_t area_len); + +/** + * @brief Write Data to Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t dest_addr : Address to write, should be 4 bytes aligned. + * + * @param const uint32_t *src : The pointer to data which is to write. + * + * @param uint32_t len : Length to write, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write(uint32_t dest_addr, const uint32_t *src, int32_t len); + +/** + * @brief Read Data from Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t src_addr : Address to read, should be 4 bytes aligned. + * + * @param uint32_t *dest : The buf to read the data. + * + * @param uint32_t len : Length to read, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read(uint32_t src_addr, uint32_t *dest, int32_t len); + +/** + * @brief SPI1 go into encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_enable(void); + +/** + * @brief Prepare 32 Bytes data to encrpto writing, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 bytes aligned. + * + * @param uint32_t *data : The pointer to data which is to write. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Prepare OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Prepare error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Prepare timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_prepare_encrypted_data(uint32_t flash_addr, uint32_t *data); + +/** + * @brief SPI1 go out of encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_disable(void); + +/** + * @brief Write data to flash with transparent encryption. + * @note Sectors to be written should already be erased. + * + * @note Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 byte aligned. + * + * @param uint32_t *data : The pointer to data to write. Note, this pointer must + * be 32 bit aligned and the content of the data will be + * modified by the encryption function. + * + * @param uint32_t len : Length to write, should be 32 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Data written successfully. + * ESP_ROM_SPIFLASH_RESULT_ERR : Encryption write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Encrypto write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_encrypted(uint32_t flash_addr, uint32_t *data, uint32_t len); + + +/* TODO: figure out how to map these to their new names */ +typedef enum { + SPI_ENCRYPT_DESTINATION_FLASH, + SPI_ENCRYPT_DESTINATION_PSRAM, +} SpiEncryptDest; + +typedef esp_rom_spiflash_result_t SpiFlashOpResult; + +SpiFlashOpResult SPI_Encrypt_Write(uint32_t flash_addr, const void* data, uint32_t len); +SpiFlashOpResult SPI_Encrypt_Write_Dest(SpiEncryptDest dest, uint32_t flash_addr, const void* data, uint32_t len); +void SPI_Write_Encrypt_Enable(void); +void SPI_Write_Encrypt_Disable(void); + +/** @brief Wait until SPI flash write operation is complete + * + * @note Please do not call this function in SDK. + * + * Reads the Write In Progress bit of the SPI flash status register, + * repeats until this bit is zero (indicating write complete). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write is complete + * ESP_ROM_SPIFLASH_RESULT_ERR : Error while reading status. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_wait_idle(esp_rom_spiflash_chip_t *spi); + + +/** @brief Enable Quad I/O pin functions + * + * @note Please do not call this function in SDK. + * + * Sets the HD & WP pin functions for Quad I/O modes, based on the + * efuse SPI pin configuration. + * + * @param wp_gpio_num - Number of the WP pin to reconfigure for quad I/O. + * + * @param spiconfig - Pin configuration, as returned from ets_efuse_get_spiconfig(). + * - If this parameter is 0, default SPI pins are used and wp_gpio_num parameter is ignored. + * - If this parameter is 1, default HSPI pins are used and wp_gpio_num parameter is ignored. + * - For other values, this parameter encodes the HD pin number and also the CLK pin number. CLK pin selection is used + * to determine if HSPI or SPI peripheral will be used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). + * Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral. + */ +void esp_rom_spiflash_select_qio_pins(uint8_t wp_gpio_num, uint32_t spiconfig); + +/** + * @brief Clear WEL bit unconditionally. + * + * @return always ESP_ROM_SPIFLASH_RESULT_OK + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_disable(void); + +/** @brief Global esp_rom_spiflash_chip_t structure used by ROM functions + * + */ +extern esp_rom_spiflash_chip_t g_rom_flashchip; + +extern uint8_t g_rom_spiflash_dummy_len_plus[]; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_SPI_FLASH_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/uart.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/uart.h new file mode 100644 index 00000000..899413f3 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/uart.h @@ -0,0 +1,456 @@ +// Copyright 2010-2016 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. + +#ifndef _ROM_UART_H_ +#define _ROM_UART_H_ + +#include "esp_types.h" +#include "esp_attr.h" +#include "ets_sys.h" +#include "soc/soc.h" +#include "soc/uart_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + +#define RX_BUFF_SIZE 0x400 +#define TX_BUFF_SIZE 100 + +//uart int enalbe register ctrl bits +#define UART_RCV_INTEN BIT0 +#define UART_TRX_INTEN BIT1 +#define UART_LINE_STATUS_INTEN BIT2 + +//uart int identification ctrl bits +#define UART_INT_FLAG_MASK 0x0E + +//uart fifo ctrl bits +#define UART_CLR_RCV_FIFO BIT1 +#define UART_CLR_TRX_FIFO BIT2 +#define UART_RCVFIFO_TRG_LVL_BITS BIT6 + +//uart line control bits +#define UART_DIV_LATCH_ACCESS_BIT BIT7 + +//uart line status bits +#define UART_RCV_DATA_RDY_FLAG BIT0 +#define UART_RCV_OVER_FLOW_FLAG BIT1 +#define UART_RCV_PARITY_ERR_FLAG BIT2 +#define UART_RCV_FRAME_ERR_FLAG BIT3 +#define UART_BRK_INT_FLAG BIT4 +#define UART_TRX_FIFO_EMPTY_FLAG BIT5 +#define UART_TRX_ALL_EMPTY_FLAG BIT6 // include fifo and shift reg +#define UART_RCV_ERR_FLAG BIT7 + +//send and receive message frame head +#define FRAME_FLAG 0x7E + +typedef enum { + UART_LINE_STATUS_INT_FLAG = 0x06, + UART_RCV_FIFO_INT_FLAG = 0x04, + UART_RCV_TMOUT_INT_FLAG = 0x0C, + UART_TXBUFF_EMPTY_INT_FLAG = 0x02 +} UartIntType; //consider bit0 for int_flag + +typedef enum { + RCV_ONE_BYTE = 0x0, + RCV_FOUR_BYTE = 0x1, + RCV_EIGHT_BYTE = 0x2, + RCV_FOURTEEN_BYTE = 0x3 +} UartRcvFifoTrgLvl; + +typedef enum { + FIVE_BITS = 0x0, + SIX_BITS = 0x1, + SEVEN_BITS = 0x2, + EIGHT_BITS = 0x3 +} UartBitsNum4Char; + +typedef enum { + ONE_STOP_BIT = 1, + ONE_HALF_STOP_BIT = 2, + TWO_STOP_BIT = 3 +} UartStopBitsNum; + +typedef enum { + NONE_BITS = 0, + ODD_BITS = 2, + EVEN_BITS = 3 + +} UartParityMode; + +typedef enum { + STICK_PARITY_DIS = 0, + STICK_PARITY_EN = 2 +} UartExistParity; + +typedef enum { + BIT_RATE_9600 = 9600, + BIT_RATE_19200 = 19200, + BIT_RATE_38400 = 38400, + BIT_RATE_57600 = 57600, + BIT_RATE_115200 = 115200, + BIT_RATE_230400 = 230400, + BIT_RATE_460800 = 460800, + BIT_RATE_921600 = 921600 +} UartBautRate; + +typedef enum { + NONE_CTRL, + HARDWARE_CTRL, + XON_XOFF_CTRL +} UartFlowCtrl; + +typedef enum { + EMPTY, + UNDER_WRITE, + WRITE_OVER +} RcvMsgBuffState; + +typedef struct { + uint8_t *pRcvMsgBuff; + uint8_t *pWritePos; + uint8_t *pReadPos; + uint8_t TrigLvl; + RcvMsgBuffState BuffState; +} RcvMsgBuff; + +typedef struct { + uint32_t TrxBuffSize; + uint8_t *pTrxBuff; +} TrxMsgBuff; + +typedef enum { + BAUD_RATE_DET, + WAIT_SYNC_FRM, + SRCH_MSG_HEAD, + RCV_MSG_BODY, + RCV_ESC_CHAR, +} RcvMsgState; + +typedef struct { + UartBautRate baut_rate; + UartBitsNum4Char data_bits; + UartExistParity exist_parity; + UartParityMode parity; // chip size in byte + UartStopBitsNum stop_bits; + UartFlowCtrl flow_ctrl; + uint8_t buff_uart_no; //indicate which uart use tx/rx buffer + RcvMsgBuff rcv_buff; +// TrxMsgBuff trx_buff; + RcvMsgState rcv_state; + int received; +} UartDevice; + +/** + * @brief Init uart device struct value and reset uart0/uart1 rx. + * Please do not call this function in SDK. + * + * @param rxBuffer, must be a pointer to RX_BUFF_SIZE bytes or NULL + * + * @return None + */ +void uartAttach(void *rxBuffer); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, else for UART1. + * + * @param uint32_t clock : clock used by uart module, to adjust baudrate. + * + * @return None + */ +void Uart_Init(uint8_t uart_no, uint32_t clock); + +/** + * @brief Modify uart baudrate. + * This function will reset RX/TX fifo for uart. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint32_t DivLatchValue : (clock << 4)/baudrate. + * + * @return None + */ +void uart_div_modify(uint8_t uart_no, uint32_t DivLatchValue); + + +/** + * @brief Re-calculate UART baudrate divisor for a given (changed) + * clock speed. + * This function will not reset RX/TX fifo for uart. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint32_t clock : clock used by uart module, to adjust baudrate. + * + * @return None + */ +void uart_div_reinit(uint8_t uart_no, uint32_t clock); + + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint8_t is_sync : 0, only one UART module, easy to detect, wait until detected; + * 1, two UART modules, hard to detect, detect and return. + * + * @return None + */ +int uart_baudrate_detect(uint8_t uart_no, uint8_t is_sync); + +/** + * @brief Switch printf channel of uart_tx_one_char. + * Please do not call this function when printf. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_tx_switch(uint8_t uart_no); + +/** + * @brief Switch message exchange channel for UART download booting. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_buff_switch(uint8_t uart_no); + +/** + * @brief Output a char to printf channel, wait until fifo not full. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char(uint8_t TxChar); + +/** + * @brief Output a char to message exchange channel, wait until fifo not full. + * Please do not call this function in SDK. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char2(uint8_t TxChar); + +/** + * @brief Wait until uart tx full empty. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None. + */ +void uart_tx_flush(uint8_t uart_no); + +/** + * @brief Wait until uart tx full empty and the last char send ok. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2 + * + * The function defined in ROM code has a bug, so we define the correct version + * here for compatibility. + */ +void uart_tx_wait_idle(uint8_t uart_no); + +/** + * @brief Get an input char from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pRxChar : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_one_char(uint8_t *pRxChar); + +/** + * @brief Get an input char from message channel, wait until successful. + * Please do not call this function in SDK. + * + * @param None + * + * @return char : input char value. + */ +char uart_rx_one_char_block(void); + +/** + * @brief Get an input string line from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pString : the pointer to store the string. + * + * @param uint8_t MaxStrlen : the max string length, incude '\0'. + * + * @return OK. + */ +STATUS UartRxString(uint8_t *pString, uint8_t MaxStrlen); + +/** + * @brief Process uart recevied information in the interrupt handler. + * Please do not call this function in SDK. + * + * @param void *para : the message receive buffer. + * + * @return None + */ +void uart_rx_intr_handler(void *para); + +/** + * @brief Get an char from receive buffer. + * Please do not call this function in SDK. + * + * @param RcvMsgBuff *pRxBuff : the pointer to the struct that include receive buffer. + * + * @param uint8_t *pRxByte : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_readbuff( RcvMsgBuff *pRxBuff, uint8_t *pRxByte); + +/** + * @brief Get all chars from receive buffer. + * Please do not call this function in SDK. + * + * @param uint8_t *pCmdLn : the pointer to store the string. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS UartGetCmdLn(uint8_t *pCmdLn); + +/** + * @brief Get uart configuration struct. + * Please do not call this function in SDK. + * + * @param None + * + * @return UartDevice * : uart configuration struct pointer. + */ +UartDevice *GetUartDevice(void); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to output string. + * + * @param int len : the string length. + * + * @return None. + */ +void send_packet(uint8_t *p, int len); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to input string. + * + * @param int len : If string length > len, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return int : the length of the string. + */ +int recv_packet(uint8_t *p, int len, uint8_t is_sync); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t DataLen : the string length. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS SendMsg(uint8_t *pData, uint16_t DataLen); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t MaxDataLen : If string length > MaxDataLen, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS RcvMsg(uint8_t *pData, uint16_t MaxDataLen, uint8_t is_sync); + +/** + * @brief Check if this UART is in download connection. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return ETS_NO_BOOT = 0 for no. + * SEL_UART_BOOT = BIT(1) for yes. + */ +uint8_t UartConnCheck(uint8_t uart_no); + +/** + * @brief Initialize the USB ACM UART + * Needs to be fed a buffer of at least 128 bytes (ESP_ROM_CDC_ACM_WORK_BUF_MIN), + * plus any rx buffer you may want to have. + * + * @param cdc_acm_work_mem Pointer to work mem for CDC-ACM code + * @param cdc_acm_work_mem_len Length of work mem + */ +void Uart_Init_USB(void *cdc_acm_work_mem, int cdc_acm_work_mem_len); + + +/** + * @brief Install handler to reset the chip when a RTS change has been detected on the CDC-ACM 'UART'. + */ +void uart_usb_enable_reset_on_rts(void); + + +extern UartDevice UartDev; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* _ROM_UART_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cdc_acm.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cdc_acm.h new file mode 100644 index 00000000..90d71e81 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cdc_acm.h @@ -0,0 +1,262 @@ +/******************************************************************************* + * + * Copyright(c) 2015,2016 Intel Corporation. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void cdc_acm_device; +extern cdc_acm_device *uart_acm_dev; + +#define ACM_BYTES_PER_TX 64 + +//ACM statuses are negative to distinguish from USB_DC_* status codes +#define ACM_STATUS_LINESTATE_CHANGED -1 +#define ACM_STATUS_LINECODING_CHANGED -2 +#define ACM_STATUS_TX -3 +#define ACM_STATUS_RX -4 + +typedef void(*uart_irq_callback_t)(cdc_acm_device *dev, int status); + +/** + * @brief Get amount of received characters in buffer + * + * @returns character count + */ + +int cdc_acm_rx_fifo_cnt(cdc_acm_device *dev); + + +/* + * @brief Poll the device for input. + * + * @return -ENOTSUP Since underlying USB device controller always uses + * interrupts, polled mode UART APIs are not implemented for the UART interface + * exported by CDC ACM driver. Apps should use fifo_read API instead. + */ + +int cdc_acm_poll_in(cdc_acm_device *dev, unsigned char *c); + +/* + * @brief Output a character in polled mode. + * + * The UART poll method for USB UART is simulated by waiting till + * we get the next BULK In upcall from the USB device controller or 100 ms. + * + * @return the same character which is sent + */ +unsigned char cdc_acm_poll_out(cdc_acm_device *dev, unsigned char c); + +/** + * @brief Fill FIFO with data + * + * @param dev CDC ACM device struct. + * @param tx_data Data to transmit. + * @param len Number of bytes to send. + * + * @return Number of bytes sent. + */ +int cdc_acm_fifo_fill(cdc_acm_device *dev, const uint8_t *tx_data, int len); + +/** + * @brief Read data from FIFO + * + * @param dev CDC ACM device struct. + * @param rx_data Pointer to data container. + * @param size Container size. + * + * @return Number of bytes read. + */ +int cdc_acm_fifo_read(cdc_acm_device *dev, uint8_t *rx_data, const int size); + +/** + * @brief Enable TX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_tx_enable(cdc_acm_device *dev); + +/** + * @brief Disable TX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_tx_disable(cdc_acm_device *dev); + +/** + * @brief Check if Tx IRQ has been raised + * + * @param dev CDC ACM device struct. + * + * @return 1 if a Tx IRQ is pending, 0 otherwise. + */ +int cdc_acm_irq_tx_ready(cdc_acm_device *dev); + +/** + * @brief Enable RX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A + */ +void cdc_acm_irq_rx_enable(cdc_acm_device *dev); + +/** + * @brief Disable RX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_rx_disable(cdc_acm_device *dev); + +/** + * @brief Enable line state interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_state_enable(cdc_acm_device *dev); + +/** + * @brief Disable line state interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_state_disable(cdc_acm_device *dev); + + +/** + * @brief Check if Rx IRQ has been raised + * + * @param dev CDC ACM device struct. + * + * @return 1 if an IRQ is ready, 0 otherwise. + */ +int cdc_acm_irq_rx_ready(cdc_acm_device *dev); + +/** + * @brief Check if Tx or Rx IRQ is pending + * + * @param dev CDC ACM device struct. + * + * @return 1 if a Tx or Rx IRQ is pending, 0 otherwise. + */ +int cdc_acm_irq_is_pending(cdc_acm_device *dev); + +/** + * @brief Set the callback function pointer for IRQ. + * + * @param dev CDC ACM device struct. + * @param cb Callback function pointer. + * + * @return N/A + */ +void cdc_acm_irq_callback_set(cdc_acm_device *dev, uart_irq_callback_t cb); + +/** + * @brief Manipulate line control for UART. + * + * @param dev CDC ACM device struct + * @param ctrl The line control to be manipulated + * @param val Value to set the line control + * + * @return 0 if successful, failed otherwise. + */ +int cdc_acm_line_ctrl_set(cdc_acm_device *dev, uint32_t ctrl, uint32_t val); + +/** + * @brief Manipulate line control for UART. + * + * @param dev CDC ACM device struct + * @param ctrl The line control to be manipulated + * @param val Value to set the line control + * + * @return 0 if successful, failed otherwise. + */ +int cdc_acm_line_ctrl_get(cdc_acm_device *dev, uint32_t ctrl, uint32_t *val); + + +/** + * @brief Initialize UART channel + * + * This routine is called to reset the chip in a quiescent state. + * It is assumed that this function is called only once per UART. + * + * @param mem_chunk Memory chunk to use for internal use + * @param mem_chunk_size Size of the memory chunk in bytes + * + * @return dev or NULL + */ +cdc_acm_device *cdc_acm_init(void *mem_chunk, int mem_chunk_size); + + +/** Common line controls for UART.*/ +#define LINE_CTRL_BAUD_RATE (1 << 0) +#define LINE_CTRL_RTS (1 << 1) +#define LINE_CTRL_DTR (1 << 2) +#define LINE_CTRL_DCD (1 << 3) +#define LINE_CTRL_DSR (1 << 4) + +/* Common communication errors for UART.*/ + +/** @brief Overrun error */ +#define UART_ERROR_OVERRUN (1 << 0) + +/** @brief Parity error */ +#define UART_ERROR_PARITY (1 << 1) + +/** @brief Framing error */ +#define UART_ERROR_FRAMING (1 << 2) + +/** + * @brief Break interrupt error: + * + * A break interrupt was received. This happens when the serial input is + * held at a logic '0' state for longer than the sum of start time + data bits + * + parity + stop bits. + */ +#define UART_ERROR_BREAK (1 << 3) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/chip_usb_dw_wrapper.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/chip_usb_dw_wrapper.h new file mode 100644 index 00000000..a7c50643 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/chip_usb_dw_wrapper.h @@ -0,0 +1,30 @@ +// Copyright 2019-2020 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. + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int chip_usb_dw_init(void); +int chip_usb_dw_did_persist(void); +void chip_usb_dw_prepare_persist(void); +uint32_t chip_usb_get_persist_flags(void); +void chip_usb_set_persist_flags(uint32_t flags); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cpio.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cpio.h new file mode 100644 index 00000000..5603b3f5 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/cpio.h @@ -0,0 +1,180 @@ +// Copyright 2015-2016 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. + + +/** + * Archive to parse cpio data in the newc and crc formats. Generate a cpio archive like that by e.g. + * find . | cpio -o -H newc > archive.cpio + */ + +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define CPIO_MODE_FILETYPE_MASK 0xF000 +#define CPIO_MODE_FILETYPE_SOCKET 0xC000 +#define CPIO_MODE_FILETYPE_SYMLINK 0xA000 +#define CPIO_MODE_FILETYPE_REGULAR 0x8000 +#define CPIO_MODE_FILETYPE_BLOCKDEV 0x6000 +#define CPIO_MODE_FILETYPE_DIR 0x4000 +#define CPIO_MODE_FILETYPE_CHARDEV 0x2000 +#define CPIO_MODE_FILETYPE_FIFO 0x1000 +#define CPIO_MODE_SUID 0x0800 +#define CPIO_MODE_SGID 0x0400 +#define CPIO_MODE_STICKY 0x0200 + +typedef struct { + size_t filesize; + char *name; + uint32_t mode; + uint32_t check; +} cpio_file_t; + +typedef enum { + CPIO_RET_MORE = 0, + CPIO_RET_DONE, + CPIO_RET_ERR +} cpio_ret_t; + +typedef struct cpio_handle_data_t cpio_handle_data_t; +typedef cpio_handle_data_t *cpio_handle_t; + +typedef enum { + CPIO_RSN_FILE_ALL = 0, + CPIO_RSN_FILE_INITIAL, + CPIO_RSN_FILE_MORE, + CPIO_RSN_FILE_END +} cpio_callback_reason_t; + + +/** + * Callback for cpio file data. + * + * This callback will be called by the library to indicate data for a file is available. + * + * For files in the cpio archive that fit entirely in the internal buffer, or when no internal + * buffer is available, are entirely contained in the buffer fed to cpio_feed(), this callback + * is only called once, with reason=CPIO_RNS_FILE_ALL. fileinfo will contain the information + * for that specific file (name, size, ...), buff_offset will be 0, buff_len is the file + * size and buff contains all the information for the file. + * + * For files that do not fit in the buffer, this callback will be called multiple times. + * The initial time with reason=CPIO_RSN_FILE_INITIAL, when more data is available with + * CPIO_RSN_FILE_MORE and finally with CPIO_RSN_FILE_END. For these calls, fileinfo + * will again contain file information. buff will be the information contained in the + * file at offset buff_offset, and the lenght of this buffer will be in buff_len. + * + * The library guarantees to feed all file data to the callback consequitively, so + * within the same file, the buff_offset from a call will always be (buff_offset+buff_len) + * from the call before that. If cpio_start is + * + * The library also guarantees every file in the cpio archive will either generate a single + * callback call with CPIO_RSN_ALL, or multiple with in sequence CPIO_RSN_FILE_INITIAL, 0 or + * more CPIO_RSN_FILE_MORE and finally a CPIO_RSN_FILE_END. + * + * When a non-zero buffer size is passed to cpio_start, the library guarantees that all callback + * calls with a reason of CPIO_RSN_FILE_INITIAL and CPIO_RSN_FILE_MORE will have a buffer + * filled with exactly this amount of bytes. + * + */ +typedef void (*cpio_callback_t)(cpio_callback_reason_t reason, cpio_file_t *fileinfo, size_t buff_offset, size_t buff_len, char *buff, void *arg); + + +/** + * @brief Initialize a cpio handle. + * + * Call this to start parsing a cpio archive. You can set the callback that handles the + * files/data here. + * + * @param callback The callback that will handle the data of the files inside the cpio archive + * + * @param cbarg User-supplied argument. The callback will be called with this as an argument. + * + * @param buflen Length of internal buffer used. + * If this is zero, the callback will be called with data that lives in the data buffer + * supplied to the cpio library by whomever called cpio_feed(). Because this library has + * no power over that buffer, the callback can be passed as little as 1 and as many as + * INT_MAX bytes at a time. + * If this is non-zero, the library will allocate an internal buffer of this size. All + * cpio_feed()-calls will be rebuffered, and the callback is guaranteed to only be called + * with this many bytes in the buffer, given there's enough data in the file to fill it. + * + * @param memchunk Chunk of memory to allocate everything (handle, I/O buffer, filename buffer) in. Minimum size + * (estimate) is 160+buflen+sizeof(largest filename/path). + * @param memchunklen Size of the mem chunk + * + * @return + * - Success: A pointer to a cpio handle + * - Error: NULL + * + */ +cpio_handle_t cpio_start(cpio_callback_t callback, void *cbarg, size_t buflen, void *memchunk, int memchunklen); + +/** + * @brief Feed data from a cpio archive into the library + * + * This routine is used to feed consecutive data of the cpio archive into the library. While processing, + * the library can call the callback function one or more times if needed. + * + * @param cpio Handle obtained by calling cpio_start() + * + * @param buffer Pointer to buffer containing cpio archive data + * + * @param len Length of the buffer, in bytes + * + * @return + * - CPIO_RET_MORE: CPIO archive isn't done yet, please feed more data. + * - CPIO_RET_DONE: CPUI archive is finished. + * - CPIO_RET_ERR: Invalid CPIO archive data; decoding aborted. + * + */ +cpio_ret_t cpio_feed(cpio_handle_t cpio, char *buffer, int len); + +/** + * @brief Indicate there is no more cpio data to be fed into the archive + * + * This call is to be called when the source data is exhausted. Normally, the library can find the end of the + * cpio archive by looking for the end marker, + * + * @param timer_conf Pointer of LEDC timer configure struct + * + * + * @return + * - CPIO_RET_DONE on success + * - CPIO_RET_ERR when cpio archive is invalid + * + */ +cpio_ret_t cpio_done(cpio_handle_t cpio); + + +/** + * @brief Free the memory allocated for a cpio handle. + * + * @param cpio Handle obtained by calling cpio_start() + * + * @return + * - CPIO_RET_DONE on success + * + */ +cpio_ret_t cpio_destroy(cpio_handle_t cpio); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_cdc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_cdc.h new file mode 100644 index 00000000..c241bcfe --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_cdc.h @@ -0,0 +1,174 @@ +/* usb_cdc.h - USB CDC-ACM and CDC-ECM public header */ + +/* + * Copyright (c) 2017 PHYTEC Messtechnik GmbH + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/** + * @file + * @brief USB Communications Device Class (CDC) public header + * + * Header follows the Class Definitions for + * Communications Devices Specification (CDC120-20101103-track.pdf), + * PSTN Devices Specification (PSTN120.pdf) and + * Ethernet Control Model Devices Specification (ECM120.pdf). + * Header is limited to ACM and ECM Subclasses. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** CDC Specification release number in BCD format */ +#define CDC_SRN_1_20 0x0120 + +/** Communications Class Subclass Codes */ +#define ACM_SUBCLASS 0x02 +#define ECM_SUBCLASS 0x06 +#define EEM_SUBCLASS 0x0c + +/** Communications Class Protocol Codes */ +#define AT_CMD_V250_PROTOCOL 0x01 +#define EEM_PROTOCOL 0x07 + +/** + * @brief Data Class Interface Codes + * @note CDC120-20101103-track.pdf, 4.5, Table 6 + */ +#define DATA_INTERFACE_CLASS 0x0A + +/** + * @brief Values for the bDescriptorType Field + * @note CDC120-20101103-track.pdf, 5.2.3, Table 12 + */ +#define CS_INTERFACE 0x24 +#define CS_ENDPOINT 0x25 + +/** + * @brief bDescriptor SubType for Communications + * Class Functional Descriptors + * @note CDC120-20101103-track.pdf, 5.2.3, Table 13 + */ +#define HEADER_FUNC_DESC 0x00 +#define CALL_MANAGEMENT_FUNC_DESC 0x01 +#define ACM_FUNC_DESC 0x02 +#define UNION_FUNC_DESC 0x06 +#define ETHERNET_FUNC_DESC 0x0F + +/** + * @brief PSTN Subclass Specific Requests + * for ACM devices + * @note PSTN120.pdf, 6.3, Table 13 + */ +#define CDC_SEND_ENC_CMD 0x00 +#define CDC_GET_ENC_RSP 0x01 +#define SET_LINE_CODING 0x20 +#define GET_LINE_CODING 0x21 +#define SET_CONTROL_LINE_STATE 0x22 + +/** Control Signal Bitmap Values for SetControlLineState */ +#define SET_CONTROL_LINE_STATE_RTS 0x02 +#define SET_CONTROL_LINE_STATE_DTR 0x01 + +/** UART State Bitmap Values */ +#define SERIAL_STATE_OVERRUN 0x40 +#define SERIAL_STATE_PARITY 0x20 +#define SERIAL_STATE_FRAMING 0x10 +#define SERIAL_STATE_RING 0x08 +#define SERIAL_STATE_BREAK 0x04 +#define SERIAL_STATE_TX_CARRIER 0x02 +#define SERIAL_STATE_RX_CARRIER 0x01 + +/** + * @brief Class-Specific Request Codes for Ethernet subclass + * @note ECM120.pdf, 6.2, Table 6 + */ +#define SET_ETHERNET_MULTICAST_FILTERS 0x40 +#define SET_ETHERNET_PM_FILTER 0x41 +#define GET_ETHERNET_PM_FILTER 0x42 +#define SET_ETHERNET_PACKET_FILTER 0x43 +#define GET_ETHERNET_STATISTIC 0x44 + +/** Ethernet Packet Filter Bitmap */ +#define PACKET_TYPE_MULTICAST 0x10 +#define PACKET_TYPE_BROADCAST 0x08 +#define PACKET_TYPE_DIRECTED 0x04 +#define PACKET_TYPE_ALL_MULTICAST 0x02 +#define PACKET_TYPE_PROMISCUOUS 0x01 + +/** Header Functional Descriptor */ +struct cdc_header_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint16_t bcdCDC; +} __packed; + +/** Union Interface Functional Descriptor */ +struct cdc_union_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bControlInterface; + uint8_t bSubordinateInterface0; +} __packed; + +/** Call Management Functional Descriptor */ +struct cdc_cm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bmCapabilities; + uint8_t bDataInterface; +} __packed; + +/** Abstract Control Management Functional Descriptor */ +struct cdc_acm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bmCapabilities; +} __packed; + + +/** Data structure for GET_LINE_CODING / SET_LINE_CODING class requests */ +struct cdc_acm_line_coding { + uint32_t dwDTERate; + uint8_t bCharFormat; + uint8_t bParityType; + uint8_t bDataBits; +} __packed; + +/** Data structure for the notification about SerialState */ +struct cdc_acm_notification { + uint8_t bmRequestType; + uint8_t bNotificationType; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; + uint16_t data; +} __packed; + +/** Ethernet Networking Functional Descriptor */ +struct cdc_ecm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t iMACAddress; + uint32_t bmEthernetStatistics; + uint16_t wMaxSegmentSize; + uint16_t wNumberMCFilters; + uint8_t bNumberPowerFilters; +} __packed; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_common.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_common.h new file mode 100644 index 00000000..796a77bc --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_common.h @@ -0,0 +1,249 @@ +/*************************************************************************** + * + * + * Copyright(c) 2015,2016 Intel Corporation. + * Copyright(c) 2017 PHYTEC Messtechnik GmbH + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ***************************************************************************/ + +/** + * @file + * @brief useful constants and macros for the USB application + * + * This file contains useful constants and macros for the USB applications. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define BCD(x) ((((x) / 10) << 4) | ((x) / 10)) + +/* Descriptor size in bytes */ +#define USB_DEVICE_DESC_SIZE 18 +#define USB_CONFIGURATION_DESC_SIZE 9 +#define USB_INTERFACE_DESC_SIZE 9 +#define USB_ENDPOINT_DESC_SIZE 7 +#define USB_STRING_DESC_SIZE 4 +#define USB_HID_DESC_SIZE 9 +#define USB_DFU_DESC_SIZE 9 +#define USB_DEVICE_QUAL_DESC_SIZE 10 +#define USB_INTERFACE_ASSOC_DESC_SIZE 8 + +/* Descriptor type */ +#define USB_DEVICE_DESC 0x01 +#define USB_CONFIGURATION_DESC 0x02 +#define USB_STRING_DESC 0x03 +#define USB_INTERFACE_DESC 0x04 +#define USB_ENDPOINT_DESC 0x05 +#define USB_DEVICE_QUAL_DESC 0x06 +#define USB_INTERFACE_ASSOC_DESC 0x0B +#define USB_DEVICE_CAPABILITY_DESC 0x10 +#define USB_HID_DESC 0x21 +#define USB_HID_REPORT_DESC 0x22 +#define USB_DFU_FUNCTIONAL_DESC 0x21 +#define USB_ASSOCIATION_DESC 0x0B +#define USB_BINARY_OBJECT_STORE_DESC 0x0F + +/* Useful define */ +#define USB_1_1 0x0110 +#define USB_2_0 0x0200 +/* Set USB version to 2.1 so that the host will request the BOS descriptor */ +#define USB_2_1 0x0210 + +#define BCDDEVICE_RELNUM (BCD(KERNEL_VERSION_MAJOR) << 8 | \ + BCD(KERNEL_VERSION_MINOR)) + +/* 100mA max power, per 2mA units */ +/* USB 1.1 spec indicates 100mA(max) per unit load, up to 5 loads */ +#define MAX_LOW_POWER 0x32 +#define MAX_HIGH_POWER 0xFA + +/* bmAttributes: + * D7:Reserved, always 1, + * D6:Self-Powered -> 1, + * D5:Remote Wakeup -> 0, + * D4...0:Reserved -> 0 + */ +#define USB_CONFIGURATION_ATTRIBUTES 0xC0 + +/* Classes */ +#define COMMUNICATION_DEVICE_CLASS 0x02 +#define COMMUNICATION_DEVICE_CLASS_DATA 0x0A +#define HID_CLASS 0x03 +#define MASS_STORAGE_CLASS 0x08 +#define WIRELESS_DEVICE_CLASS 0xE0 +#define MISC_CLASS 0xEF +#define CUSTOM_CLASS 0xFF +#define DFU_DEVICE_CLASS 0xFE + +/* Sub-classes */ +#define CDC_NCM_SUBCLASS 0x0d +#define BOOT_INTERFACE_SUBCLASS 0x01 +#define SCSI_TRANSPARENT_SUBCLASS 0x06 +#define DFU_INTERFACE_SUBCLASS 0x01 +#define RF_SUBCLASS 0x01 +#define CUSTOM_SUBCLASS 0xFF +#define COMMON_SUBCLASS 0x02 +/* Misc subclasses */ +#define MISC_RNDIS_SUBCLASS 0x04 +#define CDC_ABSTRACT_CONTROL_MODEL 0x02 + +/* Protocols */ +#define V25TER_PROTOCOL 0x01 +#define MOUSE_PROTOCOL 0x02 +#define BULK_ONLY_PROTOCOL 0x50 +#define DFU_RUNTIME_PROTOCOL 0x01 +#define DFU_MODE_PROTOCOL 0x02 +#define BLUETOOTH_PROTOCOL 0x01 +/* CDC ACM protocols */ +#define ACM_VENDOR_PROTOCOL 0xFF +/* Misc protocols */ +#define MISC_ETHERNET_PROTOCOL 0x01 +#define IAD_PROTOCOL 0x01 + +/** Standard Device Descriptor */ +struct usb_device_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} __packed; + +/** Unicode (UTF16LE) String Descriptor */ +struct usb_string_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bString; +} __packed; + +/** Association Descriptor */ +struct usb_association_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bFirstInterface; + uint8_t bInterfaceCount; + uint8_t bFunctionClass; + uint8_t bFunctionSubClass; + uint8_t bFunctionProtocol; + uint8_t iFunction; +} __packed; + +/** Standard Configuration Descriptor */ +struct usb_cfg_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} __packed; + +/** Standard Interface Descriptor */ +struct usb_if_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} __packed; + +/** Standard Endpoint Descriptor */ +struct usb_ep_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; +} __packed; + +struct string_descriptor_zero { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wBcdLang[]; +} __packed; + +struct string_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bString[]; +} __packed; + +#define ROM_MAX_CFG_DESC_CNT 1 + +struct rom_usb_descriptors { + const struct usb_device_descriptor *device_descr; + const void *config_descr[ROM_MAX_CFG_DESC_CNT]; + int string_count; // including string_descriptor_zero + const struct string_descriptor_zero *string0_descr; + const struct string_descriptor *string_descrs[]; +}; + +/* Descriptors defined in the ROM */ +extern struct usb_device_descriptor general_device_descr; +extern const void* acm_config_descr; +extern const void* dfu_config_descr; +extern const struct string_descriptor str_manu_descr; +extern const struct string_descriptor str_prod_descr; +extern const struct string_descriptor_zero string0_descr; +extern const struct rom_usb_descriptors acm_usb_descriptors; +extern const struct rom_usb_descriptors dfu_usb_descriptors; +extern const struct rom_usb_descriptors *rom_usb_curr_desc; + +/* ROM patch: set the ACM descriptor with the correct serial number. + * Only needed on ESP32-S2, on later chips the ROM descriptor is correct. + */ +void rom_usb_cdc_set_descriptor_patch(void); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dc.h new file mode 100644 index 00000000..f20e897c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dc.h @@ -0,0 +1,392 @@ +/* usb_dc.h - USB device controller driver interface */ + +/* + * Copyright (c) 2016 Intel Corporation. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief USB device controller APIs + * + * This file contains the USB device controller APIs. All device controller + * drivers should implement the APIs described in this file. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * USB endpoint direction and number. + */ + +#define USB_EP_DIR_MASK 0x80 +#define USB_EP_DIR_IN 0x80 +#define USB_EP_DIR_OUT 0x00 + +/** + * USB Driver Status Codes + */ +enum usb_dc_status_code { + USB_DC_ERROR, /* USB error reported by the controller */ + USB_DC_RESET, /* USB reset */ + /* USB connection established, hardware enumeration is completed */ + USB_DC_CONNECTED, + USB_DC_CONFIGURED, /* USB configuration done */ + USB_DC_DISCONNECTED, /* USB connection lost */ + USB_DC_SUSPEND, /* USB connection suspended by the HOST */ + USB_DC_RESUME, /* USB connection resumed by the HOST */ + USB_DC_INTERFACE, /* USB interface selected */ + USB_DC_SET_HALT, /* Set Feature ENDPOINT_HALT received */ + USB_DC_CLEAR_HALT, /* Clear Feature ENDPOINT_HALT received */ + USB_DC_UNKNOWN /* Initial USB connection status */ +}; + +/** + * USB Endpoint Callback Status Codes + */ +enum usb_dc_ep_cb_status_code { + USB_DC_EP_SETUP, /* SETUP received */ + /* Out transaction on this EP, data is available for read */ + USB_DC_EP_DATA_OUT, + USB_DC_EP_DATA_IN, /* In transaction done on this EP */ +}; + +/** + * USB Endpoint type + */ +enum usb_dc_ep_type { + USB_DC_EP_CONTROL = 0, /* Control type endpoint */ + USB_DC_EP_ISOCHRONOUS, /* Isochronous type endpoint */ + USB_DC_EP_BULK, /* Bulk type endpoint */ + USB_DC_EP_INTERRUPT /* Interrupt type endpoint */ +}; + +/** + * USB Endpoint Configuration. + */ +struct usb_dc_ep_cfg_data { + /** The number associated with the EP in the device + * configuration structure + * IN EP = 0x80 | \ + * OUT EP = 0x00 | \ + */ + uint8_t ep_addr; + uint16_t ep_mps; /** Endpoint max packet size */ + enum usb_dc_ep_type ep_type; /** Endpoint type */ +}; + +/** + * Callback function signature for the USB Endpoint status + */ +typedef void (*usb_dc_ep_callback)(uint8_t ep, + enum usb_dc_ep_cb_status_code cb_status); + +/** + * Callback function signature for the device + */ +typedef void (*usb_dc_status_callback)(enum usb_dc_status_code cb_status, + uint8_t *param); + +/** + * @brief attach USB for device connection + * + * Function to attach USB for device connection. Upon success, the USB PLL + * is enabled, and the USB device is now capable of transmitting and receiving + * on the USB bus and of generating interrupts. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_attach(void); + +/** + * @brief detach the USB device + * + * Function to detach the USB device. Upon success, the USB hardware PLL + * is powered down and USB communication is disabled. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_detach(void); + +/** + * @brief reset the USB device + * + * This function returns the USB device and firmware back to it's initial state. + * N.B. the USB PLL is handled by the usb_detach function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_reset(void); + +/** + * @brief set USB device address + * + * @param[in] addr device address + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_set_address(const uint8_t addr); + +/** + * @brief set USB device controller status callback + * + * Function to set USB device controller status callback. The registered + * callback is used to report changes in the status of the device controller. + * + * @param[in] cb callback function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_set_status_callback(const usb_dc_status_callback cb); + +/** + * @brief check endpoint capabilities + * + * Function to check capabilities of an endpoint. usb_dc_ep_cfg_data structure + * provides the endpoint configuration parameters: endpoint address, + * endpoint maximum packet size and endpoint type. + * The driver should check endpoint capabilities and return 0 if the + * endpoint configuration is possible. + * + * @param[in] cfg Endpoint config + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data *const cfg); + +/** + * @brief configure endpoint + * + * Function to configure an endpoint. usb_dc_ep_cfg_data structure provides + * the endpoint configuration parameters: endpoint address, endpoint maximum + * packet size and endpoint type. + * + * @param[in] cfg Endpoint config + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_configure(const struct usb_dc_ep_cfg_data *const cfg); + +/** + * @brief set stall condition for the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_set_stall(const uint8_t ep); + +/** + * @brief clear stall condition for the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_clear_stall(const uint8_t ep); + +/** + * @brief check if selected endpoint is stalled + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[out] stalled Endpoint stall status + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_is_stalled(const uint8_t ep, uint8_t *const stalled); + +/** + * @brief halt the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_halt(const uint8_t ep); + +/** + * @brief enable the selected endpoint + * + * Function to enable the selected endpoint. Upon success interrupts are + * enabled for the corresponding endpoint and the endpoint is ready for + * transmitting/receiving data. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_enable(const uint8_t ep); + +/** + * @brief disable the selected endpoint + * + * Function to disable the selected endpoint. Upon success interrupts are + * disabled for the corresponding endpoint and the endpoint is no longer able + * for transmitting/receiving data. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_disable(const uint8_t ep); + +/** + * @brief flush the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_flush(const uint8_t ep); + +/** + * @brief write data to the specified endpoint + * + * This function is called to write data to the specified endpoint. The supplied + * usb_ep_callback function will be called when data is transmitted out. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data to write + * @param[in] data_len length of data requested to write. This may + * be zero for a zero length status packet. + * @param[out] ret_bytes bytes scheduled for transmission. This value + * may be NULL if the application expects all + * bytes to be written + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_write(const uint8_t ep, const uint8_t *const data, + const uint32_t data_len, uint32_t *const ret_bytes); + + + +/** + * @brief Indicate if the write to an IN endpoint (using usb_dc_ep_write) would block + * to wait until the endpoint has enoug space + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 when writable, 0 when not, negative errno code on fail. + */ +int usb_dc_ep_write_would_block(const uint8_t ep); + + +/** + * @brief read data from the specified endpoint + * + * This function is called by the Endpoint handler function, after an OUT + * interrupt has been received for that EP. The application must only call this + * function through the supplied usb_ep_callback function. This function clears + * the ENDPOINT NAK, if all data in the endpoint FIFO has been read, + * so as to accept more data from host. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read(const uint8_t ep, uint8_t *const data, + const uint32_t max_data_len, uint32_t *const read_bytes); + +/** + * @brief set callback function for the specified endpoint + * + * Function to set callback function for notification of data received and + * available to application or transmit done on the selected endpoint, + * NULL if callback not required by application code. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] cb callback function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_set_callback(const uint8_t ep, const usb_dc_ep_callback cb); + +/** + * @brief read data from the specified endpoint + * + * This is similar to usb_dc_ep_read, the difference being that, it doesn't + * clear the endpoint NAKs so that the consumer is not bogged down by further + * upcalls till he is done with the processing of the data. The caller should + * reactivate ep by invoking usb_dc_ep_read_continue() do so. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *read_bytes); + + +/** + * @brief Continue reading data from the endpoint + * + * Clear the endpoint NAK and enable the endpoint to accept more data + * from the host. Usually called after usb_dc_ep_read_wait() when the consumer + * is fine to accept more data. Thus these calls together acts as flow control + * mechanism. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read_continue(uint8_t ep); + +/** + * @brief Get endpoint max packet size + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return enpoint max packet size (mps) + */ +int usb_dc_ep_mps(uint8_t ep); + + + +//Hack - fake interrupts by pollinfg +void usb_dc_check_poll_for_interrupts(void); + + +//Prepare for USB persist. You should reboot after this. +int usb_dc_prepare_persist(void); + + +void usb_dw_isr_handler(void); + + +int usb_dc_ep_write_would_block(const uint8_t ep); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_descriptor.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_descriptor.h new file mode 100644 index 00000000..1b20ef80 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_descriptor.h @@ -0,0 +1,34 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define USB_DESCRIPTOR_TYPE_ACM 0 +#define USB_DESCRIPTOR_TYPE_DFU 1 + +void usb_set_current_descriptor(int descriptor_type); + +bool usb_get_descriptor(uint16_t type_index, uint16_t lang_id, + int32_t *len, uint8_t **data); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_device.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_device.h new file mode 100644 index 00000000..5564d41e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_device.h @@ -0,0 +1,401 @@ +/* + * LPCUSB, an USB device driver for LPC microcontrollers + * Copyright (C) 2006 Bertrik Sikken (bertrik@sikken.nl) + * Copyright (c) 2016 Intel Corporation + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * @brief USB device core layer APIs and structures + * + * This file contains the USB device core layer APIs and structures. + */ + +#pragma once + +#include +#include +#include "usb_dc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/************************************************************************* + * USB configuration + **************************************************************************/ + +#define MAX_PACKET_SIZE0 64 /**< maximum packet size for EP 0 */ +//Note: for FS this should be 8, 16, 32, 64 bytes. HS can go up to 512. + +/************************************************************************* + * USB application interface + **************************************************************************/ + +/** setup packet definitions */ +struct usb_setup_packet { + uint8_t bmRequestType; /**< characteristics of the specific request */ + uint8_t bRequest; /**< specific request */ + uint16_t wValue; /**< request specific parameter */ + uint16_t wIndex; /**< request specific parameter */ + uint16_t wLength; /**< length of data transferred in data phase */ +} __packed; + + +_Static_assert(sizeof(struct usb_setup_packet) == 8, "USB setup packet struct size error"); + +/** + * Callback function signature for the device + */ +typedef void (*usb_status_callback)(enum usb_dc_status_code status_code, + uint8_t *param); + +/** + * Callback function signature for the USB Endpoint status + */ +typedef void (*usb_ep_callback)(uint8_t ep, + enum usb_dc_ep_cb_status_code cb_status); + +/** + * Function which handles Class specific requests corresponding to an + * interface number specified in the device descriptor table + */ +typedef int (*usb_request_handler) (struct usb_setup_packet *detup, + int32_t *transfer_len, uint8_t **payload_data); + +/** + * Function for interface runtime configuration + */ +typedef void (*usb_interface_config)(uint8_t bInterfaceNumber); + +/* + * USB Endpoint Configuration + */ +struct usb_ep_cfg_data { + /** + * Callback function for notification of data received and + * available to application or transmit done, NULL if callback + * not required by application code + */ + usb_ep_callback ep_cb; + /** + * The number associated with the EP in the device configuration + * structure + * IN EP = 0x80 | \ + * OUT EP = 0x00 | \ + */ + uint8_t ep_addr; +}; + +/** + * USB Interface Configuration + */ +struct usb_interface_cfg_data { + /** Handler for USB Class specific Control (EP 0) communications */ + usb_request_handler class_handler; + /** Handler for USB Vendor specific commands */ + usb_request_handler vendor_handler; + /** + * The custom request handler gets a first chance at handling + * the request before it is handed over to the 'chapter 9' request + * handler + */ + usb_request_handler custom_handler; + /** + * This data area, allocated by the application, is used to store + * Class specific command data and must be large enough to store the + * largest payload associated with the largest supported Class' + * command set. This data area may be used for USB IN or OUT + * communications + */ + uint8_t *payload_data; + /** + * This data area, allocated by the application, is used to store + * Vendor specific payload + */ + uint8_t *vendor_data; +}; + +/* + * @brief USB device configuration + * + * The Application instantiates this with given parameters added + * using the "usb_set_config" function. Once this function is called + * changes to this structure will result in undefined behaviour. This structure + * may only be updated after calls to usb_deconfig + */ +struct usb_cfg_data { + /** + * USB device description, see + * http://www.beyondlogic.org/usbnutshell/usb5.shtml#DeviceDescriptors + */ + const uint8_t *usb_device_description; + /** Pointer to interface descriptor */ + const void *interface_descriptor; + /** Function for interface runtime configuration */ + usb_interface_config interface_config; + /** Callback to be notified on USB connection status change */ + usb_status_callback cb_usb_status; + /** USB interface (Class) handler and storage space */ + struct usb_interface_cfg_data interface; + /** Number of individual endpoints in the device configuration */ + uint8_t num_endpoints; + /** + * Pointer to an array of endpoint structs of length equal to the + * number of EP associated with the device description, + * not including control endpoints + */ + struct usb_ep_cfg_data *endpoint; +}; + +/* + * @brief configure USB controller + * + * Function to configure USB controller. + * Configuration parameters must be valid or an error is returned + * + * @param[in] config Pointer to configuration structure + * + * @return 0 on success, negative errno code on fail + */ +int usb_set_config(struct usb_cfg_data *config); + +/* + * @brief return the USB device to it's initial state + * + * @return 0 on success, negative errno code on fail + */ +int usb_deconfig(void); + +/* + * @brief enable USB for host/device connection + * + * Function to enable USB for host/device connection. + * Upon success, the USB module is no longer clock gated in hardware, + * it is now capable of transmitting and receiving on the USB bus and + * of generating interrupts. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_enable(struct usb_cfg_data *config); + +/* + * @brief disable the USB device. + * + * Function to disable the USB device. + * Upon success, the specified USB interface is clock gated in hardware, + * it is no longer capable of generating interrupts. + * + * @return 0 on success, negative errno code on fail + */ +int usb_disable(void); + +/* + * @brief Check if a write to an in ep would block until there is enough space + * in the fifo + * + * @param[in] ep Endpoint address corresponding to the one listed in the + * device configuration table + * + * @return 0 if free to write, 1 if a write would block, negative errno code on fail + */ +int usb_write_would_block(uint8_t ep); + +/* + * @brief write data to the specified endpoint + * + * Function to write data to the specified endpoint. The supplied + * usb_ep_callback will be called when transmission is done. + * + * @param[in] ep Endpoint address corresponding to the one listed in the + * device configuration table + * @param[in] data Pointer to data to write + * @param[in] data_len Length of data requested to write. This may be zero for + * a zero length status packet. + * @param[out] bytes_ret Bytes written to the EP FIFO. This value may be NULL if + * the application expects all bytes to be written + * + * @return 0 on success, negative errno code on fail + */ +int usb_write(uint8_t ep, const uint8_t *data, uint32_t data_len, + uint32_t *bytes_ret); + +/* + * @brief read data from the specified endpoint + * + * This function is called by the Endpoint handler function, after an + * OUT interrupt has been received for that EP. The application must + * only call this function through the supplied usb_ep_callback function. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * @param[in] data Pointer to data buffer to write to + * @param[in] max_data_len Max length of data to read + * @param[out] ret_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes available + * for read is returned. + * + * @return 0 on success, negative errno code on fail + */ +int usb_read(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *ret_bytes); + +/* + * @brief set STALL condition on the specified endpoint + * + * This function is called by USB device class handler code to set stall + * conditionin on endpoint. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * + * @return 0 on success, negative errno code on fail + */ +int usb_ep_set_stall(uint8_t ep); + + +/* + * @brief clears STALL condition on the specified endpoint + * + * This function is called by USB device class handler code to clear stall + * conditionin on endpoint. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * + * @return 0 on success, negative errno code on fail + */ +int usb_ep_clear_stall(uint8_t ep); + +/** + * @brief read data from the specified endpoint + * + * This is similar to usb_ep_read, the difference being that, it doesn't + * clear the endpoint NAKs so that the consumer is not bogged down by further + * upcalls till he is done with the processing of the data. The caller should + * reactivate ep by invoking usb_ep_read_continue() do so. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *read_bytes); + + +/** + * @brief Continue reading data from the endpoint + * + * Clear the endpoint NAK and enable the endpoint to accept more data + * from the host. Usually called after usb_ep_read_wait() when the consumer + * is fine to accept more data. Thus these calls together acts as flow control + * mechanism. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_ep_read_continue(uint8_t ep); + +/** + * Callback function signature for transfer completion. + */ +typedef void (*usb_transfer_callback)(uint8_t ep, int tsize, void *priv); + +/* USB transfer flags */ +#define USB_TRANS_READ BIT(0) /** Read transfer flag */ +#define USB_TRANS_WRITE BIT(1) /** Write transfer flag */ +#define USB_TRANS_NO_ZLP BIT(2) /** No zero-length packet flag */ + +/** + * @brief Transfer management endpoint callback + * + * If a USB class driver wants to use high-level transfer functions, driver + * needs to register this callback as usb endpoint callback. + */ +void usb_transfer_ep_callback(uint8_t ep, enum usb_dc_ep_cb_status_code); + +/** + * @brief Start a transfer + * + * Start a usb transfer to/from the data buffer. This function is asynchronous + * and can be executed in IRQ context. The provided callback will be called + * on transfer completion (or error) in thread context. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data Pointer to data buffer to write-to/read-from + * @param[in] dlen Size of data buffer + * @param[in] flags Transfer flags (USB_TRANS_READ, USB_TRANS_WRITE...) + * @param[in] cb Function called on transfer completion/failure + * @param[in] priv Data passed back to the transfer completion callback + * + * @return 0 on success, negative errno code on fail. + */ +int usb_transfer(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags, + usb_transfer_callback cb, void *priv); + +/** + * @brief Start a transfer and block-wait for completion + * + * Synchronous version of usb_transfer, wait for transfer completion before + * returning. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data Pointer to data buffer to write-to/read-from + * @param[in] dlen Size of data buffer + * @param[in] flags Transfer flags + + * + * @return number of bytes transferred on success, negative errno code on fail. + */ +int usb_transfer_sync(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags); + +/** + * @brief Cancel any ongoing transfer on the specified endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +void usb_cancel_transfer(uint8_t ep); + + +void usb_dev_resume(int configuration); +int usb_dev_get_configuration(void); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dfu.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dfu.h new file mode 100644 index 00000000..dec7ea93 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_dfu.h @@ -0,0 +1,147 @@ +/*************************************************************************** + * + * Copyright(c) 2015,2016 Intel Corporation. + * Copyright(c) 2017 PHYTEC Messtechnik GmbH + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ***************************************************************************/ + +/** + * @file + * @brief USB Device Firmware Upgrade (DFU) public header + * + * Header follows the Device Class Specification for + * Device Firmware Upgrade Version 1.1 + */ + +#pragma once + +#include +#include +#include "usb_device.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** DFU Class Subclass */ +#define DFU_SUBCLASS 0x01 + +/** DFU Class runtime Protocol */ +#define DFU_RT_PROTOCOL 0x01 + +/** DFU Class DFU mode Protocol */ +#define DFU_MODE_PROTOCOL 0x02 + +/** + * @brief DFU Class Specific Requests + */ +#define DFU_DETACH 0x00 +#define DFU_DNLOAD 0x01 +#define DFU_UPLOAD 0x02 +#define DFU_GETSTATUS 0x03 +#define DFU_CLRSTATUS 0x04 +#define DFU_GETSTATE 0x05 +#define DFU_ABORT 0x06 + +/** DFU FUNCTIONAL descriptor type */ +#define DFU_FUNC_DESC 0x21 + +/** DFU attributes DFU Functional Descriptor */ +#define DFU_ATTR_WILL_DETACH 0x08 +#define DFU_ATTR_MANIFESTATION_TOLERANT 0x04 +#define DFU_ATTR_CAN_UPLOAD 0x02 +#define DFU_ATTR_CAN_DNLOAD 0x01 + +/** DFU Specification release */ +#define DFU_VERSION 0x0110 + +/** Run-Time Functional Descriptor */ +struct dfu_runtime_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bmAttributes; + uint16_t wDetachTimeOut; + uint16_t wTransferSize; + uint16_t bcdDFUVersion; +} __packed; + +/** bStatus values for the DFU_GETSTATUS response */ +enum dfu_status { + statusOK, + errTARGET, + errFILE, + errWRITE, + errERASE, + errCHECK_ERASED, + errPROG, + errVERIFY, + errADDRESS, + errNOTDONE, + errFIRMWARE, + errVENDOR, + errUSB, + errPOR, + errUNKNOWN, + errSTALLEDPKT +}; + +/** bState values for the DFU_GETSTATUS response */ +enum dfu_state { + appIDLE, + appDETACH, + dfuIDLE, + dfuDNLOAD_SYNC, + dfuDNBUSY, + dfuDNLOAD_IDLE, + dfuMANIFEST_SYNC, + dfuMANIFEST, + dfuMANIFEST_WAIT_RST, + dfuUPLOAD_IDLE, + dfuERROR, +}; + +/* + These callbacks are made public so the ACM driver can call them to handle the switch to DFU. +*/ + +int dfu_class_handle_req(struct usb_setup_packet *pSetup, + int32_t *data_len, uint8_t **data); +void dfu_status_cb(enum usb_dc_status_code status, uint8_t *param); +int usb_dfu_init(void); +int dfu_custom_handle_req(struct usb_setup_packet *pSetup, + int32_t *data_len, uint8_t **data); + + +typedef void(*usb_dfu_detach_routine_t)(int delay); +void usb_dfu_set_detach_cb(usb_dfu_detach_routine_t cb); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_os_glue.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_os_glue.h new file mode 100644 index 00000000..74d9b2a7 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_os_glue.h @@ -0,0 +1,40 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef void(*usb_osglue_intdisena_routine_t)(void); +typedef int(*usb_osglue_wait_routine_t)(int delay_us); + +typedef struct { + /* Disable USB interrupt */ + usb_osglue_intdisena_routine_t int_dis_proc; + /* Enable USB interrupt */ + usb_osglue_intdisena_routine_t int_ena_proc; + /* Wait for a set amount of uS. Return the amount actually waited. If delay_us is 0, just yield.*/ + usb_osglue_wait_routine_t wait_proc; +} usb_osglue_data_t; + +extern usb_osglue_data_t rom_usb_osglue; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_persist.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_persist.h new file mode 100644 index 00000000..bcf11b7c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s2/rom/usb/usb_persist.h @@ -0,0 +1,50 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// USB persistence flags. + +//This bit indicates persistence has been enabled, that is, the USB initialization routines should not +//reset the USB device as the device still is initialized and the host detected it with the same cdcacm/dfu +//descriptor as the ROM uses; we can just re-initialize the software side and have at 'er. +#define USBDC_PERSIST_ENA (1<<31) + +//This bit indicates to the ROM that we rebooted because of a request to go into DFU mode; the ROM should +//honour this request. +#define USBDC_BOOT_DFU (1<<30) + + +//This being non-0 indicates a memory location where a 'testament' is stored, aka a piece of text that should be output +//after a reboot. Can contain core dump info or something. +#define USBDC_TESTAMENT_LOC_MASK 0x7FFFF //bits 19-0; this is added to a base address of 0x3FF80000. + +//The testament is a FIFO. The ROM will output all data between textstart and textend; if textend is lower than textstart it will +//output everything from textstart to memend, then memstart to textend. +typedef struct { + char *memstart; //start of memory region + char *memend; //end of memory region + char *textstart; //start of text to output + char *textend; +} usbdc_testament_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/aes.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/aes.h new file mode 100644 index 00000000..1df00a1d --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/aes.h @@ -0,0 +1,53 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +enum AES_TYPE { + AES_ENC, + AES_DEC, +}; + +enum AES_BITS { + AES128, + AES192, + AES256 +}; + +void ets_aes_enable(void); + +void ets_aes_disable(void); + +void ets_aes_set_endian(bool key_word_swap, bool key_byte_swap, + bool in_word_swap, bool in_byte_swap, + bool out_word_swap, bool out_byte_swap); + +int ets_aes_setkey(enum AES_TYPE type, const void *key, enum AES_BITS bits); + +int ets_aes_setkey_enc(const void *key, enum AES_BITS bits); + +int ets_aes_setkey_dec(const void *key, enum AES_BITS bits); + +void ets_aes_block(const void *input, void *output); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/bigint.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/bigint.h new file mode 100644 index 00000000..2ab022d8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/bigint.h @@ -0,0 +1,40 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void ets_bigint_enable(void); + +void ets_bigint_disable(void); + +int ets_bigint_multiply(const uint32_t *x, const uint32_t *y, uint32_t len_words); + +int ets_bigint_modmult(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, uint32_t len_words); + +int ets_bigint_modexp(const uint32_t *x, const uint32_t *y, const uint32_t *m, uint32_t m_dash, const uint32_t *rb, bool constant_time, uint32_t len_words); + +void ets_bigint_wait_finish(void); + +int ets_bigint_getz(uint32_t *z, uint32_t len_words); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/cache.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/cache.h new file mode 100644 index 00000000..0ec6308f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/cache.h @@ -0,0 +1,1097 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef BIT +#define BIT(nr) (1 << (nr)) +#endif + +/** \defgroup cache_apis, cache operation related apis + * @brief cache apis + */ + +/** @addtogroup cache_apis + * @{ + */ +#define MIN_ICACHE_SIZE 16384 +#define MAX_ICACHE_SIZE 32768 +#define MIN_DCACHE_SIZE 32768 +#define MAX_DCACHE_SIZE 65536 +#define MIN_ICACHE_WAYS 4 +#define MAX_ICACHE_WAYS 8 +#define MIN_DCACHE_WAYS 4 +#define MAX_DCACHE_WAYS 4 +#define MAX_CACHE_WAYS 8 +#define MIN_CACHE_LINE_SIZE 16 +#define TAG_SIZE 4 +#define MIN_ICACHE_BANK_NUM 1 +#define MAX_ICACHE_BANK_NUM 2 +#define MIN_DCACHE_BANK_NUM 1 +#define MAX_DCACHE_BANK_NUM 2 +#define CACHE_MEMORY_BANK_NUM 4 +#define CACHE_MEMORY_IBANK_SIZE 0x4000 +#define CACHE_MEMORY_DBANK_SIZE 0x8000 + +#define MAX_ITAG_BANK_ITEMS (MAX_ICACHE_SIZE / MAX_ICACHE_BANK_NUM / MIN_CACHE_LINE_SIZE) +#define MAX_ITAG_BLOCK_ITEMS (MAX_ICACHE_SIZE / MAX_ICACHE_BANK_NUM / MAX_ICACHE_WAYS / MIN_CACHE_LINE_SIZE) +#define MAX_ITAG_BANK_SIZE (MAX_ITAG_BANK_ITEMS * TAG_SIZE) +#define MAX_ITAG_BLOCK_SIZE (MAX_ITAG_BLOCK_ITEMS * TAG_SIZE) +#define MAX_DTAG_BANK_ITEMS (MAX_DCACHE_SIZE / MAX_DCACHE_BANK_NUM / MIN_CACHE_LINE_SIZE) +#define MAX_DTAG_BLOCK_ITEMS (MAX_DCACHE_SIZE / MAX_DCACHE_BANK_NUM / MAX_DCACHE_WAYS / MIN_CACHE_LINE_SIZE) +#define MAX_DTAG_BANK_SIZE (MAX_DTAG_BANK_ITEMS * TAG_SIZE) +#define MAX_DTAG_BLOCK_SIZE (MAX_DTAG_BLOCK_ITEMS * TAG_SIZE) + +typedef enum { + CACHE_DCACHE = 0, + CACHE_ICACHE0 = 1, + CACHE_ICACHE1 = 2, +} cache_t; + +typedef enum { + CACHE_MEMORY_INVALID = 0, + CACHE_MEMORY_IBANK0 = BIT(0), + CACHE_MEMORY_IBANK1 = BIT(1), + CACHE_MEMORY_IBANK2 = BIT(2), + CACHE_MEMORY_IBANK3 = BIT(3), + CACHE_MEMORY_DBANK0 = BIT(0), + CACHE_MEMORY_DBANK1 = BIT(1), + CACHE_MEMORY_DBANK2 = BIT(2), + CACHE_MEMORY_DBANK3 = BIT(3), +} cache_array_t; + +#define ICACHE_SIZE_16KB CACHE_SIZE_HALF +#define ICACHE_SIZE_32KB CACHE_SIZE_FULL +#define DCACHE_SIZE_32KB CACHE_SIZE_HALF +#define DCACHE_SIZE_64KB CACHE_SIZE_FULL + +typedef enum { + CACHE_SIZE_HALF = 0, /*!< 8KB for icache and dcache */ + CACHE_SIZE_FULL = 1, /*!< 16KB for icache and dcache */ +} cache_size_t; + +typedef enum { + CACHE_4WAYS_ASSOC = 0, /*!< 4 way associated cache */ + CACHE_8WAYS_ASSOC = 1, /*!< 8 way associated cache */ +} cache_ways_t; + +typedef enum { + CACHE_LINE_SIZE_16B = 0, /*!< 16 Byte cache line size */ + CACHE_LINE_SIZE_32B = 1, /*!< 32 Byte cache line size */ + CACHE_LINE_SIZE_64B = 2, /*!< 64 Byte cache line size */ +} cache_line_size_t; + +typedef enum { + CACHE_AUTOLOAD_POSITIVE = 0, /*!< cache autoload step is positive */ + CACHE_AUTOLOAD_NEGATIVE = 1, /*!< cache autoload step is negative */ +} cache_autoload_order_t; + +#define CACHE_AUTOLOAD_STEP(i) ((i) - 1) + +typedef enum { + CACHE_AUTOLOAD_MISS_TRIGGER = 0, /*!< autoload only triggered by cache miss */ + CACHE_AUTOLOAD_HIT_TRIGGER = 1, /*!< autoload only triggered by cache hit */ + CACHE_AUTOLOAD_BOTH_TRIGGER = 2, /*!< autoload triggered both by cache miss and hit */ +} cache_autoload_trigger_t; + +typedef enum { + CACHE_FREEZE_ACK_BUSY = 0, /*!< in this mode, cache ack busy to CPU if a cache miss happens*/ + CACHE_FREEZE_ACK_ERROR = 1, /*!< in this mode, cache ack wrong data to CPU and trigger an error if a cache miss happens */ +} cache_freeze_mode_t; + +struct cache_mode { + uint32_t cache_size; /*!< cache size in byte */ + uint16_t cache_line_size; /*!< cache line size in byte */ + uint8_t cache_ways; /*!< cache ways, always 4 */ + uint8_t icache; /*!< the cache index, 0 for dcache, 1 for icache */ +}; + +struct icache_tag_item { + uint32_t valid: 1; /*!< the tag item is valid or not */ + uint32_t lock: 1; /*!< the cache line is locked or not */ + uint32_t attr: 4; /*!< the attribute of the external memory physical address */ + uint32_t fifo_cnt: 3; /*!< fifo cnt, 0 ~ 3 for 4 ways cache */ + uint32_t tag: 14; /*!< the tag is the high part of the cache address, however is only 64MB range, and without low part */ + uint32_t reserved: 9; +}; + +struct dcache_tag_item { + uint32_t dirty: 1; /*!< the cache line value is dirty or not */ + uint32_t valid: 1; /*!< the tag item is valid or not */ + uint32_t lock: 1; /*!< the cache line is locked or not */ + uint32_t occupy: 1; /*!< the cache line is occupied as internal sram */ + uint32_t attr: 4; /*!< the attribute of the external memory physical address */ + uint32_t fifo_cnt: 2; /*!< fifo cnt, 0 ~ 3 for 4 ways cache */ + uint32_t tag: 13; /*!< the tag is the high part of the cache address, however is only 64MB range, and without low part */ + uint32_t reserved: 9; +}; + +struct autoload_config { + uint8_t order; /*!< autoload step is positive or negative */ + uint8_t trigger; /*!< autoload trigger */ + uint8_t ena0; /*!< autoload region0 enable */ + uint8_t ena1; /*!< autoload region1 enable */ + uint32_t addr0; /*!< autoload region0 start address */ + uint32_t size0; /*!< autoload region0 size */ + uint32_t addr1; /*!< autoload region1 start address */ + uint32_t size1; /*!< autoload region1 size */ +}; + +struct tag_group_info { + struct cache_mode mode; /*!< cache and cache mode */ + uint32_t filter_addr; /*!< the address that used to generate the struct */ + uint32_t vaddr_offset; /*!< virtual address offset of the cache ways */ + uint32_t tag_addr[MAX_CACHE_WAYS]; /*!< tag memory address, only [0~mode.ways-1] is valid to use */ + uint32_t cache_memory_offset[MAX_CACHE_WAYS]; /*!< cache memory address, only [0~mode.ways-1] is valid to use */ +}; + +struct lock_config { + uint32_t addr; /*!< manual lock address*/ + uint16_t size; /*!< manual lock size*/ + uint16_t group; /*!< manual lock group, 0 or 1*/ +}; + +#define ESP_ROM_ERR_INVALID_ARG 1 +#define MMU_SET_ADDR_ALIGNED_ERROR 2 +#define MMU_SET_PASE_SIZE_ERROR 3 +#define MMU_SET_VADDR_OUT_RANGE 4 + +#define CACHE_OP_ICACHE_Y 1 +#define CACHE_OP_ICACHE_N 0 + +/** + * @brief Initialise cache mmu, mark all entries as invalid. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_MMU_Init(void); + +/** + * @brief Set ICache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be Iram0,Iram1,Irom0,Drom0 and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of ICache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + * + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Ibus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Set DCache mmu mapping. + * Please do not call this function in your SDK application. + * + * @param uint32_t ext_ram : DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. + * + * @param uint32_t vaddr : virtual address in CPU address space. + * Can be DRam0, DRam1, DRom0, DPort and AHB buses address. + * Should be aligned by psize. + * + * @param uint32_t paddr : physical address in external memory. + * Should be aligned by psize. + * + * @param uint32_t psize : page size of DCache, in kilobytes. Should be 64 here. + * + * @param uint32_t num : pages to be set. + + * @param uint32_t fixed : 0 for physical pages grow with virtual pages, other for virtual pages map to same physical page. + * + * @return uint32_t: error status + * 0 : mmu set success + * 2 : vaddr or paddr is not aligned + * 3 : psize error + * 4 : vaddr is out of range + */ +int Cache_Dbus_MMU_Set(uint32_t ext_ram, uint32_t vaddr, uint32_t paddr, uint32_t psize, uint32_t num, uint32_t fixed); + +/** + * @brief Count the pages in the bus room address which map to Flash. + * Please do not call this function in your SDK application. + * + * @param uint32_t bus : the bus to count with. + * + * @param uint32_t * page0_mapped : value should be initial by user, 0 for not mapped, other for mapped count. + * + * return uint32_t : the number of pages which map to Flash. + */ +uint32_t Cache_Count_Flash_Pages(uint32_t bus, uint32_t *page0_mapped); + +/** + * @brief Copy Instruction or rodata from Flash to SPIRAM, and remap to SPIRAM. + * Please do not call this function in your SDK application. + * + * @param uint32_t bus : the bus which need to copy to SPIRAM. + * + * @param uint32_t bus_start_addr : the start virtual address for the bus. + * + * @param uint32_t start_page : the start (64KB) page number in SPIRAM. + * + * @param uint32_t * page0_page : the flash page0 in SPIRAM page number, 0xffff for invalid. + * + * return uint32_t : the next start page number for SPIRAM not mapped. + */ +uint32_t Cache_Flash_To_SPIRAM_Copy(uint32_t bus, uint32_t bus_start_addr, uint32_t start_page, uint32_t *page0_page); + +/** + * @brief allocate memory to used by ICache. + * Please do not call this function in your SDK application. + * + * @param cache_array_t icache_low : the data array bank used by icache low part, can be CACHE_MEMORY_INVALID, CACHE_MEMORY_IBANK0, CACHE_MEMORY_IBANK1 + * + * @param cache_array_t icache_high : the data array bank used by icache high part, can be CACHE_MEMORY_INVALID, CACHE_MEMORY_IBANK0, CACHE_MEMORY_IBANK1 only if icache_low and icache_high is not CACHE_MEMORY_INVALID + * + * return none + */ +void Cache_Occupy_ICache_MEMORY(cache_array_t icache_low, cache_array_t icache_high); + +/** + * @brief allocate memory to used by DCache. + * Please do not call this function in your SDK application. + * + * @param cache_array_t dcache_low : the data array bank used by dcache low part, can be CACHE_MEMORY_INVALID, CACHE_MEMORY_DBANK0, CACHE_MEMORY_DBANK1 + * + * @param cache_array_t dcache1_high : the data array bank used by dcache high part, can be CACHE_MEMORY_INVALID, CACHE_MEMORY_DBANK0, CACHE_MEMORY_DBANK1 only if dcache_low0 and dcache_low1 is not CACHE_MEMORY_INVALID + * + * return none + */ +void Cache_Occupy_DCache_MEMORY(cache_array_t dcache_low, cache_array_t dcache_high); + +/** + * @brief Get cache mode of ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the pointer of cache mode struct, caller should set the icache field + * + * return none + */ +void Cache_Get_Mode(struct cache_mode *mode); + +/** + * @brief set ICache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_HALF and CACHE_SIZE_FULL + * + * @param cache_ways_t ways : the associate ways of cache, can be CACHE_4WAYS_ASSOC and CACHE_8WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B and CACHE_LINE_SIZE_64B + * + * return none + */ +void Cache_Set_ICache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief set DCache modes: cache size, associate ways and cache line size. + * Please do not call this function in your SDK application. + * + * @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_8KB and CACHE_SIZE_16KB + * + * @param cache_ways_t ways : the associate ways of cache, can be CACHE_4WAYS_ASSOC and CACHE_8WAYS_ASSOC + * + * @param cache_line_size_t cache_line_size : the cache line size, can be CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B and CACHE_LINE_SIZE_64B + * + * return none + */ +void Cache_Set_DCache_Mode(cache_size_t cache_size, cache_ways_t ways, cache_line_size_t cache_line_size); + +/** + * @brief check if the address is accessed through ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through ICache, 0 if not. + */ +uint32_t Cache_Address_Through_ICache(uint32_t addr); + +/** + * @brief check if the address is accessed through DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : the address to check. + * + * @return 1 if the address is accessed through DCache, 0 if not. + */ +uint32_t Cache_Address_Through_DCache(uint32_t addr); + +/** + * @brief Init mmu owner register to make i/d cache use half mmu entries. + * + * @param None + * + * @return None + */ +void Cache_Owner_Init(void); + +/** + * @brief Invalidate the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to invalidate + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Invalidate_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Invalidate the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to invalidate + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Invalidate_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Clean the dirty bit of cache Items of DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to Clean + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Clean_Items(uint32_t addr, uint32_t items); + +/** + * @brief Write back the cache items of DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to write back + * + * @param uint32_t items: cache lines to invalidate, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_WriteBack_Items(uint32_t addr, uint32_t items); + +/** + * @brief Invalidate the Cache items in the region from ICache or DCache. + * If the region is not in Cache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : invalidated region start address. + * + * @param uint32_t size : invalidated region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Invalidate_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Clean the dirty bit of Cache items in the region from DCache. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : cleaned region start address. + * + * @param uint32_t size : cleaned region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Clean_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Writeback the Cache items(also clean the dirty bit) in the region from DCache. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : writeback region start address. + * + * @param uint32_t size : writeback region size. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_WriteBack_Addr(uint32_t addr, uint32_t size); + + +/** + * @brief Invalidate all cache items in ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Invalidate_ICache_All(void); + +/** + * @brief Invalidate all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Invalidate_DCache_All(void); + +/** + * @brief Clean the dirty bit of all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Clean_All(void); + +/** + * @brief WriteBack all cache items in DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_WriteBack_All(void); + +/** + * @brief Mask all buses through ICache and DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Mask_All(void); + +/** + * @brief UnMask DRam0 bus through DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_UnMask_Dram0(void); + +/** + * @brief Suspend ICache auto preload operation, then you can resume it after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache not auto preload before suspend. + */ +uint32_t Cache_Suspend_ICache_Autoload(void); + +/** + * @brief Resume ICache auto preload operation after some ICache operations. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before suspend. + * + * @return None. + */ +void Cache_Resume_ICache_Autoload(uint32_t autoload); + +/** + * @brief Suspend DCache auto preload operation, then you can resume it after some DCache operations. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for DCache not auto preload before suspend. + */ +uint32_t Cache_Suspend_DCache_Autoload(void); + +/** + * @brief Resume DCache auto preload operation after some DCache operations. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for DCache not auto preload before suspend. + * + * @return None. + */ +void Cache_Resume_DCache_Autoload(uint32_t autoload); + +/** + * @brief Start an ICache manual preload, will suspend auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of the preload region. + * + * @param uint32_t size : size of the preload region, should not exceed the size of ICache. + * + * @param uint32_t order : the preload order, 0 for positive, other for negative + * + * @return uint32_t : 0 for ICache not auto preload before manual preload. + */ +uint32_t Cache_Start_ICache_Preload(uint32_t addr, uint32_t size, uint32_t order); + +/** + * @brief Return if the ICache manual preload done. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for ICache manual preload not done. + */ +uint32_t Cache_ICache_Preload_Done(void); + +/** + * @brief End the ICache manual preload to resume auto preload of ICache. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for ICache not auto preload before manual preload. + * + * @return None + */ +void Cache_End_ICache_Preload(uint32_t autoload); + +/** + * @brief Start an DCache manual preload, will suspend auto preload of DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of the preload region. + * + * @param uint32_t size : size of the preload region, should not exceed the size of DCache. + * + * @param uint32_t order : the preload order, 0 for positive, other for negative + * + * @return uint32_t : 0 for DCache not auto preload before manual preload. + */ +uint32_t Cache_Start_DCache_Preload(uint32_t addr, uint32_t size, uint32_t order); + +/** + * @brief Return if the DCache manual preload done. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : 0 for DCache manual preload not done. + */ +uint32_t Cache_DCache_Preload_Done(void); + +/** + * @brief End the DCache manual preload to resume auto preload of DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : 0 for DCache not auto preload before manual preload. + * + * @return None + */ +void Cache_End_DCache_Preload(uint32_t autoload); + +/** + * @brief Config autoload parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct autoload_config * config : autoload parameters. + * + * @return None + */ +void Cache_Config_ICache_Autoload(const struct autoload_config *config); + +/** + * @brief Enable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Enable_ICache_Autoload(void); + +/** + * @brief Disable auto preload for ICache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Disable_ICache_Autoload(void); + +/** + * @brief Config autoload parameters of DCache. + * Please do not call this function in your SDK application. + * + * @param struct autoload_config * config : autoload parameters. + * + * @return None + */ +void Cache_Config_DCache_Autoload(const struct autoload_config *config); + +/** + * @brief Enable auto preload for DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Enable_DCache_Autoload(void); + +/** + * @brief Disable auto preload for DCache. + * Please do not call this function in your SDK application. + * + * @param None + * + * @return None + */ +void Cache_Disable_DCache_Autoload(void); + +/** + * @brief Config a group of prelock parameters of ICache. + * Please do not call this function in your SDK application. + * + * @param struct lock_config * config : a group of lock parameters. + * + * @return None + */ + +void Cache_Enable_ICache_PreLock(const struct lock_config *config); + +/** + * @brief Disable a group of prelock parameters for ICache. + * However, the locked data will not be released. + * Please do not call this function in your SDK application. + * + * @param uint16_t group : 0 for group0, 1 for group1. + * + * @return None + */ +void Cache_Disable_ICache_PreLock(uint16_t group); + +/** + * @brief Lock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to lock + * + * @param uint32_t items: cache lines to lock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Lock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Unlock the cache items for ICache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in ICache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to unlock + * + * @param uint32_t items: cache lines to unlock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Unlock_ICache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Config a group of prelock parameters of DCache. + * Please do not call this function in your SDK application. + * + * @param struct lock_config * config : a group of lock parameters. + * + * @return None + */ +void Cache_Enable_DCache_PreLock(const struct lock_config *config); + +/** + * @brief Disable a group of prelock parameters for DCache. + * However, the locked data will not be released. + * Please do not call this function in your SDK application. + * + * @param uint16_t group : 0 for group0, 1 for group1. + * + * @return None + */ +void Cache_Disable_DCache_PreLock(uint16_t group); + +/** + * @brief Lock the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to lock + * + * @param uint32_t items: cache lines to lock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Lock_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Unlock the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr: start address to unlock + * + * @param uint32_t items: cache lines to unlock, items * cache_line_size should not exceed the bus address size(16MB/32MB/64MB) + * + * @return None + */ +void Cache_Unlock_DCache_Items(uint32_t addr, uint32_t items); + +/** + * @brief Lock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of lock region. + * + * @param uint32_t size : size of lock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Lock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Unlock the cache items in tag memory for ICache or DCache. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of unlock region. + * + * @param uint32_t size : size of unlock region. + * + * @return 0 for success + * 1 for invalid argument + */ +int Cache_Unlock_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Disable ICache access for the cpu. + * This operation will make all ICache tag memory invalid, CPU can't access ICache, ICache will keep idle. + * Please do not call this function in your SDK application. + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Disable_ICache(void); + +/** + * @brief Enable ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Enable_ICache(uint32_t autoload); + +/** + * @brief Disable DCache access for the cpu. + * This operation will make all DCache tag memory invalid, CPU can't access DCache, DCache will keep idle + * Please do not call this function in your SDK application. + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Disable_DCache(void); + +/** + * @brief Enable DCache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : DCache will preload then. + * + * @return None + */ +void Cache_Enable_DCache(uint32_t autoload); + +/** + * @brief Suspend ICache access for the cpu. + * The ICache tag memory is still there, CPU can't access ICache, ICache will keep idle. + * Please do not change MMU, cache mode or tag memory(tag memory can be changed in some special case). + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Suspend_ICache(void); + +/** + * @brief Resume ICache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : ICache will preload then. + * + * @return None + */ +void Cache_Resume_ICache(uint32_t autoload); + +/** + * @brief Suspend DCache access for the cpu. + * The ICache tag memory is still there, CPU can't access DCache, DCache will keep idle. + × Please do not change MMU, cache mode or tag memory(tag memory can be changed in some special case). + * Please do not call this function in your SDK application. + * + * @param None + * + * @return uint32_t : auto preload enabled before + */ +uint32_t Cache_Suspend_DCache(void); + +/** + * @brief Resume DCache access for the cpu. + * Please do not call this function in your SDK application. + * + * @param uint32_t autoload : DCache will preload then. + * + * @return None + */ +void Cache_Resume_DCache(uint32_t autoload); + +/** + * @brief Get ICache cache line size + * + * @param None + * + * @return uint32_t: 16, 32, 64 Byte + */ +uint32_t Cache_Get_ICache_Line_Size(void); + +/** + * @brief Get DCache cache line size + * + * @param None + * + * @return uint32_t: 16, 32, 64 Byte + */ +uint32_t Cache_Get_DCache_Line_Size(void); + +/** + * @brief Set default mode from boot, 8KB ICache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Set_Default_Mode(void); + +/** + * @brief Set default mode from boot, 8KB ICache, 16Byte cache line size. + * + * @param None + * + * @return None + */ +void Cache_Enable_Defalut_ICache_Mode(void); + +/** + * @brief Occupy the cache items for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of occupy region + * + * @param uint32_t items : cache lines to occupy, items * cache_line_size should not exceed the cache_size + * + * @return None + */ +void Cache_Occupy_Items(uint32_t addr, uint32_t items); + +/** + * @brief Occupy the cache addr for DCache. + * Operation will be done CACHE_LINE_SIZE aligned. + * If the region is not in DCache addr room, nothing will be done. + * Please do not call this function in your SDK application. + * + * @param uint32_t addr : start address of occupy region + * + * @param uint32_t size : size of occupy region, size should not exceed the cache_size + */ +int Cache_Occupy_Addr(uint32_t addr, uint32_t size); + +/** + * @brief Enable freeze for ICache. + * Any miss request will be rejected, including cpu miss and preload/autoload miss. + * Please do not call this function in your SDK application. + * + * @param cache_freeze_mode_t mode : 0 for assert busy 1 for assert hit + * + * @return None + */ +void Cache_Freeze_ICache_Enable(cache_freeze_mode_t mode); + +/** + * @brief Disable freeze for ICache. + * Please do not call this function in your SDK application. + * + * @return None + */ +void Cache_Freeze_ICache_Disable(void); + +/** + * @brief Enable freeze for DCache. + * Any miss request will be rejected, including cpu miss and preload/autoload miss. + * Please do not call this function in your SDK application. + * + * @param cache_freeze_mode_t mode : 0 for assert busy 1 for assert hit + * + * @return None + */ +void Cache_Freeze_DCache_Enable(cache_freeze_mode_t mode); + +/** + * @brief Disable freeze for DCache. + * Please do not call this function in your SDK application. + * + * @return None + */ +void Cache_Freeze_DCache_Disable(void); + +/** + * @brief Travel tag memory to run a call back function. + * ICache and DCache are suspend when doing this. + * The callback will get the parameter tag_group_info, which will include a group of tag memory addresses and cache memory addresses. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to check and the cache mode. + * + * @param uint32_t filter_addr : only the cache lines which may include the filter_address will be returned to the call back function. + * 0 for do not filter, all cache lines will be returned. + * + * @param void (* process)(struct tag_group_info *) : call back function, which may be called many times, a group(the addresses in the group are in the same position in the cache ways) a time. + * + * @return None + */ +void Cache_Travel_Tag_Memory(struct cache_mode *mode, uint32_t filter_addr, void (* process)(struct tag_group_info *)); + +/** + * @brief Get the virtual address from cache mode, cache tag and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t tag : the tag part fo a tag item, 12-14 bits. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Virtual_Addr(struct cache_mode *mode, uint32_t tag, uint32_t vaddr_offset); + +/** + * @brief Get cache memory block base address. + * Please do not call this function in your SDK application. + * + * @param uint32_t icache : 0 for dcache, other for icache. + * + * @param uint32_t bank_no : 0 ~ 3 bank. + * + * @return uint32_t : the cache memory block base address, 0 if the block not used. + */ +uint32_t Cache_Get_Memory_BaseAddr(uint32_t icache, uint32_t bank_no); + +/** + * @brief Get the cache memory address from cache mode, cache memory offset and the virtual address offset of cache ways. + * Please do not call this function in your SDK application. + * + * @param struct cache_mode * mode : the cache to calculate the virtual address and the cache mode. + * + * @param uint32_t cache_memory_offset : the cache memory offset of the whole cache (ICache or DCache) for the cache line. + * + * @param uint32_t addr_offset : the virtual address offset of the cache ways. + * + * @return uint32_t : the virtual address. + */ +uint32_t Cache_Get_Memory_Addr(struct cache_mode *mode, uint32_t cache_memory_offset, uint32_t vaddr_offset); + +/** + * @brief Get the cache memory value by DRAM address. + * Please do not call this function in your SDK application. + * + * @param uint32_t cache_memory_addr : DRAM address for the cache memory, should be 4 byte aligned for IBus address. + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_Memory_value(uint32_t cache_memory_addr); +/** + * @} + */ + +/** + * @brief Get the cache MMU IROM end address. + * Please do not call this function in your SDK application. + * + * @param void + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_IROM_MMU_End(void); + +/** + * @brief Get the cache MMU DROM end address. + * Please do not call this function in your SDK application. + * + * @param void + * + * @return uint32_t : the word value of the address. + */ +uint32_t Cache_Get_DROM_MMU_End(void); + +/** + * @brief Used by SPI flash mmap + * + */ +int flash2spiram_instruction_offset(void); +int flash2spiram_rodata_offset(void); +uint32_t flash_instr_rodata_start_page(uint32_t bus); +uint32_t flash_instr_rodata_end_page(uint32_t bus); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/crc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/crc.h new file mode 100644 index 00000000..e47a2ff5 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/crc.h @@ -0,0 +1,122 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup crc_apis, uart configuration and communication related apis + * @brief crc apis + */ + +/** @addtogroup crc_apis + * @{ + */ + +/* Standard CRC8/16/32 algorithms. */ +// CRC-8 x8+x2+x1+1 0x07 +// CRC16-CCITT x16+x12+x5+1 1021 ISO HDLC, ITU X.25, V.34/V.41/V.42, PPP-FCS +// CRC32: +//G(x) = x32 +x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x1 + 1 +//If your buf is not continuous, you can use the first result to be the second parameter. + +/** + * @brief Crc32 value that is in little endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc32 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint32_t crc32_be(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc16 value that is in little endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc16 value that is in big endian. + * + * @param uint16_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint16_t crc16_be(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc8 value that is in little endian. + * + * @param uint8_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief Crc8 value that is in big endian. + * + * @param uint32_t crc : init crc value, use 0 at the first use. + * + * @param uint8_t const *buf : buffer to start calculate crc. + * + * @param uint32_t len : buffer length in byte. + * + * @return None + */ +uint8_t crc8_be(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/digital_signature.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/digital_signature.h new file mode 100644 index 00000000..36e71e7c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/digital_signature.h @@ -0,0 +1,142 @@ +// Copyright 2019-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define ETS_DS_IV_LEN 16 + +/* Length of parameter 'C' stored in flash */ +#define ETS_DS_C_LEN (12672 / 8) + +/* Encrypted ETS data. Recommended to store in flash in this format. + */ +typedef struct { + /* RSA LENGTH register parameters + * (number of words in RSA key & operands, minus one). + * + * Max value 127 (for RSA 4096). + * + * This value must match the length field encrypted and stored in 'c', + * or invalid results will be returned. (The DS peripheral will + * always use the value in 'c', not this value, so an attacker can't + * alter the DS peripheral results this way, it will just truncate or + * extend the message and the resulting signature in software.) + */ + unsigned rsa_length; + + /* IV value used to encrypt 'c' */ + uint8_t iv[ETS_DS_IV_LEN]; + + /* Encrypted Digital Signature parameters. Result of AES-CBC encryption + of plaintext values. Includes an encrypted message digest. + */ + uint8_t c[ETS_DS_C_LEN]; +} ets_ds_data_t; + +typedef enum { + ETS_DS_OK, + ETS_DS_INVALID_PARAM, /* Supplied parameters are invalid */ + ETS_DS_INVALID_KEY, /* HMAC peripheral failed to supply key */ + ETS_DS_INVALID_PADDING, /* 'c' decrypted with invalid padding */ + ETS_DS_INVALID_DIGEST, /* 'c' decrypted with invalid digest */ +} ets_ds_result_t; + +void ets_ds_enable(void); + +void ets_ds_disable(void); + +/* + * @brief Start signing a message (or padded message digest) using the Digital Signature peripheral + * + * - @param message Pointer to message (or padded digest) containing the message to sign. Should be + * (data->rsa_length + 1)*4 bytes long. @param data Pointer to DS data. Can be a pointer to data + * in flash. + * + * Caller must have already called ets_ds_enable() and ets_hmac_calculate_downstream() before calling + * this function, and is responsible for calling ets_ds_finish_sign() and then + * ets_hmac_invalidate_downstream() afterwards. + * + * @return ETS_DS_OK if signature is in progress, ETS_DS_INVALID_PARAM if param is invalid, + * EST_DS_INVALID_KEY if key or HMAC peripheral is configured incorrectly. + */ +ets_ds_result_t ets_ds_start_sign(const void *message, const ets_ds_data_t *data); + + +/* + * @brief Returns true if the DS peripheral is busy following a call to ets_ds_start_sign() + * + * A result of false indicates that a call to ets_ds_finish_sign() will not block. + * + * Only valid if ets_ds_enable() has been called. + */ +bool ets_ds_is_busy(void); + + +/* @brief Finish signing a message using the Digital Signature peripheral + * + * Must be called after ets_ds_start_sign(). Can use ets_ds_busy() to wait until + * peripheral is no longer busy. + * + * - @param signature Pointer to buffer to contain the signature. Should be + * (data->rsa_length + 1)*4 bytes long. + * - @param data Should match the 'data' parameter passed to ets_ds_start_sign() + * + * @param ETS_DS_OK if signing succeeded, ETS_DS_INVALID_PARAM if param is invalid, + * ETS_DS_INVALID_DIGEST or ETS_DS_INVALID_PADDING if there is a problem with the + * encrypted data digest or padding bytes (in case of ETS_DS_INVALID_PADDING, a + * digest is produced anyhow.) + */ +ets_ds_result_t ets_ds_finish_sign(void *signature, const ets_ds_data_t *data); + + +/* Plaintext parameters used by Digital Signature. + + Not used for signing with DS peripheral, but can be encrypted + in-device by calling ets_ds_encrypt_params() +*/ +typedef struct { + uint32_t Y[4096 / 32]; + uint32_t M[4096 / 32]; + uint32_t Rb[4096 / 32]; + uint32_t M_prime; + uint32_t length; +} ets_ds_p_data_t; + +typedef enum { + ETS_DS_KEY_HMAC, /* The HMAC key (as stored in efuse) */ + ETS_DS_KEY_AES, /* The AES key (as derived from HMAC key by HMAC peripheral in downstream mode) */ +} ets_ds_key_t; + +/* @brief Encrypt DS parameters suitable for storing and later use with DS peripheral + * + * @param data Output buffer to store encrypted data, suitable for later use generating signatures. + * @param iv Pointer to 16 byte IV buffer, will be copied into 'data'. Should be randomly generated bytes each time. + * @param p_data Pointer to input plaintext key data. The expectation is this data will be deleted after this process is done and 'data' is stored. + * @param key Pointer to 32 bytes of key data. Type determined by key_type parameter. The expectation is the corresponding HMAC key will be stored to efuse and then permanently erased. + * @param key_type Type of key stored in 'key' (either the AES-256 DS key, or an HMAC DS key from which the AES DS key is derived using HMAC peripheral) + * + * @return ETS_DS_INVALID_PARAM if any parameter is invalid, or ETS_DS_OK if 'data' is successfully generated from the input parameters. + */ +ets_ds_result_t ets_ds_encrypt_params(ets_ds_data_t *data, const void *iv, const ets_ds_p_data_t *p_data, const void *key, ets_ds_key_t key_type); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/efuse.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/efuse.h new file mode 100644 index 00000000..cbe38e6a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/efuse.h @@ -0,0 +1,391 @@ +// Copyright 2015-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +/** \defgroup efuse_APIs efuse APIs + * @brief ESP32 efuse read/write APIs + * @attention + * + */ + +/** @addtogroup efuse_APIs + * @{ + */ + +typedef enum { + ETS_EFUSE_KEY_PURPOSE_USER = 0, + ETS_EFUSE_KEY_PURPOSE_RESERVED = 1, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_1 = 2, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_256_KEY_2 = 3, + ETS_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY = 4, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL = 5, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG = 6, + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE = 7, + ETS_EFUSE_KEY_PURPOSE_HMAC_UP = 8, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST0 = 9, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST1 = 10, + ETS_EFUSE_KEY_PURPOSE_SECURE_BOOT_DIGEST2 = 11, + ETS_EFUSE_KEY_PURPOSE_MAX, +} ets_efuse_purpose_t; + +typedef enum { + ETS_EFUSE_BLOCK0 = 0, + ETS_EFUSE_MAC_SPI_SYS_0 = 1, + ETS_EFUSE_BLOCK_SYS_DATA = 2, + ETS_EFUSE_BLOCK_USR_DATA = 3, + ETS_EFUSE_BLOCK_KEY0 = 4, + ETS_EFUSE_BLOCK_KEY1 = 5, + ETS_EFUSE_BLOCK_KEY2 = 6, + ETS_EFUSE_BLOCK_KEY3 = 7, + ETS_EFUSE_BLOCK_KEY4 = 8, + ETS_EFUSE_BLOCK_KEY5 = 9, + ETS_EFUSE_BLOCK_KEY6 = 10, + ETS_EFUSE_BLOCK_MAX, +} ets_efuse_block_t; + +/** + * @brief set timing accroding the apb clock, so no read error or write error happens. + * + * @param clock: apb clock in HZ, only accept 5M(in FPGA), 10M(in FPGA), 20M, 40M, 80M. + * + * @return : 0 if success, others if clock not accepted + */ +int ets_efuse_set_timing(uint32_t clock); + +/** + * @brief Enable efuse subsystem. Called after reset. Doesn't need to be called again. + */ +void ets_efuse_start(void); + +/** + * @brief Efuse read operation: copies data from physical efuses to efuse read registers. + * + * @param null + * + * @return : 0 if success, others if apb clock is not accepted + */ +int ets_efuse_read(void); + +/** + * @brief Efuse write operation: Copies data from efuse write registers to efuse. Operates on a single block of efuses at a time. + * + * @note This function does not update read efuses, call ets_efuse_read() once all programming is complete. + * + * @return : 0 if success, others if apb clock is not accepted + */ +int ets_efuse_program(ets_efuse_block_t block); + +/** + * @brief Set all Efuse program registers to zero. + * + * Call this before writing new data to the program registers. + */ +void ets_efuse_clear_program_registers(void); + +/** + * @brief Program a block of key data to an efuse block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. Key block must be unused (@ref ets_efuse_key_block_unused). + * @param purpose Purpose to set for this key. Purpose must be already unset. + * @param data Pointer to data to write. + * @param data_len Length of data to write. + * + * @note This function also calls ets_efuse_program() for the specified block, and for block 0 (setting the purpose) + */ +int ets_efuse_write_key(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose, const void *data, size_t data_len); + + +/* @brief Return the address of a particular efuse block's first read register + * + * @param block Index of efuse block to look up + * + * @return 0 if block is invalid, otherwise a numeric read register address + * of the first word in the block. + */ +uint32_t ets_efuse_get_read_register_address(ets_efuse_block_t block); + +/** + * @brief Return the current purpose set for an efuse key block + * + * @param key_block Block to read purpose for. Must be in range ETS_EFUSE_BLOCK_KEY0 to ETS_EFUSE_BLOCK_KEY6. + */ +ets_efuse_purpose_t ets_efuse_get_key_purpose(ets_efuse_block_t key_block); + +/** + * @brief Find a key block with the particular purpose set + * + * @param purpose Purpose to search for. + * @param[out] key_block Pointer which will be set to the key block if found. Can be NULL, if only need to test the key block exists. + * @return true if found, false if not found. If false, value at key_block pointer is unchanged. + */ +bool ets_efuse_find_purpose(ets_efuse_purpose_t purpose, ets_efuse_block_t *key_block); + +/** + * Return true if the key block is unused, false otherwise. + * + * An unused key block is all zero content, not read or write protected, + * and has purpose 0 (ETS_EFUSE_KEY_PURPOSE_USER) + * + * @param key_block key block to check. + * + * @return true if key block is unused, false if key block or used + * or the specified block index is not a key block. + */ +bool ets_efuse_key_block_unused(ets_efuse_block_t key_block); + + +/** + * @brief Search for an unused key block and return the first one found. + * + * See @ref ets_efuse_key_block_unused for a description of an unused key block. + * + * @return First unused key block, or ETS_EFUSE_BLOCK_MAX if no unused key block is found. + */ +ets_efuse_block_t ets_efuse_find_unused_key_block(void); + +/** + * @brief Return the number of unused efuse key blocks (0-6) + */ +unsigned ets_efuse_count_unused_key_blocks(void); + +/** + * @brief Calculate Reed-Solomon Encoding values for a block of efuse data. + * + * @param data Pointer to data buffer (length 32 bytes) + * @param rs_values Pointer to write encoded data to (length 12 bytes) + */ +void ets_efuse_rs_calculate(const void *data, void *rs_values); + +/** + * @brief Read spi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - 1 for default HSPI pins. + * - Other values define a custom pin configuration mask. Pins are encoded as per the EFUSE_SPICONFIG_RET_SPICLK, + * EFUSE_SPICONFIG_RET_SPIQ, EFUSE_SPICONFIG_RET_SPID, EFUSE_SPICONFIG_RET_SPICS0, EFUSE_SPICONFIG_RET_SPIHD macros. + * WP pin (for quad I/O modes) is not saved in efuse and not returned by this function. + */ +uint32_t ets_efuse_get_spiconfig(void); + +/** + * @brief Read spi flash wp pad from Efuse + * + * @return + * - 0x3f for invalid. + * - 0~46 is valid. + */ +uint32_t ets_efuse_get_wp_pad(void); + +/** + * @brief Read opi flash pads configuration from Efuse + * + * @return + * - 0 for default SPI pins. + * - Other values define a custom pin configuration mask. From the LSB, every 6 bits represent a GPIO number which stand for: + * DQS, D4, D5, D6, D7 accordingly. + */ +uint32_t ets_efuse_get_opiconfig(void); + +/** + * @brief Read if download mode disabled from Efuse + * + * @return + * - true for efuse disable download mode. + * - false for efuse doesn't disable download mode. + */ +bool ets_efuse_download_modes_disabled(void); + +/** + * @brief Read if legacy spi flash boot mode disabled from Efuse + * + * @return + * - true for efuse disable legacy spi flash boot mode. + * - false for efuse doesn't disable legacy spi flash boot mode. + */ +bool ets_efuse_legacy_spi_boot_mode_disabled(void); + +/** + * @brief Read if uart print control value from Efuse + * + * @return + * - 0 for uart force print. + * - 1 for uart print when GPIO46 is low when digital reset. + * 2 for uart print when GPIO46 is high when digital reset. + * 3 for uart force slient + */ +uint32_t ets_efuse_get_uart_print_control(void); + +/** + * @brief Read which channel will used by ROM to print + * + * @return + * - 0 for UART0. + * - 1 for UART1. + */ +uint32_t ets_efuse_get_uart_print_channel(void); + +/** + * @brief Read if usb download mode disabled from Efuse + * + * (Also returns true if security download mode is enabled, as this mode + * disables USB download.) + * + * @return + * - true for efuse disable usb download mode. + * - false for efuse doesn't disable usb download mode. + */ +bool ets_efuse_usb_download_mode_disabled(void); + +/** + * @brief Read if tiny basic mode disabled from Efuse + * + * @return + * - true for efuse disable tiny basic mode. + * - false for efuse doesn't disable tiny basic mode. + */ +bool ets_efuse_tiny_basic_mode_disabled(void); + +/** + * @brief Read if usb module disabled from Efuse + * + * @return + * - true for efuse disable usb module. + * - false for efuse doesn't disable usb module. + */ +bool ets_efuse_usb_module_disabled(void); + +/** + * @brief Read if security download modes enabled from Efuse + * + * @return + * - true for efuse enable security download mode. + * - false for efuse doesn't enable security download mode. + */ +bool ets_efuse_security_download_modes_enabled(void); + +/** + * @brief Return true if secure boot is enabled in EFuse + */ +bool ets_efuse_secure_boot_enabled(void); + +/** + * @brief Return true if secure boot aggressive revoke is enabled in EFuse + */ +bool ets_efuse_secure_boot_aggressive_revoke_enabled(void); + +/** + * @brief Return true if cache encryption (flash, PSRAM, etc) is enabled from boot via EFuse + */ +bool ets_efuse_cache_encryption_enabled(void); + +/** + * @brief Return true if EFuse indicates an external phy needs to be used for USB + */ +bool ets_efuse_usb_use_ext_phy(void); + +/** + * @brief Return true if EFuse indicates USB device persistence is disabled + */ +bool ets_efuse_usb_force_nopersist(void); + +/** + * @brief Return true if OPI pins GPIO33-37 are powered by VDDSPI, otherwise by VDD33CPU + */ +bool ets_efuse_flash_opi_5pads_power_sel_vddspi(void); + +/** + * @brief Return true if EFuse indicates an opi flash is attached. + */ +bool ets_efuse_flash_opi_mode(void); + +/** + * @brief Return true if EFuse indicates to send a flash resume command. + */ +bool ets_efuse_force_send_resume(void); + +/** + * @brief return the time in us ROM boot need wait flash to power on from Efuse + * + * @return + * - uint32_t the time in us. + */ +uint32_t ets_efuse_get_flash_delay_us(void); + +#define EFUSE_SPICONFIG_SPI_DEFAULTS 0 +#define EFUSE_SPICONFIG_HSPI_DEFAULTS 1 + +#define EFUSE_SPICONFIG_RET_SPICLK_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICLK_SHIFT 0 +#define EFUSE_SPICONFIG_RET_SPICLK(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICLK_SHIFT) & EFUSE_SPICONFIG_RET_SPICLK_MASK) + +#define EFUSE_SPICONFIG_RET_SPIQ_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIQ_SHIFT 6 +#define EFUSE_SPICONFIG_RET_SPIQ(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIQ_SHIFT) & EFUSE_SPICONFIG_RET_SPIQ_MASK) + +#define EFUSE_SPICONFIG_RET_SPID_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPID_SHIFT 12 +#define EFUSE_SPICONFIG_RET_SPID(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPID_SHIFT) & EFUSE_SPICONFIG_RET_SPID_MASK) + +#define EFUSE_SPICONFIG_RET_SPICS0_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPICS0_SHIFT 18 +#define EFUSE_SPICONFIG_RET_SPICS0(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPICS0_SHIFT) & EFUSE_SPICONFIG_RET_SPICS0_MASK) + + +#define EFUSE_SPICONFIG_RET_SPIHD_MASK 0x3f +#define EFUSE_SPICONFIG_RET_SPIHD_SHIFT 24 +#define EFUSE_SPICONFIG_RET_SPIHD(ret) (((ret) >> EFUSE_SPICONFIG_RET_SPIHD_SHIFT) & EFUSE_SPICONFIG_RET_SPIHD_MASK) + +/** + * @brief Enable JTAG temporarily by writing a JTAG HMAC "key" into + * the JTAG_CTRL registers. + * + * Works if JTAG has been "soft" disabled by burning the EFUSE_SOFT_DIS_JTAG efuse. + * + * Will enable the HMAC module to generate a "downstream" HMAC value from a key already saved in efuse, and then write the JTAG HMAC "key" which will enable JTAG if the two keys match. + * + * @param jtag_hmac_key Pointer to a 32 byte array containing a valid key. Supplied by user. + * @param key_block Index of a key block containing the source for this key. + * + * @return ETS_FAILED if HMAC operation fails or invalid parameter, ETS_OK otherwise. ETS_OK doesn't necessarily mean that JTAG was enabled. + */ +int ets_jtag_enable_temporarily(const uint8_t *jtag_hmac_key, ets_efuse_block_t key_block); + +/** + * @brief A crc8 algorithm used for MAC addresses in efuse + * + * @param unsigned char const *p : Pointer to original data. + * + * @param unsigned int len : Data length in byte. + * + * @return unsigned char: Crc value. + */ +unsigned char esp_crc8(unsigned char const *p, unsigned int len); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/ets_sys.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/ets_sys.h new file mode 100644 index 00000000..edf9627c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/ets_sys.h @@ -0,0 +1,654 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include +#include +#include "soc/soc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup ets_sys_apis, ets system related apis + * @brief ets system apis + */ + +/** @addtogroup ets_sys_apis + * @{ + */ + +/************************************************************************ + * NOTE + * Many functions in this header files can't be run in FreeRTOS. + * Please see the comment of the Functions. + * There are also some functions that doesn't work on FreeRTOS + * without listed in the header, such as: + * xtos functions start with "_xtos_" in ld file. + * + *********************************************************************** + */ + +/** \defgroup ets_apis, Espressif Task Scheduler related apis + * @brief ets apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +typedef enum { + ETS_OK = 0, /**< return successful in ets*/ + ETS_FAILED = 1 /**< return failed in ets*/ +} ETS_STATUS; + +typedef ETS_STATUS ets_status_t; + +typedef uint32_t ETSSignal; +typedef uint32_t ETSParam; + +typedef struct ETSEventTag ETSEvent; /**< Event transmit/receive in ets*/ + +struct ETSEventTag { + ETSSignal sig; /**< Event signal, in same task, different Event with different signal*/ + ETSParam par; /**< Event parameter, sometimes without usage, then will be set as 0*/ +}; + +typedef void (*ETSTask)(ETSEvent *e); /**< Type of the Task processer*/ +typedef void (* ets_idle_cb_t)(void *arg); /**< Type of the system idle callback*/ + +/** + * @brief Start the Espressif Task Scheduler, which is an infinit loop. Please do not add code after it. + * + * @param none + * + * @return none + */ +void ets_run(void); + +/** + * @brief Set the Idle callback, when Tasks are processed, will call the callback before CPU goto sleep. + * + * @param ets_idle_cb_t func : The callback function. + * + * @param void *arg : Argument of the callback. + * + * @return None + */ +void ets_set_idle_cb(ets_idle_cb_t func, void *arg); + +/** + * @brief Init a task with processer, priority, queue to receive Event, queue length. + * + * @param ETSTask task : The task processer. + * + * @param uint8_t prio : Task priority, 0-31, bigger num with high priority, one priority with one task. + * + * @param ETSEvent *queue : Queue belongs to the task, task always receives Events, Queue is circular used. + * + * @param uint8_t qlen : Queue length. + * + * @return None + */ +void ets_task(ETSTask task, uint8_t prio, ETSEvent *queue, uint8_t qlen); + +/** + * @brief Post an event to an Task. + * + * @param uint8_t prio : Priority of the Task. + * + * @param ETSSignal sig : Event signal. + * + * @param ETSParam par : Event parameter + * + * @return ETS_OK : post successful + * @return ETS_FAILED : post failed + */ +ETS_STATUS ets_post(uint8_t prio, ETSSignal sig, ETSParam par); + +/** + * @} + */ + +/** \defgroup ets_boot_apis, Boot routing related apis + * @brief ets boot apis + */ + +/** @addtogroup ets_apis + * @{ + */ + +extern const char *const exc_cause_table[40]; ///**< excption cause that defined by the core.*/ + +/** + * @brief Set Pro cpu Entry code, code can be called in PRO CPU when booting is not completed. + * When Pro CPU booting is completed, Pro CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the PRO Entry code address value in uint32_t + * + * @return None + */ +void ets_set_user_start(uint32_t start); + +/** + * @brief Set Pro cpu Startup code, code can be called when booting is not completed, or in Entry code. + * When Entry code completed, CPU will call the Startup code if not NULL, else call ets_run. + * + * @param uint32_t callback : the Startup code address value in uint32_t + * + * @return None : post successful + */ +void ets_set_startup_callback(uint32_t callback); + +/** + * @brief Set App cpu Entry code, code can be called in PRO CPU. + * When APP booting is completed, APP CPU will call the Entry code if not NULL. + * + * @param uint32_t start : the APP Entry code address value in uint32_t, stored in register APPCPU_CTRL_REG_D. + * + * @return None + */ +void ets_set_appcpu_boot_addr(uint32_t start); + +/** + * @} + */ + +/** \defgroup ets_printf_apis, ets_printf related apis used in ets + * @brief ets printf apis + */ + +/** @addtogroup ets_printf_apis + * @{ + */ + +/** + * @brief Printf the strings to uart or other devices, similar with printf, simple than printf. + * Can not print float point data format, or longlong data format. + * So we maybe only use this in ROM. + * + * @param const char *fmt : See printf. + * + * @param ... : See printf. + * + * @return int : the length printed to the output device. + */ +int ets_printf(const char *fmt, ...); + +/** + * @brief Set the uart channel of ets_printf(uart_tx_one_char). + * ROM will set it base on the efuse and gpio setting, however, this can be changed after booting. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2. + * + * @return None + */ +void ets_set_printf_channel(uint8_t uart_no); + +/** + * @brief Get the uart channel of ets_printf(uart_tx_one_char). + * + * @return uint8_t uart channel used by ets_printf(uart_tx_one_char). + */ +uint8_t ets_get_printf_channel(void); + +/** + * @brief Output a char to uart, which uart to output(which is in uart module in ROM) is not in scope of the function. + * Can not print float point data format, or longlong data format + * + * @param char c : char to output. + * + * @return None + */ +void ets_write_char_uart(char c); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc1, which is defaulted installed as ets_write_char_uart in none silent boot mode, as NULL in silent mode. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc1(void (*p)(char c)); + +/** + * @brief Ets_printf have two output functions: putc1 and putc2, both of which will be called if need ouput. + * To install putc2, which is defaulted installed as NULL. + * + * @param void (*)(char) p: Output function to install. + * + * @return None + */ +void ets_install_putc2(void (*p)(char c)); + +/** + * @brief Install putc1 as ets_write_char_uart. + * In silent boot mode(to void interfere the UART attached MCU), we can call this function, after booting ok. + * + * @param None + * + * @return None + */ +void ets_install_uart_printf(void); + +#define ETS_PRINTF(...) ets_printf(...) + +#define ETS_ASSERT(v) do { \ + if (!(v)) { \ + ets_printf("%s %u \n", __FILE__, __LINE__); \ + while (1) {}; \ + } \ +} while (0); + +/** + * @} + */ + +/** \defgroup ets_timer_apis, ets_timer related apis used in ets + * @brief ets timer apis + */ + +/** @addtogroup ets_timer_apis + * @{ + */ +typedef void ETSTimerFunc(void *timer_arg);/**< timer handler*/ + +typedef struct _ETSTIMER_ { + struct _ETSTIMER_ *timer_next; /**< timer linker*/ + uint32_t timer_expire; /**< abstruct time when timer expire*/ + uint32_t timer_period; /**< timer period, 0 means timer is not periodic repeated*/ + ETSTimerFunc *timer_func; /**< timer handler*/ + void *timer_arg; /**< timer handler argument*/ +} ETSTimer; + +/** + * @brief Init ets timer, this timer range is 640 us to 429496 ms + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_init(void); + +/** + * @brief In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_timer_deinit(void); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in ms, range is 1 to 429496. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm(ETSTimer *timer, uint32_t tmout, bool repeat); + +/** + * @brief Arm an ets timer, this timer range is 640 us to 429496 ms. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param uint32_t tmout : Timer value in us, range is 1 to 429496729. + * + * @param bool repeat : Timer is periodic repeated. + * + * @return None + */ +void ets_timer_arm_us(ETSTimer *ptimer, uint32_t us, bool repeat); + +/** + * @brief Disarm an ets timer. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_disarm(ETSTimer *timer); + +/** + * @brief Set timer callback and argument. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @param ETSTimerFunc *pfunction : Timer callback. + * + * @param void *parg : Timer callback argument. + * + * @return None + */ +void ets_timer_setfn(ETSTimer *ptimer, ETSTimerFunc *pfunction, void *parg); + +/** + * @brief Unset timer callback and argument to NULL. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param ETSTimer *timer : Timer struct pointer. + * + * @return None + */ +void ets_timer_done(ETSTimer *ptimer); + +/** + * @brief CPU do while loop for some time. + * In FreeRTOS task, please call FreeRTOS apis. + * + * @param uint32_t us : Delay time in us. + * + * @return None + */ +void ets_delay_us(uint32_t us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * Call this function when CPU frequency is changed. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency(uint32_t ticks_per_us); + +/** + * @brief Set the real CPU ticks per us to the ets, so that ets_delay_us will be accurate. + * + * @note This function only sets the tick rate for the current CPU. It is located in ROM, + * so the deep sleep stub can use it even if IRAM is not initialized yet. + * + * @param uint32_t ticks_per_us : CPU ticks per us. + * + * @return None + */ +void ets_update_cpu_frequency_rom(uint32_t ticks_per_us); + +/** + * @brief Get the real CPU ticks per us to the ets. + * This function do not return real CPU ticks per us, just the record in ets. It can be used to check with the real CPU frequency. + * + * @param None + * + * @return uint32_t : CPU ticks per us record in ets. + */ +uint32_t ets_get_cpu_frequency(void); + +/** + * @brief Get xtal_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if stored in efuse(not 0) + * clock = ets_efuse_get_xtal_freq() * 1000000; + * else if analog_8M in efuse + * clock = ets_get_xtal_scale() * 625 / 16 * ets_efuse_get_8M_clock(); + * else clock = 40M. + */ +uint32_t ets_get_xtal_freq(void); + +/** + * @brief Get the apb divisor. The xtal frequency gets divided + * by this value to generate the APB clock. + * When any types of reset happens, the default value is 2. + * + * @param None + * + * @return uint32_t : 1 or 2. + */ +uint32_t ets_get_xtal_div(void); + + +/** + * @brief Modifies the apb divisor. The xtal frequency gets divided by this to + * generate the APB clock. + * + * @note The xtal frequency divisor is 2 by default as the glitch detector + * doesn't properly stop glitches when it is 1. Please do not set the + * divisor to 1 before the PLL is active without being aware that you + * may be introducing a security risk. + * + * @param div Divisor. 1 = xtal freq, 2 = 1/2th xtal freq. + */ +void ets_set_xtal_div(int div); + + +/** + * @brief Get apb_freq value, If value not stored in RTC_STORE5, than store. + * + * @param None + * + * @return uint32_t : if rtc store the value (RTC_STORE5 high 16 bits and low 16 bits with same value), read from rtc register. + * clock = (REG_READ(RTC_STORE5) & 0xffff) << 12; + * else store ets_get_detected_xtal_freq() in. + */ +uint32_t ets_get_apb_freq(void); + +/** + * @} + */ + +/** \defgroup ets_intr_apis, ets interrupt configure related apis + * @brief ets intr apis + */ + +/** @addtogroup ets_intr_apis + * @{ + */ + +typedef void (* ets_isr_t)(void *);/**< interrupt handler type*/ + +/** + * @brief Attach a interrupt handler to a CPU interrupt number. + * This function equals to _xtos_set_interrupt_handler_arg(i, func, arg). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param int i : CPU interrupt number. + * + * @param ets_isr_t func : Interrupt handler. + * + * @param void *arg : argument of the handler. + * + * @return None + */ +void ets_isr_attach(int i, ets_isr_t func, void *arg); + +/** + * @brief Mask the interrupts which show in mask bits. + * This function equals to _xtos_ints_off(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_mask(uint32_t mask); + +/** + * @brief Unmask the interrupts which show in mask bits. + * This function equals to _xtos_ints_on(mask). + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param uint32_t mask : BIT(i) means mask CPU interrupt number i. + * + * @return None + */ +void ets_isr_unmask(uint32_t unmask); + +/** + * @brief Lock the interrupt to level 2. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_lock(void); + +/** + * @brief Unlock the interrupt to level 0. + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_intr_unlock(void); + +/** + * @brief Unlock the interrupt to level 0, and CPU will go into power save mode(wait interrupt). + * This function direct set the CPU registers. + * In FreeRTOS, please call FreeRTOS apis, never call this api. + * + * @param None + * + * @return None + */ +void ets_waiti0(void); + +/** + * @brief Attach an CPU interrupt to a hardware source. + * We have 4 steps to use an interrupt: + * 1.Attach hardware interrupt source to CPU. intr_matrix_set(0, ETS_WIFI_MAC_INTR_SOURCE, ETS_WMAC_INUM); + * 2.Set interrupt handler. xt_set_interrupt_handler(ETS_WMAC_INUM, func, NULL); + * 3.Enable interrupt for CPU. xt_ints_on(1 << ETS_WMAC_INUM); + * 4.Enable interrupt in the module. + * + * @param int cpu_no : The CPU which the interrupt number belongs. + * + * @param uint32_t model_num : The interrupt hardware source number, please see the interrupt hardware source table. + * + * @param uint32_t intr_num : The interrupt number CPU, please see the interrupt cpu using table. + * + * @return None + */ +void intr_matrix_set(int cpu_no, uint32_t model_num, uint32_t intr_num); + +#define _ETSTR(v) # v +#define _ETS_SET_INTLEVEL(intlevel) ({ unsigned __tmp; \ + __asm__ __volatile__( "rsil %0, " _ETSTR(intlevel) "\n" \ + : "=a" (__tmp) : : "memory" ); \ + }) + +#ifdef CONFIG_NONE_OS +#define ETS_INTR_LOCK() \ + ets_intr_lock() + +#define ETS_INTR_UNLOCK() \ + ets_intr_unlock() + +#define ETS_ISR_ATTACH \ + ets_isr_attach + +#define ETS_INTR_ENABLE(inum) \ + ets_isr_unmask((1< +#include +#include "soc/gpio_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup gpio_apis, uart configuration and communication related apis + * @brief gpio apis + */ + +/** @addtogroup gpio_apis + * @{ + */ + +#define GPIO_REG_READ(reg) READ_PERI_REG(reg) +#define GPIO_REG_WRITE(reg, val) WRITE_PERI_REG(reg, val) +#define GPIO_ID_PIN0 0 +#define GPIO_ID_PIN(n) (GPIO_ID_PIN0+(n)) +#define GPIO_PIN_ADDR(i) (GPIO_PIN0_REG + i*4) + +#define GPIO_FUNC_IN_HIGH 0x38 +#define GPIO_FUNC_IN_LOW 0x3C + +#define GPIO_ID_IS_PIN_REGISTER(reg_id) \ + ((reg_id >= GPIO_ID_PIN0) && (reg_id <= GPIO_ID_PIN(GPIO_PIN_COUNT-1))) + +#define GPIO_REGID_TO_PINIDX(reg_id) ((reg_id) - GPIO_ID_PIN0) + +typedef enum { + GPIO_PIN_INTR_DISABLE = 0, + GPIO_PIN_INTR_POSEDGE = 1, + GPIO_PIN_INTR_NEGEDGE = 2, + GPIO_PIN_INTR_ANYEDGE = 3, + GPIO_PIN_INTR_LOLEVEL = 4, + GPIO_PIN_INTR_HILEVEL = 5 +} GPIO_INT_TYPE; + +#define GPIO_OUTPUT_SET(gpio_no, bit_value) \ + ((gpio_no < 32) ? gpio_output_set(bit_value<>gpio_no)&BIT0) : ((gpio_input_get_high()>>(gpio_no - 32))&BIT0)) + +/* GPIO interrupt handler, registered through gpio_intr_handler_register */ +typedef void (* gpio_intr_handler_fn_t)(uint32_t intr_mask, bool high, void *arg); + +/** + * @brief Initialize GPIO. This includes reading the GPIO Configuration DataSet + * to initialize "output enables" and pin configurations for each gpio pin. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_init(void); + +/** + * @brief Change GPIO(0-31) pin output by setting, clearing, or disabling pins, GPIO0<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Change GPIO(32-39) pin output by setting, clearing, or disabling pins, GPIO32<->BIT(0). + * There is no particular ordering guaranteed; so if the order of writes is significant, + * calling code should divide a single call into multiple calls. + * + * @param uint32_t set_mask : the gpios that need high level. + * + * @param uint32_t clear_mask : the gpios that need low level. + * + * @param uint32_t enable_mask : the gpios that need be changed. + * + * @param uint32_t disable_mask : the gpios that need diable output. + * + * @return None + */ +void gpio_output_set_high(uint32_t set_mask, uint32_t clear_mask, uint32_t enable_mask, uint32_t disable_mask); + +/** + * @brief Sample the value of GPIO input pins(0-31) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO0. + */ +uint32_t gpio_input_get(void); + +/** + * @brief Sample the value of GPIO input pins(32-39) and returns a bitmask. + * + * @param None + * + * @return uint32_t : bitmask for GPIO input pins, BIT(0) for GPIO32. + */ +uint32_t gpio_input_get_high(void); + +/** + * @brief Register an application-specific interrupt handler for GPIO pin interrupts. + * Once the interrupt handler is called, it will not be called again until after a call to gpio_intr_ack. + * Please do not call this function in SDK. + * + * @param gpio_intr_handler_fn_t fn : gpio application-specific interrupt handler + * + * @param void *arg : gpio application-specific interrupt handler argument. + * + * @return None + */ +void gpio_intr_handler_register(gpio_intr_handler_fn_t fn, void *arg); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO0. + */ +uint32_t gpio_intr_pending(void); + +/** + * @brief Get gpio interrupts which happens but not processed. + * Please do not call this function in SDK. + * + * @param None + * + * @return uint32_t : bitmask for GPIO pending interrupts, BIT(0) for GPIO32. + */ +uint32_t gpio_intr_pending_high(void); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO0. + * + * @return None + */ +void gpio_intr_ack(uint32_t ack_mask); + +/** + * @brief Ack gpio interrupts to process pending interrupts. + * Please do not call this function in SDK. + * + * @param uint32_t ack_mask: bitmask for GPIO ack interrupts, BIT(0) for GPIO32. + * + * @return None + */ +void gpio_intr_ack_high(uint32_t ack_mask); + +/** + * @brief Set GPIO to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param uint32_t i: gpio number. + * + * @param GPIO_INT_TYPE intr_state : only GPIO_PIN_INTR_LOLEVEL\GPIO_PIN_INTR_HILEVEL can be used + * + * @return None + */ +void gpio_pin_wakeup_enable(uint32_t i, GPIO_INT_TYPE intr_state); + +/** + * @brief disable GPIOs to wakeup the ESP32. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void gpio_pin_wakeup_disable(void); + +/** + * @brief set gpio input to a signal, one gpio can input to several signals. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * gpio == 0x3C, input 0 to signal + * gpio == 0x3A, input nothing to signal + * gpio == 0x38, input 1 to signal + * + * @param uint32_t signal_idx : signal index. + * + * @param bool inv : the signal is inv or not + * + * @return None + */ +void gpio_matrix_in(uint32_t gpio, uint32_t signal_idx, bool inv); + +/** + * @brief set signal output to gpio, one signal can output to several gpios. + * + * @param uint32_t gpio : gpio number, 0~0x2f + * + * @param uint32_t signal_idx : signal index. + * signal_idx == 0x100, cancel output put to the gpio + * + * @param bool out_inv : the signal output is invert or not + * + * @param bool oen_inv : the signal output enable is invert or not + * + * @return None + */ +void gpio_matrix_out(uint32_t gpio, uint32_t signal_idx, bool out_inv, bool oen_inv); + +/** + * @brief Select pad as a gpio function from IOMUX. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_select_gpio(uint32_t gpio_num); + +/** + * @brief Set pad driver capability. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @param uint32_t drv : 0-3 + * + * @return None + */ +void gpio_pad_set_drv(uint32_t gpio_num, uint32_t drv); + +/** + * @brief Pull up the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pullup(uint32_t gpio_num); + +/** + * @brief Pull down the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_pulldown(uint32_t gpio_num); + +/** + * @brief Unhold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_unhold(uint32_t gpio_num); + +/** + * @brief Hold the pad from gpio number. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_hold(uint32_t gpio_num); + +/** + * @brief enable gpio pad input. + * + * @param uint32_t gpio_num : gpio number, 0~0x2f + * + * @return None + */ +void gpio_pad_input_enable(uint32_t gpio_num); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/hmac.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/hmac.h new file mode 100644 index 00000000..ac7ddf35 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/hmac.h @@ -0,0 +1,59 @@ +// Copyright 2018-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "efuse.h" + +void ets_hmac_enable(void); + +void ets_hmac_disable(void); + +/* Use the "upstream" HMAC key (ETS_EFUSE_KEY_PURPOSE_HMAC_UP) + to digest a message. +*/ +int ets_hmac_calculate_message(ets_efuse_block_t key_block, const void *message, size_t message_len, uint8_t *hmac); + +/* Calculate a downstream HMAC message to temporarily enable JTAG, or + to generate a Digital Signature data decryption key. + + - purpose must be ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE + or ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG + + - key_block must be in range ETS_EFUSE_BLOCK_KEY0 toETS_EFUSE_BLOCK_KEY6. + This efuse block must have the corresponding purpose set in "purpose", or + ETS_EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL. + + The result of this HMAC calculation is only made available "downstream" to the + corresponding hardware module, and cannot be accessed by software. +*/ +int ets_hmac_calculate_downstream(ets_efuse_block_t key_block, ets_efuse_purpose_t purpose); + +/* Invalidate a downstream HMAC value previously calculated by ets_hmac_calculate_downstream(). + * + * - purpose must match a previous call to ets_hmac_calculate_downstream(). + * + * After this function is called, the corresponding internal operation (JTAG or DS) will no longer + * have access to the generated key. + */ +int ets_hmac_invalidate_downstream(ets_efuse_purpose_t purpose); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/libc_stubs.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/libc_stubs.h new file mode 100644 index 00000000..4ad19f61 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/libc_stubs.h @@ -0,0 +1,104 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief ESP32-S3 ROM code contains implementations of some of C library functions. + * Whenever a function in ROM needs to use a syscall, it calls a pointer to the corresponding syscall + * implementation defined in the following struct. + * + * The table itself, by default, is not allocated in RAM. There are two pointers, `syscall_table_ptr_pro` and + * `syscall_table_ptr_app`, which can be set to point to the locations of syscall tables of CPU 0 (aka PRO CPU) + * and CPU 1 (aka APP CPU). Location of these pointers in .bss segment of ROM code is defined in linker script. + * + * So, before using any of the C library functions (except for pure functions and memcpy/memset functions), + * application must allocate syscall table structure for each CPU being used, and populate it with pointers + * to actual implementations of corresponding syscalls. + * + */ +struct syscall_stub_table +{ + struct _reent* (*__getreent)(void); + void* (*_malloc_r)(struct _reent *r, size_t); + void (*_free_r)(struct _reent *r, void*); + void* (*_realloc_r)(struct _reent *r, void*, size_t); + void* (*_calloc_r)(struct _reent *r, size_t, size_t); + void (*_abort)(void); + int (*_system_r)(struct _reent *r, const char*); + int (*_rename_r)(struct _reent *r, const char*, const char*); + clock_t (*_times_r)(struct _reent *r, struct tms *); + int (*_gettimeofday_r) (struct _reent *r, struct timeval *, void *); + void (*_raise_r)(struct _reent *r); + int (*_unlink_r)(struct _reent *r, const char*); + int (*_link_r)(struct _reent *r, const char*, const char*); + int (*_stat_r)(struct _reent *r, const char*, struct stat *); + int (*_fstat_r)(struct _reent *r, int, struct stat *); + void* (*_sbrk_r)(struct _reent *r, ptrdiff_t); + int (*_getpid_r)(struct _reent *r); + int (*_kill_r)(struct _reent *r, int, int); + void (*_exit_r)(struct _reent *r, int); + int (*_close_r)(struct _reent *r, int); + int (*_open_r)(struct _reent *r, const char *, int, int); + int (*_write_r)(struct _reent *r, int, const void *, int); + int (*_lseek_r)(struct _reent *r, int, int, int); + int (*_read_r)(struct _reent *r, int, void *, int); +#ifdef _RETARGETABLE_LOCKING + void (*_retarget_lock_init)(_LOCK_T *lock); + void (*_retarget_lock_init_recursive)(_LOCK_T *lock); + void (*_retarget_lock_close)(_LOCK_T lock); + void (*_retarget_lock_close_recursive)(_LOCK_T lock); + void (*_retarget_lock_acquire)(_LOCK_T lock); + void (*_retarget_lock_acquire_recursive)(_LOCK_T lock); + int (*_retarget_lock_try_acquire)(_LOCK_T lock); + int (*_retarget_lock_try_acquire_recursive)(_LOCK_T lock); + void (*_retarget_lock_release)(_LOCK_T lock); + void (*_retarget_lock_release_recursive)(_LOCK_T lock); +#else + void (*_lock_init)(_lock_t *lock); + void (*_lock_init_recursive)(_lock_t *lock); + void (*_lock_close)(_lock_t *lock); + void (*_lock_close_recursive)(_lock_t *lock); + void (*_lock_acquire)(_lock_t *lock); + void (*_lock_acquire_recursive)(_lock_t *lock); + int (*_lock_try_acquire)(_lock_t *lock); + int (*_lock_try_acquire_recursive)(_lock_t *lock); + void (*_lock_release)(_lock_t *lock); + void (*_lock_release_recursive)(_lock_t *lock); +#endif + int (*_printf_float)(struct _reent *data, void *pdata, FILE * fp, int (*pfunc) (struct _reent *, FILE *, const char *, size_t len), va_list * ap); + int (*_scanf_float) (struct _reent *rptr, void *pdata, FILE *fp, va_list *ap); + void (*__assert_func) (const char *file, int line, const char * func, const char *failedexpr) __attribute__((noreturn)); + void (*__sinit) (struct _reent *r); + void (*_cleanup_r) (struct _reent* r); +}; + +extern struct syscall_stub_table *syscall_table_ptr; +#define syscall_table_ptr_pro syscall_table_ptr +#define syscall_table_ptr_app syscall_table_ptr + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/lldesc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/lldesc.h new file mode 100644 index 00000000..ebd02016 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/lldesc.h @@ -0,0 +1,173 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include +#include "sys/queue.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LLDESC_TX_MBLK_SIZE 268 /* */ +#define LLDESC_RX_SMBLK_SIZE 64 /* small block size, for small mgmt frame */ +#define LLDESC_RX_MBLK_SIZE 524 /* rx is large sinec we want to contain mgmt frame in one block*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_SIZE 64 /* it is a small buffer which is a cycle link*/ +#define LLDESC_RX_AMPDU_LEN_MBLK_SIZE 256 /*for ampdu entry*/ +#ifdef ESP_MAC_5 +#define LLDESC_TX_MBLK_NUM 116 /* 64K / 256 */ +#define LLDESC_RX_MBLK_NUM 82 /* 64K / 512 MAX 172*/ +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 12 +#else +#ifdef SBUF_RXTX +#define LLDESC_TX_MBLK_NUM_MAX (2 * 48) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MAX (2 * 48) /* 23K / 524 */ +#define LLDESC_TX_MBLK_NUM_MIN (2 * 16) /* 23K / 260 - 8 */ +#define LLDESC_RX_MBLK_NUM_MIN (2 * 16) /* 23K / 524 */ +#endif +#define LLDESC_TX_MBLK_NUM 10 //(2 * 32) /* 23K / 260 - 8 */ + +#ifdef IEEE80211_RX_AMPDU +#define LLDESC_RX_MBLK_NUM 30 +#else +#define LLDESC_RX_MBLK_NUM 10 +#endif /*IEEE80211_RX_AMPDU*/ + +#define LLDESC_RX_AMPDU_ENTRY_MBLK_NUM 4 +#define LLDESC_RX_AMPDU_LEN_MLBK_NUM 8 +#endif /* !ESP_MAC_5 */ +/* + * SLC2 DMA Desc struct, aka lldesc_t + * + * -------------------------------------------------------------- + * | own | EoF | sub_sof | 5'b0 | length [11:0] | size [11:0] | + * -------------------------------------------------------------- + * | buf_ptr [31:0] | + * -------------------------------------------------------------- + * | next_desc_ptr [31:0] | + * -------------------------------------------------------------- + */ + +/* this bitfield is start from the LSB!!! */ +typedef struct lldesc_s { + volatile uint32_t size : 12, + length: 12, + offset: 5, /* h/w reserved 5bit, s/w use it as offset in buffer */ + sosf : 1, /* start of sub-frame */ + eof : 1, /* end of frame */ + owner : 1; /* hw or sw */ + volatile uint8_t *buf; /* point to buffer data */ + union { + volatile uint32_t empty; + STAILQ_ENTRY(lldesc_s) qe; /* pointing to the next desc */ + }; +} lldesc_t; + +typedef struct tx_ampdu_entry_s { + uint32_t sub_len : 12, + dili_num : 7, + : 1, + null_byte: 2, + data : 1, + enc : 1, + seq : 8; +} tx_ampdu_entry_t; + +typedef struct lldesc_chain_s { + lldesc_t *head; + lldesc_t *tail; +} lldesc_chain_t; + +#ifdef SBUF_RXTX +enum sbuf_mask_s { + SBUF_MOVE_NO = 0, + SBUF_MOVE_TX2RX, + SBUF_MOVE_RX2TX, +} ; + +#define SBUF_MOVE_STEP 8 +#endif +#define LLDESC_SIZE sizeof(struct lldesc_s) + +/* SLC Descriptor */ +#define LLDESC_OWNER_MASK 0x80000000 +#define LLDESC_OWNER_SHIFT 31 +#define LLDESC_SW_OWNED 0 +#define LLDESC_HW_OWNED 1 + +#define LLDESC_EOF_MASK 0x40000000 +#define LLDESC_EOF_SHIFT 30 + +#define LLDESC_SOSF_MASK 0x20000000 +#define LLDESC_SOSF_SHIFT 29 + +#define LLDESC_LENGTH_MASK 0x00fff000 +#define LLDESC_LENGTH_SHIFT 12 + +#define LLDESC_SIZE_MASK 0x00000fff +#define LLDESC_SIZE_SHIFT 0 + +#define LLDESC_ADDR_MASK 0x000fffff + +void lldesc_build_chain(uint8_t *descptr, uint32_t desclen, uint8_t *mblkptr, uint32_t buflen, uint32_t blksz, uint8_t owner, + lldesc_t **head, +#ifdef TO_HOST_RESTART + lldesc_t **one_before_tail, +#endif + lldesc_t **tail); + +lldesc_t *lldesc_num2link(lldesc_t *head, uint16_t nblks); + +lldesc_t *lldesc_set_owner(lldesc_t *head, uint16_t nblks, uint8_t owner); + +static inline uint32_t lldesc_get_chain_length(lldesc_t *head) +{ + lldesc_t *ds = head; + uint32_t len = 0; + + while (ds) { + len += ds->length; + ds = STAILQ_NEXT(ds, qe); + } + + return len; +} + +static inline void lldesc_config(lldesc_t *ds, uint8_t owner, uint8_t eof, uint8_t sosf, uint16_t len) +{ + ds->owner = owner; + ds->eof = eof; + ds->sosf = sosf; + ds->length = len; +} + +#define LLDESC_CONFIG(_desc, _owner, _eof, _sosf, _len) \ + do { \ + (_desc)->owner = (_owner); \ + (_desc)->eof = (_eof); \ + (_desc)->sosf = (_sosf); \ + (_desc)->length = (_len); \ + } while(0) + +#define LLDESC_FROM_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#define LLDESC_MAC_RX_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, (ds)->size) + +#define LLDESC_TO_HOST_CLEANUP(ds) LLDESC_CONFIG((ds), LLDESC_HW_OWNED, 0, 0, 0) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/md5_hash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/md5_hash.h new file mode 100644 index 00000000..8676ace2 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/md5_hash.h @@ -0,0 +1,35 @@ +/* + * MD5 internal definitions + * Copyright (c) 2003-2005, Jouni Malinen + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +}; + +void MD5Init(struct MD5Context *context); +void MD5Update(struct MD5Context *context, unsigned char const *buf, unsigned len); +void MD5Final(unsigned char digest[16], struct MD5Context *context); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/miniz.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/miniz.h new file mode 100644 index 00000000..75535113 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/miniz.h @@ -0,0 +1,757 @@ +#pragma once + +#include + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times, and the C run-time funcs that get/set times won't be called. +// The current downside is the times written to your archives will be from 1979. +#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +#define MINIZ_NO_MALLOC + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux +#define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +//Hardcoded options for Xtensa - JD +#define MINIZ_X86_OR_X64_CPU 0 +#define MINIZ_LITTLE_ENDIAN 1 +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0 +#define MINIZ_HAS_64BIT_REGISTERS 0 +#define TINFL_USE_64BIT_BITBUF 0 + + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s { + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef long long mz_int64; +typedef unsigned long long mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum { + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct { + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum { + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct mz_zip_archive_tag { + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum { + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum { + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum { + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum { + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct { + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag { + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 1 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum { + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +// The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). +enum { + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL +// If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum { + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum { + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct { + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/opi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/opi_flash.h new file mode 100644 index 00000000..be7fcb06 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/opi_flash.h @@ -0,0 +1,300 @@ +/* + * copyright (c) Espressif System 2019 + * + */ + +#ifndef _ROM_OPI_FLASH_H_ +#define _ROM_OPI_FLASH_H_ +#include +#include +#include +#include "spi_flash.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + uint16_t cmd; /*!< Command value */ + uint16_t cmdBitLen; /*!< Command byte length*/ + uint32_t *addr; /*!< Point to address value*/ + uint32_t addrBitLen; /*!< Address byte length*/ + uint32_t *txData; /*!< Point to send data buffer*/ + uint32_t txDataBitLen; /*!< Send data byte length.*/ + uint32_t *rxData; /*!< Point to recevie data buffer*/ + uint32_t rxDataBitLen; /*!< Recevie Data byte length.*/ + uint32_t dummyBitLen; +} esp_rom_spi_cmd_t; + +#define ESP_ROM_OPIFLASH_MUX_TAKE() +#define ESP_ROM_OPIFLASH_MUX_GIVE() +#define ESP_ROM_OPIFLASH_SEL_CS0 (BIT(0)) +#define ESP_ROM_OPIFLASH_SEL_CS1 (BIT(1)) + +// Definition of MX25UM25645G Octa Flash +// SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 +#define ESP_ROM_SPIFLASH_BP_MASK_ISSI (BIT7 | BIT5 | BIT4 | BIT3 | BIT2) + +#define FLASH_OP_MODE_RDCMD_DOUT 0x3B +#define ESP_ROM_FLASH_SECTOR_SIZE 0x1000 +#define ESP_ROM_FLASH_BLOCK_SIZE_64K 0x10000 +#define ESP_ROM_FLASH_PAGE_SIZE 256 + +// FLASH commands +#define ROM_FLASH_CMD_RDID 0x9F +#define ROM_FLASH_CMD_WRSR 0x01 +#define ROM_FLASH_CMD_WRSR2 0x31 /* Not all SPI flash uses this command */ +#define ROM_FLASH_CMD_WREN 0x06 +#define ROM_FLASH_CMD_WRDI 0x04 +#define ROM_FLASH_CMD_RDSR 0x05 +#define ROM_FLASH_CMD_RDSR2 0x35 /* Not all SPI flash uses this command */ +#define ROM_FLASH_CMD_ERASE_SEC 0x20 +#define ROM_FLASH_CMD_ERASE_BLK_32K 0x52 +#define ROM_FLASH_CMD_ERASE_BLK_64K 0xD8 +#define ROM_FLASH_CMD_OTPEN 0x3A /* Enable OTP mode, not all SPI flash uses this command */ +#define ROM_FLASH_CMD_RSTEN 0x66 +#define ROM_FLASH_CMD_RST 0x99 + +#define ROM_FLASH_CMD_SE4B 0x21 +#define ROM_FLASH_CMD_SE4B_OCT 0xDE21 +#define ROM_FLASH_CMD_BE4B 0xDC +#define ROM_FLASH_CMD_BE4B_OCT 0x23DC +#define ROM_FLASH_CMD_RSTEN_OCT 0x9966 +#define ROM_FLASH_CMD_RST_OCT 0x6699 + +#define ROM_FLASH_CMD_FSTRD4B_STR 0x13EC +#define ROM_FLASH_CMD_FSTRD4B_DTR 0x11EE +#define ROM_FLASH_CMD_FSTRD4B 0x0C +#define ROM_FLASH_CMD_PP4B 0x12 +#define ROM_FLASH_CMD_PP4B_OCT 0xED12 + +#define ROM_FLASH_CMD_RDID_OCT 0x609F +#define ROM_FLASH_CMD_WREN_OCT 0xF906 +#define ROM_FLASH_CMD_RDSR_OCT 0xFA05 +#define ROM_FLASH_CMD_RDCR2 0x71 +#define ROM_FLASH_CMD_RDCR2_OCT 0x8E71 +#define ROM_FLASH_CMD_WRCR2 0x72 +#define ROM_FLASH_CMD_WRCR2_OCT 0x8D72 + +// Definitions for GigaDevice GD25LX256E Flash +#define ROM_FLASH_CMD_RDFSR_GD 0x70 +#define ROM_FLASH_CMD_RD_GD 0x03 +#define ROM_FLASH_CMD_RD4B_GD 0x13 +#define ROM_FLASH_CMD_FSTRD_GD 0x0B +#define ROM_FLASH_CMD_FSTRD4B_GD 0x0C +#define ROM_FLASH_CMD_FSTRD_OOUT_GD 0x8B +#define ROM_FLASH_CMD_FSTRD4B_OOUT_GD 0x7C +#define ROM_FLASH_CMD_FSTRD_OIOSTR_GD 0xCB +#define ROM_FLASH_CMD_FSTRD4B_OIOSTR_GD 0xCC +#define ROM_FLASH_CMD_FSTRD4B_OIODTR_GD 0xFD + +#define ROM_FLASH_CMD_PP_GD 0x02 +#define ROM_FLASH_CMD_PP4B_GD 0x12 +#define ROM_FLASH_CMD_PP_OOUT_GD 0x82 +#define ROM_FLASH_CMD_PP4B_OOUT_GD 0x84 +#define ROM_FLASH_CMD_PP_OIO_GD 0xC2 +#define ROM_FLASH_CMD_PP4B_OIOSTR_GD 0x8E + +#define ROM_FLASH_CMD_SE_GD 0x20 +#define ROM_FLASH_CMD_SE4B_GD 0x21 +#define ROM_FLASH_CMD_BE32K_GD 0x52 +#define ROM_FLASH_CMD_BE32K4B_GD 0x5C +#define ROM_FLASH_CMD_BE64K_GD 0xD8 +#define ROM_FLASH_CMD_BE64K4B_GD 0xDC + +#define ROM_FLASH_CMD_EN4B_GD 0xB7 +#define ROM_FLASH_CMD_DIS4B_GD 0xE9 + +// spi user mode command config + +/** + * @brief Config the spi user command + * @param spi_num spi port + * @param pcmd pointer to accept the spi command struct + */ +void esp_rom_spi_cmd_config(int spi_num, esp_rom_spi_cmd_t* pcmd); + +/** + * @brief Start a spi user command sequence + * @param spi_num spi port + * @param rx_buf buffer pointer to receive data + * @param rx_len receive data length in byte + * @param cs_en_mask decide which cs to use, 0 for cs0, 1 for cs1 + * @param is_write_erase to indicate whether this is a write or erase operation, since the CPU would check permission + */ +void esp_rom_spi_cmd_start(int spi_num, uint8_t* rx_buf, uint16_t rx_len, uint8_t cs_en_mask, bool is_write_erase); + +/** + * @brief Config opi flash pads according to efuse settings. + */ +void esp_rom_opiflash_pin_config(void); + +// set SPI read/write mode +/** + * @brief Set SPI operation mode + * @param spi_num spi port + * @param mode Flash Read Mode + */ +void esp_rom_spi_set_op_mode(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Set data swap mode in DTR(DDR) mode + * @param spi_num spi port + * @param wr_swap to decide whether to swap fifo data in dtr write operation + * @param rd_swap to decide whether to swap fifo data in dtr read operation + */ +void esp_rom_spi_set_dtr_swap_mode(int spi, bool wr_swap, bool rd_swap); + + +/** + * @brief to send reset command in spi/opi-str/opi-dtr mode(for MX25UM25645G) + * @param spi_num spi port + */ +void esp_rom_opiflash_mode_reset(int spi_num); + +#if 0 +// MX25UM25645G opi flash interface +/** + * @brief To execute a flash operation command + * @param spi_num spi port + * @param mode Flash Read Mode + * @param cmd data to send in command field + * @param cmd_bit_len bit length of command field + * @param addr data to send in address field + * @param addr_bit_len bit length of address field + * @param dummy_bits bit length of dummy field + * @param mosi_data data buffer to be sent in mosi field + * @param mosi_bit_len bit length of data buffer to be sent in mosi field + * @param miso_data data buffer to accept data in miso field + * @param miso_bit_len bit length of data buffer to accept data in miso field + * @param cs_mark decide which cs pin to use. 0: cs0, 1: cs1 + * @param is_write_erase_operation to indicate whether this a write or erase flash operation + */ +void esp_rom_opiflash_exec_cmd(int spi_num, esp_rom_spiflash_read_mode_t mode, + uint32_t cmd, int cmd_bit_len, + uint32_t addr, int addr_bit_len, + int dummy_bits, + uint8_t* mosi_data, int mosi_bit_len, + uint8_t* miso_data, int miso_bit_len, + uint32_t cs_mask, + bool is_write_erase_operation); + +/** + * @brief send reset command to opi flash + * @param spi_num spi port + * @param mode Flash Operation Mode + */ +void esp_rom_opiflash_soft_reset(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read opi flash ID(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @return opi flash id + */ +uint32_t esp_rom_opiflash_read_id(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read opi flash status register(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @return opi flash status value + */ +uint8_t esp_rom_opiflash_rdsr(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief wait opi flash status register to be idle + * @param spi_num spi port + * @param mode Flash Operation Mode + */ +void esp_rom_opiflash_wait_idle(int spi_num, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read the config register2(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @param addr the address of configure register + * @return value of config register2 + */ +uint8_t esp_rom_opiflash_rdcr2(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t addr); + +/** + * @brief to write the config register2(for MX25UM25645G) + * @param spi_num spi port + * @param mode Flash Operation Mode + * @param addr the address of config register + * @param val the value to write + */ +void esp_rom_opiflash_wrcr2(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t addr, uint8_t val); + +/** + * @brief to erase flash sector(for MX25UM25645G) + * @param spi_num spi port + * @param address the sector address to be erased + * @param mode Flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_sector(int spi_num, uint32_t address, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to erase flash block(for MX25UM25645G) + * @param spi_num spi port + * @param address the block address to be erased + * @param mode Flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_block_64k(int spi_num, uint32_t address, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to erase a flash area define by start address and length(for MX25UM25645G) + * @param spi_num spi port + * @param start_addr the start address to be erased + * @param area_len the erea length to be erased + * @param mode flash operation mode + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_erase_area(int spi_num, uint32_t start_addr, uint32_t area_len, esp_rom_spiflash_read_mode_t mode); + +/** + * @brief to read data from opi flash(for MX25UM25645G) + * @param spi_num spi port + * @param mode flash operation mode + * @param flash_addr flash address to read data from + * @param data_addr data buffer to accept the data + * @param len data length to be read + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_read(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t flash_addr, uint8_t *data_addr, int len); + +/** + * @brief to write data to opi flash(for MX25UM25645G) + * @param spi_num spi port + * @param mode flash operation mode + * @param flash_addr flash address to write data to + * @param data_addr data buffer to write to flash + * @param len data length to write + * @return flash operation result + */ +esp_rom_spiflash_result_t esp_rom_opiflash_write(int spi_num, esp_rom_spiflash_read_mode_t mode, uint32_t flash_addr, uint8_t *data_addr, uint32_t len); + +/** + * @brief to set opi flash operation mode(for MX25UM25645G) + * @param spi_num spi port + * @param cur_mode current operation mode + * @param target the target operation mode to be set + */ +void esp_rom_opiflash_set_mode(int spi_num, esp_rom_spiflash_read_mode_t cur_mode, esp_rom_spiflash_read_mode_t target_mode); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rom_layout.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rom_layout.h new file mode 100644 index 00000000..289fbd60 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rom_layout.h @@ -0,0 +1,84 @@ +// Copyright 2020 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. + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define SUPPORT_WIFI 1 +#define SUPPORT_BTDM 1 +/* Structure and functions for returning ROM global layout + * + * This is for address symbols defined in the linker script, which may change during ECOs. + */ +typedef struct { + void *dram0_stack_shared_mem_start; + void *dram0_rtos_reserved_start; + void *stack_sentry; + void *stack; + void *stack_sentry_app; + void *stack_app; + + /* BTDM data */ + void *data_start_btdm; + void *data_end_btdm; + void *bss_start_btdm; + void *bss_end_btdm; + void *data_start_btdm_rom; + void *data_end_btdm_rom; + void *data_start_interface_btdm; + void *data_end_interface_btdm; + void *bss_start_interface_btdm; + void *bss_end_interface_btdm; + + /* Other DRAM ranges */ +#if SUPPORT_BTDM || SUPPORT_WIFI + void *dram_start_phyrom; + void *dram_end_phyrom; +#endif +#if SUPPORT_WIFI + void *dram_start_coexist; + void *dram_end_coexist; + void *dram_start_net80211; + void *dram_end_net80211; + void *dram_start_pp; + void *dram_end_pp; + void *data_start_interface_coexist; + void *data_end_interface_coexist; + void *bss_start_interface_coexist; + void *bss_end_interface_coexist; + void *data_start_interface_net80211; + void *data_end_interface_net80211; + void *bss_start_interface_net80211; + void *bss_end_interface_net80211; + void *data_start_interface_pp; + void *data_end_interface_pp; + void *bss_start_interface_pp; + void *bss_end_interface_pp; +#endif + void *dram_start_usbdev_rom; + void *dram_end_usbdev_rom; + void *dram_start_uart_rom; + void *dram_end_uart_rom; + +} ets_rom_layout_t; + +extern const ets_rom_layout_t * const ets_rom_layout_p; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rsa_pss.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rsa_pss.h new file mode 100644 index 00000000..b9ced67a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rsa_pss.h @@ -0,0 +1,43 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ETS_SIG_LEN 384 /* Bytes */ +#define ETS_DIGEST_LEN 32 /* SHA-256, bytes */ + +typedef struct { + uint8_t n[384]; /* Public key modulus */ + uint32_t e; /* Public key exponent */ + uint8_t rinv[384]; + uint32_t mdash; +} ets_rsa_pubkey_t; + +bool ets_rsa_pss_verify(const ets_rsa_pubkey_t *key, const uint8_t *sig, const uint8_t *digest); + +void ets_mgf1_sha256(const uint8_t *mgfSeed, size_t seedLen, size_t maskLen, uint8_t *mask); + +bool ets_emsa_pss_verify(const uint8_t *encoded_message, const uint8_t *mhash); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rtc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rtc.h new file mode 100644 index 00000000..b8ff8519 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/rtc.h @@ -0,0 +1,231 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include +#include +#include "soc/rtc_cntl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup rtc_apis, rtc registers and memory related apis + * @brief rtc apis + */ + +/** @addtogroup rtc_apis + * @{ + */ + +/************************************************************************************** + * Note: * + * Some Rtc memory and registers are used, in ROM or in internal library. * + * Please do not use reserved or used rtc memory or registers. * + * * + ************************************************************************************* + * RTC Memory & Store Register usage + ************************************************************************************* + * rtc memory addr type size usage + * 0x3f421000(0x50000000) Slow SIZE_CP Co-Processor code/Reset Entry + * 0x3f421000+SIZE_CP Slow 8192-SIZE_CP + * + * 0x3ff80000(0x40070000) Fast 8192 deep sleep entry code + * + ************************************************************************************* + * RTC store registers usage + * RTC_CNTL_STORE0_REG Reserved + * RTC_CNTL_STORE1_REG RTC_SLOW_CLK calibration value + * RTC_CNTL_STORE2_REG Boot time, low word + * RTC_CNTL_STORE3_REG Boot time, high word + * RTC_CNTL_STORE4_REG External XTAL frequency + * RTC_CNTL_STORE5_REG APB bus frequency + * RTC_CNTL_STORE6_REG FAST_RTC_MEMORY_ENTRY + * RTC_CNTL_STORE7_REG FAST_RTC_MEMORY_CRC + ************************************************************************************* + */ + +#define RTC_SLOW_CLK_CAL_REG RTC_CNTL_STORE1_REG +#define RTC_BOOT_TIME_LOW_REG RTC_CNTL_STORE2_REG +#define RTC_BOOT_TIME_HIGH_REG RTC_CNTL_STORE3_REG +#define RTC_XTAL_FREQ_REG RTC_CNTL_STORE4_REG +#define RTC_APB_FREQ_REG RTC_CNTL_STORE5_REG +#define RTC_ENTRY_ADDR_REG RTC_CNTL_STORE6_REG +#define RTC_MEMORY_CRC_REG RTC_CNTL_STORE7_REG + +#define RTC_DISABLE_ROM_LOG ((1 << 0) | (1 << 16)) //!< Disable logging from the ROM code. + +typedef enum { + AWAKE = 0, // +#include +#include "ets_sys.h" +#include "rsa_pss.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct ets_secure_boot_sig_block; +struct ets_secure_boot_signature_t; + +typedef struct ets_secure_boot_sig_block ets_secure_boot_sig_block_t; +typedef struct ets_secure_boot_signature ets_secure_boot_signature_t; +typedef struct ets_secure_boot_key_digests ets_secure_boot_key_digests_t; + +/* Anti-FI measure: use full words for success/fail, instead of + 0/non-zero +*/ +typedef enum { + SB_SUCCESS = 0x3A5A5AA5, + SB_FAILED = 0x7533885E, +} secure_boot_status_t; + +/* Verify bootloader image (reconfigures cache to map, + loads trusted key digests from efuse) + + If allow_key_revoke is true and aggressive revoke efuse is set, + any failed signature has its associated key revoked in efuse. + + If result is ETS_OK, the "simple hash" of the bootloader + is copied into verified_hash. +*/ +int ets_secure_boot_verify_bootloader(uint8_t *verified_hash, bool allow_key_revoke); + +/* Verify bootloader image (reconfigures cache to map), with + key digests provided as parameters.) + + Can be used to verify secure boot status before enabling + secure boot permanently. + + If result is ETS_OK, the "simple hash" of the bootloader is + copied into verified_hash. +*/ +secure_boot_status_t ets_secure_boot_verify_bootloader_with_keys(uint8_t *verified_hash, const ets_secure_boot_key_digests_t *trusted_keys, bool stage_load); + +/* Verify supplied signature against supplied digest, using + supplied trusted key digests. + + Doesn't reconfigure cache or any other hardware access. +*/ +secure_boot_status_t ets_secure_boot_verify_signature(const ets_secure_boot_signature_t *sig, const uint8_t *image_digest, const ets_secure_boot_key_digests_t *trusted_keys, uint8_t *verified_digest); + +/* Read key digests from efuse. Any revoked/missing digests will be + marked as NULL + + Returns 0 if at least one valid digest was found. +*/ +ETS_STATUS ets_secure_boot_read_key_digests(ets_secure_boot_key_digests_t *trusted_keys); + +#define CRC_SIGN_BLOCK_LEN 1196 +#define SIG_BLOCK_PADDING 4096 +#define ETS_SECURE_BOOT_V2_SIGNATURE_MAGIC 0xE7 + +/* Secure Boot V2 signature block (up to 3 can be appended) */ +struct ets_secure_boot_sig_block { + uint8_t magic_byte; + uint8_t version; + uint8_t _reserved1; + uint8_t _reserved2; + uint8_t image_digest[32]; + ets_rsa_pubkey_t key; + uint8_t signature[384]; + uint32_t block_crc; + uint8_t _padding[16]; +}; + +_Static_assert(sizeof(ets_secure_boot_sig_block_t) == 1216, "ets_secure_boot_sig_block_t should occupy 1216 Bytes in memory"); + +#define SECURE_BOOT_NUM_BLOCKS 3 + +/* V2 Secure boot signature sector (up to 3 blocks) */ +struct ets_secure_boot_signature { + ets_secure_boot_sig_block_t block[SECURE_BOOT_NUM_BLOCKS]; + uint8_t _padding[4096 - (sizeof(ets_secure_boot_sig_block_t) * SECURE_BOOT_NUM_BLOCKS)]; +}; + +_Static_assert(sizeof(ets_secure_boot_signature_t) == 4096, "ets_secure_boot_signature_t should occupy 4096 Bytes in memory"); + +#define MAX_KEY_DIGESTS 3 + +struct ets_secure_boot_key_digests { + const void *key_digests[MAX_KEY_DIGESTS]; + bool allow_key_revoke; +}; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/sha.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/sha.h new file mode 100644 index 00000000..4d8fe901 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/sha.h @@ -0,0 +1,63 @@ +// Copyright 2015-2020 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. +#pragma once + +#include +#include +#include "ets_sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SHA1 = 0, + SHA2_224, + SHA2_256, + SHA2_384, + SHA2_512, + SHA2_512224, + SHA2_512256, + SHA2_512T, + SHA_TYPE_MAX +} SHA_TYPE; + +typedef struct SHAContext { + bool start; + bool in_hardware; // Is this context currently in peripheral? Needs to be manually cleared if multiple SHAs are interleaved + SHA_TYPE type; + uint32_t state[16]; // For SHA1/SHA224/SHA256, used 8, other used 16 + unsigned char buffer[128]; // For SHA1/SHA224/SHA256, used 64, other used 128 + uint32_t total_bits[4]; +} SHA_CTX; + +void ets_sha_enable(void); + +void ets_sha_disable(void); + +ets_status_t ets_sha_init(SHA_CTX *ctx, SHA_TYPE type); + +ets_status_t ets_sha_starts(SHA_CTX *ctx, uint16_t sha512_t); + +void ets_sha_get_state(SHA_CTX *ctx); + +void ets_sha_process(SHA_CTX *ctx, const unsigned char *input); + +void ets_sha_update(SHA_CTX *ctx, const unsigned char *input, uint32_t input_bytes, bool update_ctx); + +ets_status_t ets_sha_finish(SHA_CTX *ctx, unsigned char *output); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/spi_flash.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/spi_flash.h new file mode 100644 index 00000000..3e71bb6f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/spi_flash.h @@ -0,0 +1,591 @@ +// Copyright 2010-2020 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. + +#pragma once +#include +#include +#include "esp_attr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup spi_flash_apis, spi flash operation related apis + * @brief spi_flash apis + */ + +/** @addtogroup spi_flash_apis + * @{ + */ + +/************************************************************* + * Note + ************************************************************* + * 1. ESP32 chip have 4 SPI slave/master, however, SPI0 is + * used as an SPI master to access Flash and ext-SRAM by + * Cache module. It will support Decryto read for Flash, + * read/write for ext-SRAM. And SPI1 is also used as an + * SPI master for Flash read/write and ext-SRAM read/write. + * It will support Encrypto write for Flash. + * 2. As an SPI master, SPI support Highest clock to 80M, + * however, Flash with 80M Clock should be configured + * for different Flash chips. If you want to use 80M + * clock We should use the SPI that is certified by + * Espressif. However, the certification is not started + * at the time, so please use 40M clock at the moment. + * 3. SPI Flash can use 2 lines or 4 lines mode. If you + * use 2 lines mode, you can save two pad SPIHD and + * SPIWP for gpio. ESP32 support configured SPI pad for + * Flash, the configuration is stored in efuse and flash. + * However, the configurations of pads should be certified + * by Espressif. If you use this function, please use 40M + * clock at the moment. + * 4. ESP32 support to use Common SPI command to configure + * Flash to QIO mode, if you failed to configure with fix + * command. With Common SPI Command, ESP32 can also provide + * a way to use same Common SPI command groups on different + * Flash chips. + * 5. This functions are not protected by packeting, Please use the + ************************************************************* + */ + +#define PERIPHS_SPI_FLASH_CMD SPI_MEM_CMD_REG(1) +#define PERIPHS_SPI_FLASH_ADDR SPI_MEM_ADDR_REG(1) +#define PERIPHS_SPI_FLASH_CTRL SPI_MEM_CTRL_REG(1) +#define PERIPHS_SPI_FLASH_CTRL1 SPI_MEM_CTRL1_REG(1) +#define PERIPHS_SPI_FLASH_STATUS SPI_MEM_RD_STATUS_REG(1) +#define PERIPHS_SPI_FLASH_USRREG SPI_MEM_USER_REG(1) +#define PERIPHS_SPI_FLASH_USRREG1 SPI_MEM_USER1_REG(1) +#define PERIPHS_SPI_FLASH_USRREG2 SPI_MEM_USER2_REG(1) +#define PERIPHS_SPI_FLASH_C0 SPI_MEM_W0_REG(1) +#define PERIPHS_SPI_FLASH_C1 SPI_MEM_W1_REG(1) +#define PERIPHS_SPI_FLASH_C2 SPI_MEM_W2_REG(1) +#define PERIPHS_SPI_FLASH_C3 SPI_MEM_W3_REG(1) +#define PERIPHS_SPI_FLASH_C4 SPI_MEM_W4_REG(1) +#define PERIPHS_SPI_FLASH_C5 SPI_MEM_W5_REG(1) +#define PERIPHS_SPI_FLASH_C6 SPI_MEM_W6_REG(1) +#define PERIPHS_SPI_FLASH_C7 SPI_MEM_W7_REG(1) +#define PERIPHS_SPI_FLASH_TX_CRC SPI_MEM_TX_CRC_REG(1) + +#define SPI0_R_QIO_DUMMY_CYCLELEN 5 +#define SPI0_R_QIO_ADDR_BITSLEN 23 +#define SPI0_R_FAST_DUMMY_CYCLELEN 7 +#define SPI0_R_DIO_DUMMY_CYCLELEN 3 +#define SPI0_R_FAST_ADDR_BITSLEN 23 +#define SPI0_R_SIO_ADDR_BITSLEN 23 + +#define SPI1_R_QIO_DUMMY_CYCLELEN 5 +#define SPI1_R_QIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_DUMMY_CYCLELEN 7 +#define SPI1_R_DIO_DUMMY_CYCLELEN 3 +#define SPI1_R_DIO_ADDR_BITSLEN 23 +#define SPI1_R_FAST_ADDR_BITSLEN 23 +#define SPI1_R_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_W_SIO_ADDR_BITSLEN 23 + +#define ESP_ROM_SPIFLASH_TWO_BYTE_STATUS_EN SPI_MEM_WRSR_2B + +//SPI address register +#define ESP_ROM_SPIFLASH_BYTES_LEN 24 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_WRITE_NUM 32 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_NUM 16 +#define ESP_ROM_SPIFLASH_BUFF_BYTE_READ_BITS 0xf + +//SPI status register +#define ESP_ROM_SPIFLASH_BUSY_FLAG BIT0 +#define ESP_ROM_SPIFLASH_WRENABLE_FLAG BIT1 +#define ESP_ROM_SPIFLASH_BP0 BIT2 +#define ESP_ROM_SPIFLASH_BP1 BIT3 +#define ESP_ROM_SPIFLASH_BP2 BIT4 +#define ESP_ROM_SPIFLASH_WR_PROTECT (ESP_ROM_SPIFLASH_BP0|ESP_ROM_SPIFLASH_BP1|ESP_ROM_SPIFLASH_BP2) +#define ESP_ROM_SPIFLASH_QE BIT9 +#define ESP_ROM_SPIFLASH_BP_MASK_ISSI (BIT7 | BIT5 | BIT4 | BIT3 | BIT2) + +#define FLASH_ID_GD25LQ32C 0xC86016 + +typedef enum { + ESP_ROM_SPIFLASH_QIO_MODE = 0, + ESP_ROM_SPIFLASH_QOUT_MODE, + ESP_ROM_SPIFLASH_DIO_MODE, + ESP_ROM_SPIFLASH_DOUT_MODE, + ESP_ROM_SPIFLASH_FASTRD_MODE, + ESP_ROM_SPIFLASH_SLOWRD_MODE +} esp_rom_spiflash_read_mode_t; + +typedef enum { + ESP_ROM_SPIFLASH_RESULT_OK, + ESP_ROM_SPIFLASH_RESULT_ERR, + ESP_ROM_SPIFLASH_RESULT_TIMEOUT +} esp_rom_spiflash_result_t; + +typedef struct { + uint32_t device_id; + uint32_t chip_size; // chip size in bytes + uint32_t block_size; + uint32_t sector_size; + uint32_t page_size; + uint32_t status_mask; +} esp_rom_spiflash_chip_t; + +typedef struct { + uint8_t data_length; + uint8_t read_cmd0; + uint8_t read_cmd1; + uint8_t write_cmd; + uint16_t data_mask; + uint16_t data; +} esp_rom_spiflash_common_cmd_t; + + +/** + * @brief Fix the bug in SPI hardware communication with Flash/Ext-SRAM in High Speed. + * Please do not call this function in SDK. + * + * @param uint8_t spi: 0 for SPI0(Cache Access), 1 for SPI1(Flash read/write). + * + * @param uint8_t freqdiv: Pll is 80M, 4 for 20M, 3 for 26.7M, 2 for 40M, 1 for 80M. + * + * @return None + */ +void esp_rom_spiflash_fix_dummylen(uint8_t spi, uint8_t freqdiv); + +/** + * @brief Select SPI Flash to QIO mode when WP pad is read from Flash. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_qiomode(uint8_t wp_gpio_num, uint32_t ishspi); + +/** + * @brief Set SPI Flash pad drivers. + * Please do not call this function in SDK. + * + * @param uint8_t wp_gpio_num: WP gpio number. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t *drvs: drvs[0]-bit[3:0] for cpiclk, bit[7:4] for spiq, drvs[1]-bit[3:0] for spid, drvs[1]-bit[7:4] for spid + * drvs[2]-bit[3:0] for spihd, drvs[2]-bit[7:4] for spiwp. + * Values usually read from falsh by rom code, function usually callde by rom code. + * if value with bit(3) set, the value is valid, bit[2:0] is the real value. + * + * @return None + */ +void esp_rom_spiflash_set_drvs(uint8_t wp_gpio_num, uint32_t ishspi, uint8_t *drvs); + +/** + * @brief Select SPI Flash function for pads. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @return None + */ +void esp_rom_spiflash_select_padsfunc(uint32_t ishspi); + +/** + * @brief SPI Flash init, clock divisor is 4, use 1 line Slow read mode. + * Please do not call this function in SDK. + * + * @param uint32_t ishspi: 0 for spi, 1 for hspi, flash pad decided by strapping + * else, bit[5:0] spiclk, bit[11:6] spiq, bit[17:12] spid, bit[23:18] spics0, bit[29:24] spihd + * + * @param uint8_t legacy: In legacy mode, more SPI command is used in line. + * + * @return None + */ +void esp_rom_spiflash_attach(uint32_t ishspi, bool legacy); + +/** + * @brief SPI Read Flash status register. We use CMD 0x05 (RDSR). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_status(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief SPI Read Flash status register bits 8-15. We use CMD 0x35 (RDSR2). + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t *status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_statushigh(esp_rom_spiflash_chip_t *spi, uint32_t *status); + +/** + * @brief Write status to Falsh status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t status_value : Value to . + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_status(esp_rom_spiflash_chip_t *spi, uint32_t status_value); + +/** + * @brief Use a command to Read Flash status register. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_chip_t *spi : The information for Flash, which is exported from ld file. + * + * @param uint32_t*status : The pointer to which to return the Flash status value. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read_user_cmd(uint32_t *status, uint8_t cmd); + +/** + * @brief Config SPI Flash read mode when init. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_read_mode_t mode : QIO/QOUT/DIO/DOUT/FastRD/SlowRD. + * + * This function does not try to set the QIO Enable bit in the status register, caller is responsible for this. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_readmode(esp_rom_spiflash_read_mode_t mode); + +/** + * @brief Config SPI Flash clock divisor. + * Please do not call this function in SDK. + * + * @param uint8_t freqdiv: clock divisor. + * + * @param uint8_t spi: 0 for SPI0, 1 for SPI1. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : config OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : config error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : config timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_clk(uint8_t freqdiv, uint8_t spi); + +/** + * @brief Send CommonCmd to Flash so that is can go into QIO mode, some Flash use different CMD. + * Please do not call this function in SDK. + * + * @param esp_rom_spiflash_common_cmd_t *cmd : A struct to show the action of a command. + * + * @return uint16_t 0 : do not send command any more. + * 1 : go to the next command. + * n > 1 : skip (n - 1) commands. + */ +uint16_t esp_rom_spiflash_common_cmd(esp_rom_spiflash_common_cmd_t *cmd); + +/** + * @brief Unlock SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Unlock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Unlock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Unlock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_unlock(void); + +/** + * @brief SPI write protect. + * Please do not call this function in SDK. + * + * @param None. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Lock OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Lock error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Lock timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_lock(void); + +/** + * @brief Update SPI Flash parameter. + * Please do not call this function in SDK. + * + * @param uint32_t deviceId : Device ID read from SPI, the low 32 bit. + * + * @param uint32_t chip_size : The Flash size. + * + * @param uint32_t block_size : The Flash block size. + * + * @param uint32_t sector_size : The Flash sector size. + * + * @param uint32_t page_size : The Flash page size. + * + * @param uint32_t status_mask : The Mask used when read status from Flash(use single CMD). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Update OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Update error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Update timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_config_param(uint32_t deviceId, uint32_t chip_size, uint32_t block_size, + uint32_t sector_size, uint32_t page_size, uint32_t status_mask); + +/** + * @brief Erase whole flash chip. + * Please do not call this function in SDK. + * + * @param None + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_chip(void); + +/** + * @brief Erase a 64KB block of flash + * Uses SPI flash command D8H. + * Please do not call this function in SDK. + * + * @param uint32_t block_num : Which block to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_block(uint32_t block_num); + +/** + * @brief Erase a sector of flash. + * Uses SPI flash command 20H. + * Please do not call this function in SDK. + * + * @param uint32_t sector_num : Which sector to erase. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_sector(uint32_t sector_num); + +/** + * @brief Erase some sectors. + * Please do not call this function in SDK. + * + * @param uint32_t start_addr : Start addr to erase, should be sector aligned. + * + * @param uint32_t area_len : Length to erase, should be sector aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Erase OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Erase error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Erase timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_erase_area(uint32_t start_addr, uint32_t area_len); + +/** + * @brief Write Data to Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t dest_addr : Address to write, should be 4 bytes aligned. + * + * @param const uint32_t *src : The pointer to data which is to write. + * + * @param uint32_t len : Length to write, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write(uint32_t dest_addr, const uint32_t *src, int32_t len); + +/** + * @brief Read Data from Flash, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t src_addr : Address to read, should be 4 bytes aligned. + * + * @param uint32_t *dest : The buf to read the data. + * + * @param uint32_t len : Length to read, should be 4 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Read OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Read error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Read timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_read(uint32_t src_addr, uint32_t *dest, int32_t len); + +/** + * @brief SPI1 go into encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_enable(void); + +/** + * @brief Prepare 32 Bytes data to encrpto writing, you should Erase it yourself if need. + * Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 bytes aligned. + * + * @param uint32_t *data : The pointer to data which is to write. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Prepare OK. + * ESP_ROM_SPIFLASH_RESULT_ERR : Prepare error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Prepare timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_prepare_encrypted_data(uint32_t flash_addr, uint32_t *data); + +/** + * @brief SPI1 go out of encrypto mode. + * Please do not call this function in SDK. + * + * @param None + * + * @return None + */ +void esp_rom_spiflash_write_encrypted_disable(void); + +/** + * @brief Write data to flash with transparent encryption. + * @note Sectors to be written should already be erased. + * + * @note Please do not call this function in SDK. + * + * @param uint32_t flash_addr : Address to write, should be 32 byte aligned. + * + * @param uint32_t *data : The pointer to data to write. Note, this pointer must + * be 32 bit aligned and the content of the data will be + * modified by the encryption function. + * + * @param uint32_t len : Length to write, should be 32 bytes aligned. + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Data written successfully. + * ESP_ROM_SPIFLASH_RESULT_ERR : Encryption write error. + * ESP_ROM_SPIFLASH_RESULT_TIMEOUT : Encrypto write timeout. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_encrypted(uint32_t flash_addr, uint32_t *data, uint32_t len); + + +/* TODO: figure out how to map these to their new names */ +typedef enum { + SPI_ENCRYPT_DESTINATION_FLASH, + SPI_ENCRYPT_DESTINATION_PSRAM, +} SpiEncryptDest; + +typedef esp_rom_spiflash_result_t SpiFlashOpResult; + +SpiFlashOpResult SPI_Encrypt_Write(uint32_t flash_addr, const void *data, uint32_t len); +SpiFlashOpResult SPI_Encrypt_Write_Dest(SpiEncryptDest dest, uint32_t flash_addr, const void *data, uint32_t len); +void SPI_Write_Encrypt_Enable(void); +void SPI_Write_Encrypt_Disable(void); + +/** @brief Wait until SPI flash write operation is complete + * + * @note Please do not call this function in SDK. + * + * Reads the Write In Progress bit of the SPI flash status register, + * repeats until this bit is zero (indicating write complete). + * + * @return ESP_ROM_SPIFLASH_RESULT_OK : Write is complete + * ESP_ROM_SPIFLASH_RESULT_ERR : Error while reading status. + */ +esp_rom_spiflash_result_t esp_rom_spiflash_wait_idle(esp_rom_spiflash_chip_t *spi); + + +/** @brief Enable Quad I/O pin functions + * + * @note Please do not call this function in SDK. + * + * Sets the HD & WP pin functions for Quad I/O modes, based on the + * efuse SPI pin configuration. + * + * @param wp_gpio_num - Number of the WP pin to reconfigure for quad I/O. + * + * @param spiconfig - Pin configuration, as returned from ets_efuse_get_spiconfig(). + * - If this parameter is 0, default SPI pins are used and wp_gpio_num parameter is ignored. + * - If this parameter is 1, default HSPI pins are used and wp_gpio_num parameter is ignored. + * - For other values, this parameter encodes the HD pin number and also the CLK pin number. CLK pin selection is used + * to determine if HSPI or SPI peripheral will be used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). + * Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral. + */ +void esp_rom_spiflash_select_qio_pins(uint8_t wp_gpio_num, uint32_t spiconfig); + +/** + * @brief Clear WEL bit unconditionally. + * + * @return always ESP_ROM_SPIFLASH_RESULT_OK + */ +esp_rom_spiflash_result_t esp_rom_spiflash_write_disable(void); + +typedef void (* spi_flash_func_t)(void); +typedef SpiFlashOpResult (* spi_flash_op_t)(void); +typedef SpiFlashOpResult (* spi_flash_erase_t)(uint32_t); +typedef SpiFlashOpResult (* spi_flash_rd_t)(uint32_t, uint32_t*, int); +typedef SpiFlashOpResult (* spi_flash_wr_t)(uint32_t, const uint32_t*, int); +typedef SpiFlashOpResult (* spi_flash_ewr_t)(uint32_t, const void*, uint32_t); +typedef SpiFlashOpResult (* spi_flash_wren_t)(void*); + + +typedef struct { + uint32_t read_sub_len; + uint32_t write_sub_len; + spi_flash_op_t unlock; + spi_flash_erase_t erase_sector; + spi_flash_erase_t erase_block; + spi_flash_rd_t read; + spi_flash_wr_t write; + spi_flash_ewr_t encrypt_write; + spi_flash_func_t check_sus; + spi_flash_wren_t wren; + spi_flash_op_t wait_idle; +} spiflash_legacy_funcs_t; + +/* Defined in the interfaces file, default value is rom_default_spiflash_legacy_flash_func */ +extern const spiflash_legacy_funcs_t *rom_spiflash_legacy_funcs; + +typedef struct { + esp_rom_spiflash_chip_t chip; + uint8_t dummy_len_plus[3]; + uint8_t sig_matrix; +} spiflash_legacy_data_t; + +extern spiflash_legacy_data_t *rom_spiflash_legacy_data; + +#define g_rom_flashchip (rom_spiflash_legacy_data->chip) +#define g_rom_spiflash_dummy_len_plus (rom_spiflash_legacy_data->dummy_len_plus) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/tjpgd.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/tjpgd.h new file mode 100644 index 00000000..40340dea --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/tjpgd.h @@ -0,0 +1,97 @@ +/*----------------------------------------------------------------------------/ +/ TJpgDec - Tiny JPEG Decompressor include file (C)ChaN, 2012 +/----------------------------------------------------------------------------*/ +#ifndef _TJPGDEC +#define _TJPGDEC +/*---------------------------------------------------------------------------*/ +/* System Configurations */ + +#define JD_SZBUF 512 /* Size of stream input buffer */ +#define JD_FORMAT 0 /* Output pixel format 0:RGB888 (3 BYTE/pix), 1:RGB565 (1 WORD/pix) */ +#define JD_USE_SCALE 1 /* Use descaling feature for output */ +#define JD_TBLCLIP 1 /* Use table for saturation (might be a bit faster but increases 1K bytes of code size) */ + +/*---------------------------------------------------------------------------*/ + +#ifdef __cplusplus +extern "C" { +#endif + +/* These types must be 16-bit, 32-bit or larger integer */ +typedef int INT; +typedef unsigned int UINT; + +/* These types must be 8-bit integer */ +typedef char CHAR; +typedef unsigned char UCHAR; +typedef unsigned char BYTE; + +/* These types must be 16-bit integer */ +typedef short SHORT; +typedef unsigned short USHORT; +typedef unsigned short WORD; +typedef unsigned short WCHAR; + +/* These types must be 32-bit integer */ +typedef long LONG; +typedef unsigned long ULONG; +typedef unsigned long DWORD; + + +/* Error code */ +typedef enum { + JDR_OK = 0, /* 0: Succeeded */ + JDR_INTR, /* 1: Interrupted by output function */ + JDR_INP, /* 2: Device error or wrong termination of input stream */ + JDR_MEM1, /* 3: Insufficient memory pool for the image */ + JDR_MEM2, /* 4: Insufficient stream input buffer */ + JDR_PAR, /* 5: Parameter error */ + JDR_FMT1, /* 6: Data format error (may be damaged data) */ + JDR_FMT2, /* 7: Right format but not supported */ + JDR_FMT3 /* 8: Not supported JPEG standard */ +} JRESULT; + + + +/* Rectangular structure */ +typedef struct { + WORD left, right, top, bottom; +} JRECT; + + + +/* Decompressor object structure */ +typedef struct JDEC JDEC; +struct JDEC { + UINT dctr; /* Number of bytes available in the input buffer */ + BYTE *dptr; /* Current data read ptr */ + BYTE *inbuf; /* Bit stream input buffer */ + BYTE dmsk; /* Current bit in the current read byte */ + BYTE scale; /* Output scaling ratio */ + BYTE msx, msy; /* MCU size in unit of block (width, height) */ + BYTE qtid[3]; /* Quantization table ID of each component */ + SHORT dcv[3]; /* Previous DC element of each component */ + WORD nrst; /* Restart inverval */ + UINT width, height; /* Size of the input image (pixel) */ + BYTE *huffbits[2][2]; /* Huffman bit distribution tables [id][dcac] */ + WORD *huffcode[2][2]; /* Huffman code word tables [id][dcac] */ + BYTE *huffdata[2][2]; /* Huffman decoded data tables [id][dcac] */ + LONG *qttbl[4]; /* Dequaitizer tables [id] */ + void *workbuf; /* Working buffer for IDCT and RGB output */ + BYTE *mcubuf; /* Working buffer for the MCU */ + void *pool; /* Pointer to available memory pool */ + UINT sz_pool; /* Size of momory pool (bytes available) */ + UINT (*infunc)(JDEC *, BYTE *, UINT); /* Pointer to jpeg stream input function */ + void *device; /* Pointer to I/O device identifiler for the session */ +}; + +/* TJpgDec API functions */ +JRESULT jd_prepare (JDEC *, UINT(*)(JDEC *, BYTE *, UINT), void *, UINT, void *); +JRESULT jd_decomp (JDEC *, UINT(*)(JDEC *, void *, JRECT *), BYTE); + + +#ifdef __cplusplus +} +#endif + +#endif /* _TJPGDEC */ diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/uart.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/uart.h new file mode 100644 index 00000000..0c45e92c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/uart.h @@ -0,0 +1,436 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include +#include "ets_sys.h" +#include "soc/soc.h" +#include "soc/uart_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup uart_apis, uart configuration and communication related apis + * @brief uart apis + */ + +/** @addtogroup uart_apis + * @{ + */ + +#define RX_BUFF_SIZE 0x400 +#define TX_BUFF_SIZE 100 + +//uart int enalbe register ctrl bits +#define UART_RCV_INTEN BIT0 +#define UART_TRX_INTEN BIT1 +#define UART_LINE_STATUS_INTEN BIT2 + +//uart int identification ctrl bits +#define UART_INT_FLAG_MASK 0x0E + +//uart fifo ctrl bits +#define UART_CLR_RCV_FIFO BIT1 +#define UART_CLR_TRX_FIFO BIT2 +#define UART_RCVFIFO_TRG_LVL_BITS BIT6 + +//uart line control bits +#define UART_DIV_LATCH_ACCESS_BIT BIT7 + +//uart line status bits +#define UART_RCV_DATA_RDY_FLAG BIT0 +#define UART_RCV_OVER_FLOW_FLAG BIT1 +#define UART_RCV_PARITY_ERR_FLAG BIT2 +#define UART_RCV_FRAME_ERR_FLAG BIT3 +#define UART_BRK_INT_FLAG BIT4 +#define UART_TRX_FIFO_EMPTY_FLAG BIT5 +#define UART_TRX_ALL_EMPTY_FLAG BIT6 // include fifo and shift reg +#define UART_RCV_ERR_FLAG BIT7 + +//send and receive message frame head +#define FRAME_FLAG 0x7E + +typedef enum { + UART_LINE_STATUS_INT_FLAG = 0x06, + UART_RCV_FIFO_INT_FLAG = 0x04, + UART_RCV_TMOUT_INT_FLAG = 0x0C, + UART_TXBUFF_EMPTY_INT_FLAG = 0x02 +} UartIntType; //consider bit0 for int_flag + +typedef enum { + RCV_ONE_BYTE = 0x0, + RCV_FOUR_BYTE = 0x1, + RCV_EIGHT_BYTE = 0x2, + RCV_FOURTEEN_BYTE = 0x3 +} UartRcvFifoTrgLvl; + +typedef enum { + FIVE_BITS = 0x0, + SIX_BITS = 0x1, + SEVEN_BITS = 0x2, + EIGHT_BITS = 0x3 +} UartBitsNum4Char; + +typedef enum { + ONE_STOP_BIT = 1, + ONE_HALF_STOP_BIT = 2, + TWO_STOP_BIT = 3 +} UartStopBitsNum; + +typedef enum { + NONE_BITS = 0, + ODD_BITS = 2, + EVEN_BITS = 3 + +} UartParityMode; + +typedef enum { + STICK_PARITY_DIS = 0, + STICK_PARITY_EN = 2 +} UartExistParity; + +typedef enum { + BIT_RATE_9600 = 9600, + BIT_RATE_19200 = 19200, + BIT_RATE_38400 = 38400, + BIT_RATE_57600 = 57600, + BIT_RATE_115200 = 115200, + BIT_RATE_230400 = 230400, + BIT_RATE_460800 = 460800, + BIT_RATE_921600 = 921600 +} UartBautRate; + +typedef enum { + NONE_CTRL, + HARDWARE_CTRL, + XON_XOFF_CTRL +} UartFlowCtrl; + +typedef enum { + EMPTY, + UNDER_WRITE, + WRITE_OVER +} RcvMsgBuffState; + +typedef struct { + uint8_t *pRcvMsgBuff; + uint8_t *pWritePos; + uint8_t *pReadPos; + uint8_t TrigLvl; + RcvMsgBuffState BuffState; +} RcvMsgBuff; + +typedef struct { + uint32_t TrxBuffSize; + uint8_t *pTrxBuff; +} TrxMsgBuff; + +typedef enum { + BAUD_RATE_DET, + WAIT_SYNC_FRM, + SRCH_MSG_HEAD, + RCV_MSG_BODY, + RCV_ESC_CHAR, +} RcvMsgState; + +typedef struct { + UartBautRate baut_rate; + UartBitsNum4Char data_bits; + UartExistParity exist_parity; + UartParityMode parity; // chip size in byte + UartStopBitsNum stop_bits; + UartFlowCtrl flow_ctrl; + uint8_t buff_uart_no; //indicate which uart use tx/rx buffer + RcvMsgBuff rcv_buff; +// TrxMsgBuff trx_buff; + RcvMsgState rcv_state; + int received; +} UartDevice; + +/** + * @brief Init uart device struct value and reset uart0/uart1 rx. + * Please do not call this function in SDK. + * + * @param rxBuffer, must be a pointer to RX_BUFF_SIZE bytes or NULL + * + * @return None + */ +void uartAttach(void *rxBuffer); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, else for UART1. + * + * @param uint32_t clock : clock used by uart module, to adjust baudrate. + * + * @return None + */ +void Uart_Init(uint8_t uart_no, uint32_t clock); + +/** + * @brief Modify uart baudrate. + * This function will reset RX/TX fifo for uart. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint32_t DivLatchValue : (clock << 4)/baudrate. + * + * @return None + */ +void uart_div_modify(uint8_t uart_no, uint32_t DivLatchValue); + +/** + * @brief Init uart0 or uart1 for UART download booting mode. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @param uint8_t is_sync : 0, only one UART module, easy to detect, wait until detected; + * 1, two UART modules, hard to detect, detect and return. + * + * @return None + */ +int uart_baudrate_detect(uint8_t uart_no, uint8_t is_sync); + +/** + * @brief Switch printf channel of uart_tx_one_char. + * Please do not call this function when printf. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_tx_switch(uint8_t uart_no); + +/** + * @brief Switch message exchange channel for UART download booting. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None + */ +void uart_buff_switch(uint8_t uart_no); + +/** + * @brief Output a char to printf channel, wait until fifo not full. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char(uint8_t TxChar); + +/** + * @brief Output a char to message exchange channel, wait until fifo not full. + * Please do not call this function in SDK. + * + * @param None + * + * @return OK. + */ +STATUS uart_tx_one_char2(uint8_t TxChar); + +/** + * @brief Wait until uart tx full empty. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return None. + */ +void uart_tx_flush(uint8_t uart_no); + +/** + * @brief Wait until uart tx full empty and the last char send ok. + * + * @param uart_no : 0 for UART0, 1 for UART1, 2 for UART2 + * + * The function defined in ROM code has a bug, so we define the correct version + * here for compatibility. + */ +void uart_tx_wait_idle(uint8_t uart_no); + +/** + * @brief Get an input char from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pRxChar : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_one_char(uint8_t *pRxChar); + +/** + * @brief Get an input char from message channel, wait until successful. + * Please do not call this function in SDK. + * + * @param None + * + * @return char : input char value. + */ +char uart_rx_one_char_block(void); + +/** + * @brief Get an input string line from message channel. + * Please do not call this function in SDK. + * + * @param uint8_t *pString : the pointer to store the string. + * + * @param uint8_t MaxStrlen : the max string length, incude '\0'. + * + * @return OK. + */ +STATUS UartRxString(uint8_t *pString, uint8_t MaxStrlen); + +/** + * @brief Process uart recevied information in the interrupt handler. + * Please do not call this function in SDK. + * + * @param void *para : the message receive buffer. + * + * @return None + */ +void uart_rx_intr_handler(void *para); + +/** + * @brief Get an char from receive buffer. + * Please do not call this function in SDK. + * + * @param RcvMsgBuff *pRxBuff : the pointer to the struct that include receive buffer. + * + * @param uint8_t *pRxByte : the pointer to store the char. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS uart_rx_readbuff( RcvMsgBuff *pRxBuff, uint8_t *pRxByte); + +/** + * @brief Get all chars from receive buffer. + * Please do not call this function in SDK. + * + * @param uint8_t *pCmdLn : the pointer to store the string. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS UartGetCmdLn(uint8_t *pCmdLn); + +/** + * @brief Get uart configuration struct. + * Please do not call this function in SDK. + * + * @param None + * + * @return UartDevice * : uart configuration struct pointer. + */ +UartDevice *GetUartDevice(void); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to output string. + * + * @param int len : the string length. + * + * @return None. + */ +void send_packet(uint8_t *p, int len); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *p : the pointer to input string. + * + * @param int len : If string length > len, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return int : the length of the string. + */ +int recv_packet(uint8_t *p, int len, uint8_t is_sync); + +/** + * @brief Send an packet to download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t DataLen : the string length. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS SendMsg(uint8_t *pData, uint16_t DataLen); + +/** + * @brief Receive an packet from download tool, with SLIP escaping. + * Please do not call this function in SDK. + * + * @param uint8_t *pData : the pointer to input string. + * + * @param uint16_t MaxDataLen : If string length > MaxDataLen, the string will be truncated. + * + * @param uint8_t is_sync : 0, only one UART module; + * 1, two UART modules. + * + * @return OK for successful. + * FAIL for failed. + */ +STATUS RcvMsg(uint8_t *pData, uint16_t MaxDataLen, uint8_t is_sync); + +/** + * @brief Check if this UART is in download connection. + * Please do not call this function in SDK. + * + * @param uint8_t uart_no : 0 for UART0, 1 for UART1. + * + * @return ETS_NO_BOOT = 0 for no. + * SEL_UART_BOOT = BIT(1) for yes. + */ +uint8_t UartConnCheck(uint8_t uart_no); + +/** + * @brief Initialize the USB ACM UART + * Needs to be fed a buffer of at least 128 bytes, plus any rx buffer you may want to have. + * + * @param cdc_acm_work_mem Pointer to work mem for CDC-ACM code + * @param cdc_acm_work_mem_len Length of work mem + */ +void Uart_Init_USB(void *cdc_acm_work_mem, int cdc_acm_work_mem_len); + + +/** + * @brief Install handler to reset the chip when a RTS change has been detected on the CDC-ACM 'UART'. + */ +void uart_usb_enable_reset_on_rts(void); + + +extern UartDevice UartDev; + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cdc_acm.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cdc_acm.h new file mode 100644 index 00000000..90d71e81 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cdc_acm.h @@ -0,0 +1,262 @@ +/******************************************************************************* + * + * Copyright(c) 2015,2016 Intel Corporation. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ******************************************************************************/ + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void cdc_acm_device; +extern cdc_acm_device *uart_acm_dev; + +#define ACM_BYTES_PER_TX 64 + +//ACM statuses are negative to distinguish from USB_DC_* status codes +#define ACM_STATUS_LINESTATE_CHANGED -1 +#define ACM_STATUS_LINECODING_CHANGED -2 +#define ACM_STATUS_TX -3 +#define ACM_STATUS_RX -4 + +typedef void(*uart_irq_callback_t)(cdc_acm_device *dev, int status); + +/** + * @brief Get amount of received characters in buffer + * + * @returns character count + */ + +int cdc_acm_rx_fifo_cnt(cdc_acm_device *dev); + + +/* + * @brief Poll the device for input. + * + * @return -ENOTSUP Since underlying USB device controller always uses + * interrupts, polled mode UART APIs are not implemented for the UART interface + * exported by CDC ACM driver. Apps should use fifo_read API instead. + */ + +int cdc_acm_poll_in(cdc_acm_device *dev, unsigned char *c); + +/* + * @brief Output a character in polled mode. + * + * The UART poll method for USB UART is simulated by waiting till + * we get the next BULK In upcall from the USB device controller or 100 ms. + * + * @return the same character which is sent + */ +unsigned char cdc_acm_poll_out(cdc_acm_device *dev, unsigned char c); + +/** + * @brief Fill FIFO with data + * + * @param dev CDC ACM device struct. + * @param tx_data Data to transmit. + * @param len Number of bytes to send. + * + * @return Number of bytes sent. + */ +int cdc_acm_fifo_fill(cdc_acm_device *dev, const uint8_t *tx_data, int len); + +/** + * @brief Read data from FIFO + * + * @param dev CDC ACM device struct. + * @param rx_data Pointer to data container. + * @param size Container size. + * + * @return Number of bytes read. + */ +int cdc_acm_fifo_read(cdc_acm_device *dev, uint8_t *rx_data, const int size); + +/** + * @brief Enable TX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_tx_enable(cdc_acm_device *dev); + +/** + * @brief Disable TX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_tx_disable(cdc_acm_device *dev); + +/** + * @brief Check if Tx IRQ has been raised + * + * @param dev CDC ACM device struct. + * + * @return 1 if a Tx IRQ is pending, 0 otherwise. + */ +int cdc_acm_irq_tx_ready(cdc_acm_device *dev); + +/** + * @brief Enable RX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A + */ +void cdc_acm_irq_rx_enable(cdc_acm_device *dev); + +/** + * @brief Disable RX interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_rx_disable(cdc_acm_device *dev); + +/** + * @brief Enable line state interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_state_enable(cdc_acm_device *dev); + +/** + * @brief Disable line state interrupt + * + * @param dev CDC ACM device struct. + * + * @return N/A. + */ +void cdc_acm_irq_state_disable(cdc_acm_device *dev); + + +/** + * @brief Check if Rx IRQ has been raised + * + * @param dev CDC ACM device struct. + * + * @return 1 if an IRQ is ready, 0 otherwise. + */ +int cdc_acm_irq_rx_ready(cdc_acm_device *dev); + +/** + * @brief Check if Tx or Rx IRQ is pending + * + * @param dev CDC ACM device struct. + * + * @return 1 if a Tx or Rx IRQ is pending, 0 otherwise. + */ +int cdc_acm_irq_is_pending(cdc_acm_device *dev); + +/** + * @brief Set the callback function pointer for IRQ. + * + * @param dev CDC ACM device struct. + * @param cb Callback function pointer. + * + * @return N/A + */ +void cdc_acm_irq_callback_set(cdc_acm_device *dev, uart_irq_callback_t cb); + +/** + * @brief Manipulate line control for UART. + * + * @param dev CDC ACM device struct + * @param ctrl The line control to be manipulated + * @param val Value to set the line control + * + * @return 0 if successful, failed otherwise. + */ +int cdc_acm_line_ctrl_set(cdc_acm_device *dev, uint32_t ctrl, uint32_t val); + +/** + * @brief Manipulate line control for UART. + * + * @param dev CDC ACM device struct + * @param ctrl The line control to be manipulated + * @param val Value to set the line control + * + * @return 0 if successful, failed otherwise. + */ +int cdc_acm_line_ctrl_get(cdc_acm_device *dev, uint32_t ctrl, uint32_t *val); + + +/** + * @brief Initialize UART channel + * + * This routine is called to reset the chip in a quiescent state. + * It is assumed that this function is called only once per UART. + * + * @param mem_chunk Memory chunk to use for internal use + * @param mem_chunk_size Size of the memory chunk in bytes + * + * @return dev or NULL + */ +cdc_acm_device *cdc_acm_init(void *mem_chunk, int mem_chunk_size); + + +/** Common line controls for UART.*/ +#define LINE_CTRL_BAUD_RATE (1 << 0) +#define LINE_CTRL_RTS (1 << 1) +#define LINE_CTRL_DTR (1 << 2) +#define LINE_CTRL_DCD (1 << 3) +#define LINE_CTRL_DSR (1 << 4) + +/* Common communication errors for UART.*/ + +/** @brief Overrun error */ +#define UART_ERROR_OVERRUN (1 << 0) + +/** @brief Parity error */ +#define UART_ERROR_PARITY (1 << 1) + +/** @brief Framing error */ +#define UART_ERROR_FRAMING (1 << 2) + +/** + * @brief Break interrupt error: + * + * A break interrupt was received. This happens when the serial input is + * held at a logic '0' state for longer than the sum of start time + data bits + * + parity + stop bits. + */ +#define UART_ERROR_BREAK (1 << 3) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/chip_usb_dw_wrapper.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/chip_usb_dw_wrapper.h new file mode 100644 index 00000000..a7c50643 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/chip_usb_dw_wrapper.h @@ -0,0 +1,30 @@ +// Copyright 2019-2020 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. + +#pragma once +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int chip_usb_dw_init(void); +int chip_usb_dw_did_persist(void); +void chip_usb_dw_prepare_persist(void); +uint32_t chip_usb_get_persist_flags(void); +void chip_usb_set_persist_flags(uint32_t flags); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cpio.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cpio.h new file mode 100644 index 00000000..5603b3f5 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/cpio.h @@ -0,0 +1,180 @@ +// Copyright 2015-2016 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. + + +/** + * Archive to parse cpio data in the newc and crc formats. Generate a cpio archive like that by e.g. + * find . | cpio -o -H newc > archive.cpio + */ + +#pragma once + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define CPIO_MODE_FILETYPE_MASK 0xF000 +#define CPIO_MODE_FILETYPE_SOCKET 0xC000 +#define CPIO_MODE_FILETYPE_SYMLINK 0xA000 +#define CPIO_MODE_FILETYPE_REGULAR 0x8000 +#define CPIO_MODE_FILETYPE_BLOCKDEV 0x6000 +#define CPIO_MODE_FILETYPE_DIR 0x4000 +#define CPIO_MODE_FILETYPE_CHARDEV 0x2000 +#define CPIO_MODE_FILETYPE_FIFO 0x1000 +#define CPIO_MODE_SUID 0x0800 +#define CPIO_MODE_SGID 0x0400 +#define CPIO_MODE_STICKY 0x0200 + +typedef struct { + size_t filesize; + char *name; + uint32_t mode; + uint32_t check; +} cpio_file_t; + +typedef enum { + CPIO_RET_MORE = 0, + CPIO_RET_DONE, + CPIO_RET_ERR +} cpio_ret_t; + +typedef struct cpio_handle_data_t cpio_handle_data_t; +typedef cpio_handle_data_t *cpio_handle_t; + +typedef enum { + CPIO_RSN_FILE_ALL = 0, + CPIO_RSN_FILE_INITIAL, + CPIO_RSN_FILE_MORE, + CPIO_RSN_FILE_END +} cpio_callback_reason_t; + + +/** + * Callback for cpio file data. + * + * This callback will be called by the library to indicate data for a file is available. + * + * For files in the cpio archive that fit entirely in the internal buffer, or when no internal + * buffer is available, are entirely contained in the buffer fed to cpio_feed(), this callback + * is only called once, with reason=CPIO_RNS_FILE_ALL. fileinfo will contain the information + * for that specific file (name, size, ...), buff_offset will be 0, buff_len is the file + * size and buff contains all the information for the file. + * + * For files that do not fit in the buffer, this callback will be called multiple times. + * The initial time with reason=CPIO_RSN_FILE_INITIAL, when more data is available with + * CPIO_RSN_FILE_MORE and finally with CPIO_RSN_FILE_END. For these calls, fileinfo + * will again contain file information. buff will be the information contained in the + * file at offset buff_offset, and the lenght of this buffer will be in buff_len. + * + * The library guarantees to feed all file data to the callback consequitively, so + * within the same file, the buff_offset from a call will always be (buff_offset+buff_len) + * from the call before that. If cpio_start is + * + * The library also guarantees every file in the cpio archive will either generate a single + * callback call with CPIO_RSN_ALL, or multiple with in sequence CPIO_RSN_FILE_INITIAL, 0 or + * more CPIO_RSN_FILE_MORE and finally a CPIO_RSN_FILE_END. + * + * When a non-zero buffer size is passed to cpio_start, the library guarantees that all callback + * calls with a reason of CPIO_RSN_FILE_INITIAL and CPIO_RSN_FILE_MORE will have a buffer + * filled with exactly this amount of bytes. + * + */ +typedef void (*cpio_callback_t)(cpio_callback_reason_t reason, cpio_file_t *fileinfo, size_t buff_offset, size_t buff_len, char *buff, void *arg); + + +/** + * @brief Initialize a cpio handle. + * + * Call this to start parsing a cpio archive. You can set the callback that handles the + * files/data here. + * + * @param callback The callback that will handle the data of the files inside the cpio archive + * + * @param cbarg User-supplied argument. The callback will be called with this as an argument. + * + * @param buflen Length of internal buffer used. + * If this is zero, the callback will be called with data that lives in the data buffer + * supplied to the cpio library by whomever called cpio_feed(). Because this library has + * no power over that buffer, the callback can be passed as little as 1 and as many as + * INT_MAX bytes at a time. + * If this is non-zero, the library will allocate an internal buffer of this size. All + * cpio_feed()-calls will be rebuffered, and the callback is guaranteed to only be called + * with this many bytes in the buffer, given there's enough data in the file to fill it. + * + * @param memchunk Chunk of memory to allocate everything (handle, I/O buffer, filename buffer) in. Minimum size + * (estimate) is 160+buflen+sizeof(largest filename/path). + * @param memchunklen Size of the mem chunk + * + * @return + * - Success: A pointer to a cpio handle + * - Error: NULL + * + */ +cpio_handle_t cpio_start(cpio_callback_t callback, void *cbarg, size_t buflen, void *memchunk, int memchunklen); + +/** + * @brief Feed data from a cpio archive into the library + * + * This routine is used to feed consecutive data of the cpio archive into the library. While processing, + * the library can call the callback function one or more times if needed. + * + * @param cpio Handle obtained by calling cpio_start() + * + * @param buffer Pointer to buffer containing cpio archive data + * + * @param len Length of the buffer, in bytes + * + * @return + * - CPIO_RET_MORE: CPIO archive isn't done yet, please feed more data. + * - CPIO_RET_DONE: CPUI archive is finished. + * - CPIO_RET_ERR: Invalid CPIO archive data; decoding aborted. + * + */ +cpio_ret_t cpio_feed(cpio_handle_t cpio, char *buffer, int len); + +/** + * @brief Indicate there is no more cpio data to be fed into the archive + * + * This call is to be called when the source data is exhausted. Normally, the library can find the end of the + * cpio archive by looking for the end marker, + * + * @param timer_conf Pointer of LEDC timer configure struct + * + * + * @return + * - CPIO_RET_DONE on success + * - CPIO_RET_ERR when cpio archive is invalid + * + */ +cpio_ret_t cpio_done(cpio_handle_t cpio); + + +/** + * @brief Free the memory allocated for a cpio handle. + * + * @param cpio Handle obtained by calling cpio_start() + * + * @return + * - CPIO_RET_DONE on success + * + */ +cpio_ret_t cpio_destroy(cpio_handle_t cpio); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_cdc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_cdc.h new file mode 100644 index 00000000..c241bcfe --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_cdc.h @@ -0,0 +1,174 @@ +/* usb_cdc.h - USB CDC-ACM and CDC-ECM public header */ + +/* + * Copyright (c) 2017 PHYTEC Messtechnik GmbH + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/** + * @file + * @brief USB Communications Device Class (CDC) public header + * + * Header follows the Class Definitions for + * Communications Devices Specification (CDC120-20101103-track.pdf), + * PSTN Devices Specification (PSTN120.pdf) and + * Ethernet Control Model Devices Specification (ECM120.pdf). + * Header is limited to ACM and ECM Subclasses. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** CDC Specification release number in BCD format */ +#define CDC_SRN_1_20 0x0120 + +/** Communications Class Subclass Codes */ +#define ACM_SUBCLASS 0x02 +#define ECM_SUBCLASS 0x06 +#define EEM_SUBCLASS 0x0c + +/** Communications Class Protocol Codes */ +#define AT_CMD_V250_PROTOCOL 0x01 +#define EEM_PROTOCOL 0x07 + +/** + * @brief Data Class Interface Codes + * @note CDC120-20101103-track.pdf, 4.5, Table 6 + */ +#define DATA_INTERFACE_CLASS 0x0A + +/** + * @brief Values for the bDescriptorType Field + * @note CDC120-20101103-track.pdf, 5.2.3, Table 12 + */ +#define CS_INTERFACE 0x24 +#define CS_ENDPOINT 0x25 + +/** + * @brief bDescriptor SubType for Communications + * Class Functional Descriptors + * @note CDC120-20101103-track.pdf, 5.2.3, Table 13 + */ +#define HEADER_FUNC_DESC 0x00 +#define CALL_MANAGEMENT_FUNC_DESC 0x01 +#define ACM_FUNC_DESC 0x02 +#define UNION_FUNC_DESC 0x06 +#define ETHERNET_FUNC_DESC 0x0F + +/** + * @brief PSTN Subclass Specific Requests + * for ACM devices + * @note PSTN120.pdf, 6.3, Table 13 + */ +#define CDC_SEND_ENC_CMD 0x00 +#define CDC_GET_ENC_RSP 0x01 +#define SET_LINE_CODING 0x20 +#define GET_LINE_CODING 0x21 +#define SET_CONTROL_LINE_STATE 0x22 + +/** Control Signal Bitmap Values for SetControlLineState */ +#define SET_CONTROL_LINE_STATE_RTS 0x02 +#define SET_CONTROL_LINE_STATE_DTR 0x01 + +/** UART State Bitmap Values */ +#define SERIAL_STATE_OVERRUN 0x40 +#define SERIAL_STATE_PARITY 0x20 +#define SERIAL_STATE_FRAMING 0x10 +#define SERIAL_STATE_RING 0x08 +#define SERIAL_STATE_BREAK 0x04 +#define SERIAL_STATE_TX_CARRIER 0x02 +#define SERIAL_STATE_RX_CARRIER 0x01 + +/** + * @brief Class-Specific Request Codes for Ethernet subclass + * @note ECM120.pdf, 6.2, Table 6 + */ +#define SET_ETHERNET_MULTICAST_FILTERS 0x40 +#define SET_ETHERNET_PM_FILTER 0x41 +#define GET_ETHERNET_PM_FILTER 0x42 +#define SET_ETHERNET_PACKET_FILTER 0x43 +#define GET_ETHERNET_STATISTIC 0x44 + +/** Ethernet Packet Filter Bitmap */ +#define PACKET_TYPE_MULTICAST 0x10 +#define PACKET_TYPE_BROADCAST 0x08 +#define PACKET_TYPE_DIRECTED 0x04 +#define PACKET_TYPE_ALL_MULTICAST 0x02 +#define PACKET_TYPE_PROMISCUOUS 0x01 + +/** Header Functional Descriptor */ +struct cdc_header_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint16_t bcdCDC; +} __packed; + +/** Union Interface Functional Descriptor */ +struct cdc_union_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bControlInterface; + uint8_t bSubordinateInterface0; +} __packed; + +/** Call Management Functional Descriptor */ +struct cdc_cm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bmCapabilities; + uint8_t bDataInterface; +} __packed; + +/** Abstract Control Management Functional Descriptor */ +struct cdc_acm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t bmCapabilities; +} __packed; + + +/** Data structure for GET_LINE_CODING / SET_LINE_CODING class requests */ +struct cdc_acm_line_coding { + uint32_t dwDTERate; + uint8_t bCharFormat; + uint8_t bParityType; + uint8_t bDataBits; +} __packed; + +/** Data structure for the notification about SerialState */ +struct cdc_acm_notification { + uint8_t bmRequestType; + uint8_t bNotificationType; + uint16_t wValue; + uint16_t wIndex; + uint16_t wLength; + uint16_t data; +} __packed; + +/** Ethernet Networking Functional Descriptor */ +struct cdc_ecm_descriptor { + uint8_t bFunctionLength; + uint8_t bDescriptorType; + uint8_t bDescriptorSubtype; + uint8_t iMACAddress; + uint32_t bmEthernetStatistics; + uint16_t wMaxSegmentSize; + uint16_t wNumberMCFilters; + uint8_t bNumberPowerFilters; +} __packed; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_common.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_common.h new file mode 100644 index 00000000..c3bd52cf --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_common.h @@ -0,0 +1,243 @@ +/*************************************************************************** + * + * + * Copyright(c) 2015,2016 Intel Corporation. + * Copyright(c) 2017 PHYTEC Messtechnik GmbH + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ***************************************************************************/ + +/** + * @file + * @brief useful constants and macros for the USB application + * + * This file contains useful constants and macros for the USB applications. + */ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define BCD(x) ((((x) / 10) << 4) | ((x) / 10)) + +/* Descriptor size in bytes */ +#define USB_DEVICE_DESC_SIZE 18 +#define USB_CONFIGURATION_DESC_SIZE 9 +#define USB_INTERFACE_DESC_SIZE 9 +#define USB_ENDPOINT_DESC_SIZE 7 +#define USB_STRING_DESC_SIZE 4 +#define USB_HID_DESC_SIZE 9 +#define USB_DFU_DESC_SIZE 9 +#define USB_DEVICE_QUAL_DESC_SIZE 10 +#define USB_INTERFACE_ASSOC_DESC_SIZE 8 + +/* Descriptor type */ +#define USB_DEVICE_DESC 0x01 +#define USB_CONFIGURATION_DESC 0x02 +#define USB_STRING_DESC 0x03 +#define USB_INTERFACE_DESC 0x04 +#define USB_ENDPOINT_DESC 0x05 +#define USB_DEVICE_QUAL_DESC 0x06 +#define USB_INTERFACE_ASSOC_DESC 0x0B +#define USB_DEVICE_CAPABILITY_DESC 0x10 +#define USB_HID_DESC 0x21 +#define USB_HID_REPORT_DESC 0x22 +#define USB_DFU_FUNCTIONAL_DESC 0x21 +#define USB_ASSOCIATION_DESC 0x0B +#define USB_BINARY_OBJECT_STORE_DESC 0x0F + +/* Useful define */ +#define USB_1_1 0x0110 +#define USB_2_0 0x0200 +/* Set USB version to 2.1 so that the host will request the BOS descriptor */ +#define USB_2_1 0x0210 + +#define BCDDEVICE_RELNUM (BCD(KERNEL_VERSION_MAJOR) << 8 | \ + BCD(KERNEL_VERSION_MINOR)) + +/* 100mA max power, per 2mA units */ +/* USB 1.1 spec indicates 100mA(max) per unit load, up to 5 loads */ +#define MAX_LOW_POWER 0x32 +#define MAX_HIGH_POWER 0xFA + +/* bmAttributes: + * D7:Reserved, always 1, + * D6:Self-Powered -> 1, + * D5:Remote Wakeup -> 0, + * D4...0:Reserved -> 0 + */ +#define USB_CONFIGURATION_ATTRIBUTES 0xC0 + +/* Classes */ +#define COMMUNICATION_DEVICE_CLASS 0x02 +#define COMMUNICATION_DEVICE_CLASS_DATA 0x0A +#define HID_CLASS 0x03 +#define MASS_STORAGE_CLASS 0x08 +#define WIRELESS_DEVICE_CLASS 0xE0 +#define MISC_CLASS 0xEF +#define CUSTOM_CLASS 0xFF +#define DFU_DEVICE_CLASS 0xFE + +/* Sub-classes */ +#define CDC_NCM_SUBCLASS 0x0d +#define BOOT_INTERFACE_SUBCLASS 0x01 +#define SCSI_TRANSPARENT_SUBCLASS 0x06 +#define DFU_INTERFACE_SUBCLASS 0x01 +#define RF_SUBCLASS 0x01 +#define CUSTOM_SUBCLASS 0xFF +#define COMMON_SUBCLASS 0x02 +/* Misc subclasses */ +#define MISC_RNDIS_SUBCLASS 0x04 +#define CDC_ABSTRACT_CONTROL_MODEL 0x02 + +/* Protocols */ +#define V25TER_PROTOCOL 0x01 +#define MOUSE_PROTOCOL 0x02 +#define BULK_ONLY_PROTOCOL 0x50 +#define DFU_RUNTIME_PROTOCOL 0x01 +#define DFU_MODE_PROTOCOL 0x02 +#define BLUETOOTH_PROTOCOL 0x01 +/* CDC ACM protocols */ +#define ACM_VENDOR_PROTOCOL 0xFF +/* Misc protocols */ +#define MISC_ETHERNET_PROTOCOL 0x01 +#define IAD_PROTOCOL 0x01 + +/** Standard Device Descriptor */ +struct usb_device_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} __packed; + +/** Unicode (UTF16LE) String Descriptor */ +struct usb_string_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bString; +} __packed; + +/** Association Descriptor */ +struct usb_association_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bFirstInterface; + uint8_t bInterfaceCount; + uint8_t bFunctionClass; + uint8_t bFunctionSubClass; + uint8_t bFunctionProtocol; + uint8_t iFunction; +} __packed; + +/** Standard Configuration Descriptor */ +struct usb_cfg_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} __packed; + +/** Standard Interface Descriptor */ +struct usb_if_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} __packed; + +/** Standard Endpoint Descriptor */ +struct usb_ep_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; +} __packed; + +struct string_descriptor_zero { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wBcdLang[]; +} __packed; + +struct string_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bString[]; +} __packed; + +#define ROM_MAX_CFG_DESC_CNT 1 + +struct rom_usb_descriptors { + const struct usb_device_descriptor *device_descr; + const void *config_descr[ROM_MAX_CFG_DESC_CNT]; + int string_count; // including string_descriptor_zero + const struct string_descriptor_zero *string0_descr; + const struct string_descriptor *string_descrs[]; +}; + +/* Descriptors defined in the ROM */ +extern struct usb_device_descriptor general_device_descr; +extern const void* acm_config_descr; +extern const void* dfu_config_descr; +extern const struct string_descriptor str_manu_descr; +extern const struct string_descriptor str_prod_descr; +extern const struct string_descriptor_zero string0_descr; +extern const struct rom_usb_descriptors acm_usb_descriptors; +extern const struct rom_usb_descriptors dfu_usb_descriptors; +extern const struct rom_usb_descriptors *rom_usb_curr_desc; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dc.h new file mode 100644 index 00000000..f20e897c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dc.h @@ -0,0 +1,392 @@ +/* usb_dc.h - USB device controller driver interface */ + +/* + * Copyright (c) 2016 Intel Corporation. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief USB device controller APIs + * + * This file contains the USB device controller APIs. All device controller + * drivers should implement the APIs described in this file. + */ + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * USB endpoint direction and number. + */ + +#define USB_EP_DIR_MASK 0x80 +#define USB_EP_DIR_IN 0x80 +#define USB_EP_DIR_OUT 0x00 + +/** + * USB Driver Status Codes + */ +enum usb_dc_status_code { + USB_DC_ERROR, /* USB error reported by the controller */ + USB_DC_RESET, /* USB reset */ + /* USB connection established, hardware enumeration is completed */ + USB_DC_CONNECTED, + USB_DC_CONFIGURED, /* USB configuration done */ + USB_DC_DISCONNECTED, /* USB connection lost */ + USB_DC_SUSPEND, /* USB connection suspended by the HOST */ + USB_DC_RESUME, /* USB connection resumed by the HOST */ + USB_DC_INTERFACE, /* USB interface selected */ + USB_DC_SET_HALT, /* Set Feature ENDPOINT_HALT received */ + USB_DC_CLEAR_HALT, /* Clear Feature ENDPOINT_HALT received */ + USB_DC_UNKNOWN /* Initial USB connection status */ +}; + +/** + * USB Endpoint Callback Status Codes + */ +enum usb_dc_ep_cb_status_code { + USB_DC_EP_SETUP, /* SETUP received */ + /* Out transaction on this EP, data is available for read */ + USB_DC_EP_DATA_OUT, + USB_DC_EP_DATA_IN, /* In transaction done on this EP */ +}; + +/** + * USB Endpoint type + */ +enum usb_dc_ep_type { + USB_DC_EP_CONTROL = 0, /* Control type endpoint */ + USB_DC_EP_ISOCHRONOUS, /* Isochronous type endpoint */ + USB_DC_EP_BULK, /* Bulk type endpoint */ + USB_DC_EP_INTERRUPT /* Interrupt type endpoint */ +}; + +/** + * USB Endpoint Configuration. + */ +struct usb_dc_ep_cfg_data { + /** The number associated with the EP in the device + * configuration structure + * IN EP = 0x80 | \ + * OUT EP = 0x00 | \ + */ + uint8_t ep_addr; + uint16_t ep_mps; /** Endpoint max packet size */ + enum usb_dc_ep_type ep_type; /** Endpoint type */ +}; + +/** + * Callback function signature for the USB Endpoint status + */ +typedef void (*usb_dc_ep_callback)(uint8_t ep, + enum usb_dc_ep_cb_status_code cb_status); + +/** + * Callback function signature for the device + */ +typedef void (*usb_dc_status_callback)(enum usb_dc_status_code cb_status, + uint8_t *param); + +/** + * @brief attach USB for device connection + * + * Function to attach USB for device connection. Upon success, the USB PLL + * is enabled, and the USB device is now capable of transmitting and receiving + * on the USB bus and of generating interrupts. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_attach(void); + +/** + * @brief detach the USB device + * + * Function to detach the USB device. Upon success, the USB hardware PLL + * is powered down and USB communication is disabled. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_detach(void); + +/** + * @brief reset the USB device + * + * This function returns the USB device and firmware back to it's initial state. + * N.B. the USB PLL is handled by the usb_detach function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_reset(void); + +/** + * @brief set USB device address + * + * @param[in] addr device address + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_set_address(const uint8_t addr); + +/** + * @brief set USB device controller status callback + * + * Function to set USB device controller status callback. The registered + * callback is used to report changes in the status of the device controller. + * + * @param[in] cb callback function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_set_status_callback(const usb_dc_status_callback cb); + +/** + * @brief check endpoint capabilities + * + * Function to check capabilities of an endpoint. usb_dc_ep_cfg_data structure + * provides the endpoint configuration parameters: endpoint address, + * endpoint maximum packet size and endpoint type. + * The driver should check endpoint capabilities and return 0 if the + * endpoint configuration is possible. + * + * @param[in] cfg Endpoint config + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_check_cap(const struct usb_dc_ep_cfg_data *const cfg); + +/** + * @brief configure endpoint + * + * Function to configure an endpoint. usb_dc_ep_cfg_data structure provides + * the endpoint configuration parameters: endpoint address, endpoint maximum + * packet size and endpoint type. + * + * @param[in] cfg Endpoint config + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_configure(const struct usb_dc_ep_cfg_data *const cfg); + +/** + * @brief set stall condition for the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_set_stall(const uint8_t ep); + +/** + * @brief clear stall condition for the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_clear_stall(const uint8_t ep); + +/** + * @brief check if selected endpoint is stalled + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[out] stalled Endpoint stall status + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_is_stalled(const uint8_t ep, uint8_t *const stalled); + +/** + * @brief halt the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_halt(const uint8_t ep); + +/** + * @brief enable the selected endpoint + * + * Function to enable the selected endpoint. Upon success interrupts are + * enabled for the corresponding endpoint and the endpoint is ready for + * transmitting/receiving data. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_enable(const uint8_t ep); + +/** + * @brief disable the selected endpoint + * + * Function to disable the selected endpoint. Upon success interrupts are + * disabled for the corresponding endpoint and the endpoint is no longer able + * for transmitting/receiving data. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_disable(const uint8_t ep); + +/** + * @brief flush the selected endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_flush(const uint8_t ep); + +/** + * @brief write data to the specified endpoint + * + * This function is called to write data to the specified endpoint. The supplied + * usb_ep_callback function will be called when data is transmitted out. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data to write + * @param[in] data_len length of data requested to write. This may + * be zero for a zero length status packet. + * @param[out] ret_bytes bytes scheduled for transmission. This value + * may be NULL if the application expects all + * bytes to be written + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_write(const uint8_t ep, const uint8_t *const data, + const uint32_t data_len, uint32_t *const ret_bytes); + + + +/** + * @brief Indicate if the write to an IN endpoint (using usb_dc_ep_write) would block + * to wait until the endpoint has enoug space + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 when writable, 0 when not, negative errno code on fail. + */ +int usb_dc_ep_write_would_block(const uint8_t ep); + + +/** + * @brief read data from the specified endpoint + * + * This function is called by the Endpoint handler function, after an OUT + * interrupt has been received for that EP. The application must only call this + * function through the supplied usb_ep_callback function. This function clears + * the ENDPOINT NAK, if all data in the endpoint FIFO has been read, + * so as to accept more data from host. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read(const uint8_t ep, uint8_t *const data, + const uint32_t max_data_len, uint32_t *const read_bytes); + +/** + * @brief set callback function for the specified endpoint + * + * Function to set callback function for notification of data received and + * available to application or transmit done on the selected endpoint, + * NULL if callback not required by application code. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] cb callback function + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_set_callback(const uint8_t ep, const usb_dc_ep_callback cb); + +/** + * @brief read data from the specified endpoint + * + * This is similar to usb_dc_ep_read, the difference being that, it doesn't + * clear the endpoint NAKs so that the consumer is not bogged down by further + * upcalls till he is done with the processing of the data. The caller should + * reactivate ep by invoking usb_dc_ep_read_continue() do so. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *read_bytes); + + +/** + * @brief Continue reading data from the endpoint + * + * Clear the endpoint NAK and enable the endpoint to accept more data + * from the host. Usually called after usb_dc_ep_read_wait() when the consumer + * is fine to accept more data. Thus these calls together acts as flow control + * mechanism. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_dc_ep_read_continue(uint8_t ep); + +/** + * @brief Get endpoint max packet size + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return enpoint max packet size (mps) + */ +int usb_dc_ep_mps(uint8_t ep); + + + +//Hack - fake interrupts by pollinfg +void usb_dc_check_poll_for_interrupts(void); + + +//Prepare for USB persist. You should reboot after this. +int usb_dc_prepare_persist(void); + + +void usb_dw_isr_handler(void); + + +int usb_dc_ep_write_would_block(const uint8_t ep); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_descriptor.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_descriptor.h new file mode 100644 index 00000000..1b20ef80 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_descriptor.h @@ -0,0 +1,34 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define USB_DESCRIPTOR_TYPE_ACM 0 +#define USB_DESCRIPTOR_TYPE_DFU 1 + +void usb_set_current_descriptor(int descriptor_type); + +bool usb_get_descriptor(uint16_t type_index, uint16_t lang_id, + int32_t *len, uint8_t **data); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_device.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_device.h new file mode 100644 index 00000000..5564d41e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_device.h @@ -0,0 +1,401 @@ +/* + * LPCUSB, an USB device driver for LPC microcontrollers + * Copyright (C) 2006 Bertrik Sikken (bertrik@sikken.nl) + * Copyright (c) 2016 Intel Corporation + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * @brief USB device core layer APIs and structures + * + * This file contains the USB device core layer APIs and structures. + */ + +#pragma once + +#include +#include +#include "usb_dc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/************************************************************************* + * USB configuration + **************************************************************************/ + +#define MAX_PACKET_SIZE0 64 /**< maximum packet size for EP 0 */ +//Note: for FS this should be 8, 16, 32, 64 bytes. HS can go up to 512. + +/************************************************************************* + * USB application interface + **************************************************************************/ + +/** setup packet definitions */ +struct usb_setup_packet { + uint8_t bmRequestType; /**< characteristics of the specific request */ + uint8_t bRequest; /**< specific request */ + uint16_t wValue; /**< request specific parameter */ + uint16_t wIndex; /**< request specific parameter */ + uint16_t wLength; /**< length of data transferred in data phase */ +} __packed; + + +_Static_assert(sizeof(struct usb_setup_packet) == 8, "USB setup packet struct size error"); + +/** + * Callback function signature for the device + */ +typedef void (*usb_status_callback)(enum usb_dc_status_code status_code, + uint8_t *param); + +/** + * Callback function signature for the USB Endpoint status + */ +typedef void (*usb_ep_callback)(uint8_t ep, + enum usb_dc_ep_cb_status_code cb_status); + +/** + * Function which handles Class specific requests corresponding to an + * interface number specified in the device descriptor table + */ +typedef int (*usb_request_handler) (struct usb_setup_packet *detup, + int32_t *transfer_len, uint8_t **payload_data); + +/** + * Function for interface runtime configuration + */ +typedef void (*usb_interface_config)(uint8_t bInterfaceNumber); + +/* + * USB Endpoint Configuration + */ +struct usb_ep_cfg_data { + /** + * Callback function for notification of data received and + * available to application or transmit done, NULL if callback + * not required by application code + */ + usb_ep_callback ep_cb; + /** + * The number associated with the EP in the device configuration + * structure + * IN EP = 0x80 | \ + * OUT EP = 0x00 | \ + */ + uint8_t ep_addr; +}; + +/** + * USB Interface Configuration + */ +struct usb_interface_cfg_data { + /** Handler for USB Class specific Control (EP 0) communications */ + usb_request_handler class_handler; + /** Handler for USB Vendor specific commands */ + usb_request_handler vendor_handler; + /** + * The custom request handler gets a first chance at handling + * the request before it is handed over to the 'chapter 9' request + * handler + */ + usb_request_handler custom_handler; + /** + * This data area, allocated by the application, is used to store + * Class specific command data and must be large enough to store the + * largest payload associated with the largest supported Class' + * command set. This data area may be used for USB IN or OUT + * communications + */ + uint8_t *payload_data; + /** + * This data area, allocated by the application, is used to store + * Vendor specific payload + */ + uint8_t *vendor_data; +}; + +/* + * @brief USB device configuration + * + * The Application instantiates this with given parameters added + * using the "usb_set_config" function. Once this function is called + * changes to this structure will result in undefined behaviour. This structure + * may only be updated after calls to usb_deconfig + */ +struct usb_cfg_data { + /** + * USB device description, see + * http://www.beyondlogic.org/usbnutshell/usb5.shtml#DeviceDescriptors + */ + const uint8_t *usb_device_description; + /** Pointer to interface descriptor */ + const void *interface_descriptor; + /** Function for interface runtime configuration */ + usb_interface_config interface_config; + /** Callback to be notified on USB connection status change */ + usb_status_callback cb_usb_status; + /** USB interface (Class) handler and storage space */ + struct usb_interface_cfg_data interface; + /** Number of individual endpoints in the device configuration */ + uint8_t num_endpoints; + /** + * Pointer to an array of endpoint structs of length equal to the + * number of EP associated with the device description, + * not including control endpoints + */ + struct usb_ep_cfg_data *endpoint; +}; + +/* + * @brief configure USB controller + * + * Function to configure USB controller. + * Configuration parameters must be valid or an error is returned + * + * @param[in] config Pointer to configuration structure + * + * @return 0 on success, negative errno code on fail + */ +int usb_set_config(struct usb_cfg_data *config); + +/* + * @brief return the USB device to it's initial state + * + * @return 0 on success, negative errno code on fail + */ +int usb_deconfig(void); + +/* + * @brief enable USB for host/device connection + * + * Function to enable USB for host/device connection. + * Upon success, the USB module is no longer clock gated in hardware, + * it is now capable of transmitting and receiving on the USB bus and + * of generating interrupts. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_enable(struct usb_cfg_data *config); + +/* + * @brief disable the USB device. + * + * Function to disable the USB device. + * Upon success, the specified USB interface is clock gated in hardware, + * it is no longer capable of generating interrupts. + * + * @return 0 on success, negative errno code on fail + */ +int usb_disable(void); + +/* + * @brief Check if a write to an in ep would block until there is enough space + * in the fifo + * + * @param[in] ep Endpoint address corresponding to the one listed in the + * device configuration table + * + * @return 0 if free to write, 1 if a write would block, negative errno code on fail + */ +int usb_write_would_block(uint8_t ep); + +/* + * @brief write data to the specified endpoint + * + * Function to write data to the specified endpoint. The supplied + * usb_ep_callback will be called when transmission is done. + * + * @param[in] ep Endpoint address corresponding to the one listed in the + * device configuration table + * @param[in] data Pointer to data to write + * @param[in] data_len Length of data requested to write. This may be zero for + * a zero length status packet. + * @param[out] bytes_ret Bytes written to the EP FIFO. This value may be NULL if + * the application expects all bytes to be written + * + * @return 0 on success, negative errno code on fail + */ +int usb_write(uint8_t ep, const uint8_t *data, uint32_t data_len, + uint32_t *bytes_ret); + +/* + * @brief read data from the specified endpoint + * + * This function is called by the Endpoint handler function, after an + * OUT interrupt has been received for that EP. The application must + * only call this function through the supplied usb_ep_callback function. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * @param[in] data Pointer to data buffer to write to + * @param[in] max_data_len Max length of data to read + * @param[out] ret_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes available + * for read is returned. + * + * @return 0 on success, negative errno code on fail + */ +int usb_read(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *ret_bytes); + +/* + * @brief set STALL condition on the specified endpoint + * + * This function is called by USB device class handler code to set stall + * conditionin on endpoint. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * + * @return 0 on success, negative errno code on fail + */ +int usb_ep_set_stall(uint8_t ep); + + +/* + * @brief clears STALL condition on the specified endpoint + * + * This function is called by USB device class handler code to clear stall + * conditionin on endpoint. + * + * @param[in] ep Endpoint address corresponding to the one listed in + * the device configuration table + * + * @return 0 on success, negative errno code on fail + */ +int usb_ep_clear_stall(uint8_t ep); + +/** + * @brief read data from the specified endpoint + * + * This is similar to usb_ep_read, the difference being that, it doesn't + * clear the endpoint NAKs so that the consumer is not bogged down by further + * upcalls till he is done with the processing of the data. The caller should + * reactivate ep by invoking usb_ep_read_continue() do so. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data pointer to data buffer to write to + * @param[in] max_data_len max length of data to read + * @param[out] read_bytes Number of bytes read. If data is NULL and + * max_data_len is 0 the number of bytes + * available for read should be returned. + * + * @return 0 on success, negative errno code on fail. + */ +int usb_ep_read_wait(uint8_t ep, uint8_t *data, uint32_t max_data_len, + uint32_t *read_bytes); + + +/** + * @brief Continue reading data from the endpoint + * + * Clear the endpoint NAK and enable the endpoint to accept more data + * from the host. Usually called after usb_ep_read_wait() when the consumer + * is fine to accept more data. Thus these calls together acts as flow control + * mechanism. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +int usb_ep_read_continue(uint8_t ep); + +/** + * Callback function signature for transfer completion. + */ +typedef void (*usb_transfer_callback)(uint8_t ep, int tsize, void *priv); + +/* USB transfer flags */ +#define USB_TRANS_READ BIT(0) /** Read transfer flag */ +#define USB_TRANS_WRITE BIT(1) /** Write transfer flag */ +#define USB_TRANS_NO_ZLP BIT(2) /** No zero-length packet flag */ + +/** + * @brief Transfer management endpoint callback + * + * If a USB class driver wants to use high-level transfer functions, driver + * needs to register this callback as usb endpoint callback. + */ +void usb_transfer_ep_callback(uint8_t ep, enum usb_dc_ep_cb_status_code); + +/** + * @brief Start a transfer + * + * Start a usb transfer to/from the data buffer. This function is asynchronous + * and can be executed in IRQ context. The provided callback will be called + * on transfer completion (or error) in thread context. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data Pointer to data buffer to write-to/read-from + * @param[in] dlen Size of data buffer + * @param[in] flags Transfer flags (USB_TRANS_READ, USB_TRANS_WRITE...) + * @param[in] cb Function called on transfer completion/failure + * @param[in] priv Data passed back to the transfer completion callback + * + * @return 0 on success, negative errno code on fail. + */ +int usb_transfer(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags, + usb_transfer_callback cb, void *priv); + +/** + * @brief Start a transfer and block-wait for completion + * + * Synchronous version of usb_transfer, wait for transfer completion before + * returning. + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * @param[in] data Pointer to data buffer to write-to/read-from + * @param[in] dlen Size of data buffer + * @param[in] flags Transfer flags + + * + * @return number of bytes transferred on success, negative errno code on fail. + */ +int usb_transfer_sync(uint8_t ep, uint8_t *data, size_t dlen, unsigned int flags); + +/** + * @brief Cancel any ongoing transfer on the specified endpoint + * + * @param[in] ep Endpoint address corresponding to the one + * listed in the device configuration table + * + * @return 0 on success, negative errno code on fail. + */ +void usb_cancel_transfer(uint8_t ep); + + +void usb_dev_resume(int configuration); +int usb_dev_get_configuration(void); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dfu.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dfu.h new file mode 100644 index 00000000..dec7ea93 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_dfu.h @@ -0,0 +1,147 @@ +/*************************************************************************** + * + * Copyright(c) 2015,2016 Intel Corporation. + * Copyright(c) 2017 PHYTEC Messtechnik GmbH + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ***************************************************************************/ + +/** + * @file + * @brief USB Device Firmware Upgrade (DFU) public header + * + * Header follows the Device Class Specification for + * Device Firmware Upgrade Version 1.1 + */ + +#pragma once + +#include +#include +#include "usb_device.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** DFU Class Subclass */ +#define DFU_SUBCLASS 0x01 + +/** DFU Class runtime Protocol */ +#define DFU_RT_PROTOCOL 0x01 + +/** DFU Class DFU mode Protocol */ +#define DFU_MODE_PROTOCOL 0x02 + +/** + * @brief DFU Class Specific Requests + */ +#define DFU_DETACH 0x00 +#define DFU_DNLOAD 0x01 +#define DFU_UPLOAD 0x02 +#define DFU_GETSTATUS 0x03 +#define DFU_CLRSTATUS 0x04 +#define DFU_GETSTATE 0x05 +#define DFU_ABORT 0x06 + +/** DFU FUNCTIONAL descriptor type */ +#define DFU_FUNC_DESC 0x21 + +/** DFU attributes DFU Functional Descriptor */ +#define DFU_ATTR_WILL_DETACH 0x08 +#define DFU_ATTR_MANIFESTATION_TOLERANT 0x04 +#define DFU_ATTR_CAN_UPLOAD 0x02 +#define DFU_ATTR_CAN_DNLOAD 0x01 + +/** DFU Specification release */ +#define DFU_VERSION 0x0110 + +/** Run-Time Functional Descriptor */ +struct dfu_runtime_descriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bmAttributes; + uint16_t wDetachTimeOut; + uint16_t wTransferSize; + uint16_t bcdDFUVersion; +} __packed; + +/** bStatus values for the DFU_GETSTATUS response */ +enum dfu_status { + statusOK, + errTARGET, + errFILE, + errWRITE, + errERASE, + errCHECK_ERASED, + errPROG, + errVERIFY, + errADDRESS, + errNOTDONE, + errFIRMWARE, + errVENDOR, + errUSB, + errPOR, + errUNKNOWN, + errSTALLEDPKT +}; + +/** bState values for the DFU_GETSTATUS response */ +enum dfu_state { + appIDLE, + appDETACH, + dfuIDLE, + dfuDNLOAD_SYNC, + dfuDNBUSY, + dfuDNLOAD_IDLE, + dfuMANIFEST_SYNC, + dfuMANIFEST, + dfuMANIFEST_WAIT_RST, + dfuUPLOAD_IDLE, + dfuERROR, +}; + +/* + These callbacks are made public so the ACM driver can call them to handle the switch to DFU. +*/ + +int dfu_class_handle_req(struct usb_setup_packet *pSetup, + int32_t *data_len, uint8_t **data); +void dfu_status_cb(enum usb_dc_status_code status, uint8_t *param); +int usb_dfu_init(void); +int dfu_custom_handle_req(struct usb_setup_packet *pSetup, + int32_t *data_len, uint8_t **data); + + +typedef void(*usb_dfu_detach_routine_t)(int delay); +void usb_dfu_set_detach_cb(usb_dfu_detach_routine_t cb); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_os_glue.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_os_glue.h new file mode 100644 index 00000000..9abad6d0 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_os_glue.h @@ -0,0 +1,40 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +typedef void(*usb_osglue_intdisena_routine_t)(void); +typedef int(*usb_osglue_wait_routine_t)(int delay_us); + +typedef struct { + /* Disable USB interrupt */ + usb_osglue_intdisena_routine_t int_dis_proc; + /* Enable USB interrupt */ + usb_osglue_intdisena_routine_t int_ena_proc; + /* Wait for a set amount of uS. Return the amount actually waited. If delay_us is 0, just yield.*/ + usb_osglue_wait_routine_t wait_proc; +} usb_osglue_data_t; + +extern usb_osglue_data_t s_usb_osglue; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_persist.h b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_persist.h new file mode 100644 index 00000000..bcf11b7c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp32s3/rom/usb/usb_persist.h @@ -0,0 +1,50 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// USB persistence flags. + +//This bit indicates persistence has been enabled, that is, the USB initialization routines should not +//reset the USB device as the device still is initialized and the host detected it with the same cdcacm/dfu +//descriptor as the ROM uses; we can just re-initialize the software side and have at 'er. +#define USBDC_PERSIST_ENA (1<<31) + +//This bit indicates to the ROM that we rebooted because of a request to go into DFU mode; the ROM should +//honour this request. +#define USBDC_BOOT_DFU (1<<30) + + +//This being non-0 indicates a memory location where a 'testament' is stored, aka a piece of text that should be output +//after a reboot. Can contain core dump info or something. +#define USBDC_TESTAMENT_LOC_MASK 0x7FFFF //bits 19-0; this is added to a base address of 0x3FF80000. + +//The testament is a FIFO. The ROM will output all data between textstart and textend; if textend is lower than textstart it will +//output everything from textstart to memend, then memstart to textend. +typedef struct { + char *memstart; //start of memory region + char *memend; //end of memory region + char *textstart; //start of text to output + char *textend; +} usbdc_testament_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_crc.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_crc.h new file mode 100644 index 00000000..39787ed1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_crc.h @@ -0,0 +1,124 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** Notes about CRC API + * The ESP32 ROM include some CRC tables and CRC APIs to speed up CRC calculation. + * The CRC APIs include CRC8, CRC16, CRC32 algorithms for both little endian and big endian modes. + * Here are the polynomials for the algorithms: + * CRC-8 x8+x2+x1+1 0x07 + * CRC16-CCITT x16+x12+x5+1 0x1021 + * CRC32 x32+x26+x23+x22+x16+x12+x11+x10+x8+x7+x5+x4+x2+x1+1 0x04c11db7 + * + * These group of CRC APIs are designed to calculate the data in buffers either continuous or not. + * To make it easy, we had added a `~` at the beginning and the end of the functions. + * To calculate non-continuous buffers, we can write the code like this: + * init = ~init; + * crc = crc32_le(init, buf0, length0); + * crc = crc32_le(crc, buf1, length1); + * crc = ~crc; + * + * However, it is not easy to select which API to use and give the correct parameters. + * A specific CRC algorithm will include this parameters: width, polynomials, init, refin, refout, xorout + * refin and refout show the endian of the algorithm: + * if both of them are true, please use the little endian API. + * if both of them are false, please use the big endian API. + * xorout is the value which you need to be xored to the raw result. + * However, these group of APIs need one '~' before and after the APIs. + * + * Here are some examples for CRC16: + * CRC-16/CCITT, poly = 0x1021, init = 0x0000, refin = true, refout = true, xorout = 0x0000 + * crc = ~crc16_le((uint16_t)~0x0000, buf, length); + * + * CRC-16/CCITT-FALSE, poly = 0x1021, init = 0xffff, refin = false, refout = false, xorout = 0x0000 + * crc = ~crc16_be((uint16_t)~0xffff, buf, length); + * + * CRC-16/X25, poly = 0x1021, init = 0xffff, refin = true, refout = true, xorout = 0xffff + * crc = (~crc16_le((uint16_t)~(0xffff), buf, length))^0xffff; + * + * CRC-16/XMODEM, poly= 0x1021, init = 0x0000, refin = false, refout = false, xorout = 0x0000 + * crc = ~crc16_be((uint16_t)~0x0000, buf, length); + * + */ + +/** + * @brief CRC32 value in little endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC32 value + */ +uint32_t esp_rom_crc32_le(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC32 value in big endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC32 value + */ +uint32_t esp_rom_crc32_be(uint32_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC16 value in little endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC16 value + */ +uint16_t esp_rom_crc16_le(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC16 value in big endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC16 value + */ +uint16_t esp_rom_crc16_be(uint16_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC8 value in little endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC8 value + */ +uint8_t esp_rom_crc8_le(uint8_t crc, uint8_t const *buf, uint32_t len); + +/** + * @brief CRC8 value in big endian. + * + * @param crc: Initial CRC value (result of last calculation or 0 for the first time) + * @param buf: Data buffer that used to calculate the CRC value + * @param len: Length of the data buffer + * @return CRC8 value + */ +uint8_t esp_rom_crc8_be(uint8_t crc, uint8_t const *buf, uint32_t len); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_efuse.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_efuse.h new file mode 100644 index 00000000..907e175e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_efuse.h @@ -0,0 +1,68 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#define ESP_ROM_EFUSE_FLASH_DEFAULT_SPI (0) +#define ESP_ROM_EFUSE_FLASH_DEFAULT_HSPI (1) + +/** + * @brief A CRC8 algorithm used for MAC addresses stored in eFuse + * + * @param data Pointer to the original data + * @param len Data length in byte + * @return uint8_t CRC value + */ +uint8_t esp_rom_efuse_mac_address_crc8(const uint8_t *data, uint32_t len); + +/** + * @brief Get SPI Flash GPIO pin configurations from eFuse + * + * @return uint32_t + * - 0: default SPI pins (ESP_ROM_EFUSE_FLASH_DEFAULT_SPI) + * - 1: default HSPI pins (ESP_ROM_EFUSE_FLASH_DEFAULT_HSPI) + * - Others: Customized pin configuration mask. Pins are encoded as per the + * EFUSE_SPICONFIG_RET_SPICLK, EFUSE_SPICONFIG_RET_SPIQ, EFUSE_SPICONFIG_RET_SPID, + * EFUSE_SPICONFIG_RET_SPICS0, EFUSE_SPICONFIG_RET_SPIHD macros. + * + * @note WP pin (for quad I/O modes) is not saved in eFuse and not returned by this function. + */ +uint32_t esp_rom_efuse_get_flash_gpio_info(void); + +/** + * @brief Get SPI Flash WP pin information from eFuse + * + * @return uint32_t + * - 0x3F: invalid GPIO number + * - 0~46: valid GPIO number + */ +uint32_t esp_rom_efuse_get_flash_wp_gpio(void); + +/** + * @brief Read eFuse to check whether secure boot has been enabled or not + * + * @return true if secure boot is enabled, otherwise false + */ +bool esp_rom_efuse_is_secure_boot_enabled(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_gpio.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_gpio.h new file mode 100644 index 00000000..ce4bb765 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_gpio.h @@ -0,0 +1,87 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/gpio_pins.h" //for GPIO_MATRIX_CONST_ONE_INPUT, GPIO_MATRIX_CONST_ZERO_INPUT + +/** + * @brief Configure IO Pad as General Purpose IO, + * so that it can be connected to internal Matrix, + * then combined with one or more peripheral signals. + * + * @param iopad_num IO Pad number + */ +void esp_rom_gpio_pad_select_gpio(uint32_t iopad_num); + +/** + * @brief Enable internal pull up, and disable internal pull down. + * + * @param iopad_num IO Pad number + */ +void esp_rom_gpio_pad_pullup_only(uint32_t iopad_num); + +/** + * @brief Unhold the IO Pad. + * @note When the Pad is set to hold, the state is latched at that moment and won't get changed. + * + * @param iopad_num IP Pad number + */ +void esp_rom_gpio_pad_unhold(uint32_t gpio_num); + +/** + * @brief Set IO Pad current drive capability. + * + * @param iopad_num IO Pad number + * @param drv Numeric to indicate the capability of current drive + * - 0: 5mA + * - 1: 10mA + * - 2: 20mA + * - 3: 40mA + */ +void esp_rom_gpio_pad_set_drv(uint32_t iopad_num, uint32_t drv); + +/** + * @brief Combine a GPIO input with a peripheral signal, which tagged as input attribute. + * + * @note There's no limitation on the number of signals that a GPIO can combine with. + * + * @param gpio_num GPIO number, especially, `GPIO_MATRIX_CONST_ZERO_INPUT` means connect logic 0 to signal + * `GPIO_MATRIX_CONST_ONE_INPUT` means connect logic 1 to signal + * @param signal_idx Peripheral signal index (tagged as input attribute) + * @param inv Whether the GPIO input to be inverted or not + */ +void esp_rom_gpio_connect_in_signal(uint32_t gpio_num, uint32_t signal_idx, bool inv); + +/** + * @brief Combine a peripheral signal which tagged as output attribute with a GPIO. + * + * @note There's no limitation on the number of signals that a GPIO can combine with. + * + * @param gpio_num GPIO number + * @param signal_idx Peripheral signal index (tagged as output attribute) + * @param out_inv Whether to signal to be inverted or not + * @param oen_inv Whether the output enable control is inverted or not + */ +void esp_rom_gpio_connect_out_signal(uint32_t gpio_num, uint32_t signal_idx, bool out_inv, bool oen_inv); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_md5.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_md5.h new file mode 100644 index 00000000..5bb71f3e --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_md5.h @@ -0,0 +1,63 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * The MD5 functions calculate a 128-bit cryptographic digest for any number of input bytes. + */ + +/** + * @brief Type defined for MD5 context + * + */ +typedef struct MD5Context { + uint32_t buf[4]; + uint32_t bits[2]; + uint8_t in[64]; +} md5_context_t; + +/** + * @brief Initialize the MD5 context + * + * @param context Context object allocated by user + */ +void esp_rom_md5_init(md5_context_t *context); + +/** + * @brief Running MD5 algorithm over input data + * + * @param context MD5 context which has been initialized by `MD5Init` + * @param buf Input buffer + * @param len Buffer length + */ +void esp_rom_md5_update(md5_context_t *context, const uint8_t *buf, uint32_t len); + +/** + * @brief Extract the MD5 result, and erase the context + * + * @param digest Where to store the 128-bit digest value + * @param context MD5 context + */ +void esp_rom_md5_final(uint8_t digest[16], md5_context_t *context); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_sys.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_sys.h new file mode 100644 index 00000000..a5b01ade --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_sys.h @@ -0,0 +1,56 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * @brief Print formated string to console device + * @note float and long long data are not supported! + * + * @param fmt Format string + * @param ... Additional arguments, depending on the format string + * @return int: Total number of characters written on success; A negative number on failure. + */ +int esp_rom_printf(const char *fmt, ...); + +/** + * @brief Pauses execution for us microseconds + * + * @param us Number of microseconds to pause + */ +void esp_rom_delay_us(uint32_t us); + +/** + * @brief esp_rom_printf can print message to different channels simultaneously. + * This function can help install the low level putc function for esp_rom_printf. + * + * @param channel Channel number (startting from 1) + * @param putc Function pointer to the putc implementation. Set NULL can disconnect esp_rom_printf with putc. + */ +void esp_rom_install_channel_putc(int channel, void (*putc)(char c)); + +/** + * @brief Install UART1 as the default console channel, equivalent to `esp_rom_install_channel_putc(1, esp_rom_uart_putc)` + */ +void esp_rom_install_uart_printf(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_uart.h b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_uart.h new file mode 100644 index 00000000..a07740c1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_rom/include/esp_rom_uart.h @@ -0,0 +1,109 @@ +// Copyright 2010-2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#define ESP_ROM_CDC_ACM_WORK_BUF_MIN 128 + +typedef enum { + ESP_ROM_UART_0, + ESP_ROM_UART_1, + ESP_ROM_UART_USB +} esp_rom_uart_num_t; + +/** + * @brief Wait for UART TX FIFO is empty and all data has been sent out. + * + * @param uart_no UART port number + */ +void esp_rom_uart_tx_wait_idle(uint8_t uart_no); + +/** + * @brief Set clock source and baud rate for UART. + * + * @param uart_no UART port number + * @param clock_hz Source clock (in Hz) + * @param baud_rate Baud rate to set + */ +void esp_rom_uart_set_clock_baudrate(uint8_t uart_no, uint32_t clock_hz, uint32_t baud_rate); + +/** + * @brief Wait until UART TX FIFO is empty (i.e. flush TX FIFO) + * + * @param uart_no UART port number + */ +void esp_rom_uart_flush_tx(uint8_t uart_no); + +/** + * @brief Transmit one character to the console channel. + * + * @param c Character to send + * @return + * - 0 on success + * - 1 on failure + */ +int esp_rom_uart_tx_one_char(uint8_t c); + +/** + * @brief Transmit one character to the console channel. + * @note This function is a wrapper over esp_rom_uart_tx_one_char, it can help handle line ending issue by replacing '\n' with '\r\n'. + * + * @param c Character to send + */ +void esp_rom_uart_putc(char c); + +/** + * @brief Get one character from the console channel. + * + * @param c Where to store the character + * @return + * - 0 on success + * - 1 on failure or no data available + */ +int esp_rom_uart_rx_one_char(uint8_t *c); + +/** + * @brief Get one line of string from console channel (line ending won't be stored in the buffer). + * + * @param str Where to store the string + * @param max_len Maximum length of the buffer (including the NULL delimiter) + * @return always return 0 when on success or wait in a loop for rx data + */ +int esp_rom_uart_rx_string(uint8_t *str, uint8_t max_len); + +/** + * @brief Set the UART port used by ets_printf. + * + * @param uart_no UART port number + */ +void esp_rom_uart_set_as_console(uint8_t uart_no); + +/** + * @brief Initialize the USB ACM UART + * @note The ACM working memroy should be at least 128 bytes (ESP_ROM_CDC_ACM_WORK_BUF_MIN) in size. + * + * @param cdc_acm_work_mem Pointer to the work memroy used for CDC-ACM + * @param cdc_acm_work_mem_len Length of work memory + */ +void esp_rom_uart_usb_acm_init(void *cdc_acm_work_mem, int cdc_acm_work_mem_len); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl.h new file mode 100644 index 00000000..82e91778 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl.h @@ -0,0 +1,212 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "sdmmc_cmd.h" +#include "driver/spi_master.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + + +#define ESP_ERR_NOT_FINISHED 0x201 ///< There is still remaining data. + +struct essl_dev_t; +/// Handle of an ESSL device +typedef struct essl_dev_t* essl_handle_t; + +/** + * @brief Initialize the slave. + * + * @param handle Handle of a ``essl`` device. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * @return ESP_OK if success, or other value returned from lower layer `init`. + */ +esp_err_t essl_init(essl_handle_t handle, uint32_t wait_ms); + +/** Wait for interrupt of a ESP32 slave device. + * + * @param handle Handle of a ``essl`` device. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK if success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_wait_for_ready(essl_handle_t handle, uint32_t wait_ms); + +/** Get buffer num for the host to send data to the slave. The buffers are size of ``buffer_size``. + * + * @param handle Handle of a ``essl`` device. + * @param out_tx_num Output of buffer num that host can send data to ESP32 slave. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_get_tx_buffer_num(essl_handle_t handle, uint32_t *out_tx_num, uint32_t wait_ms); + +/** Get amount of data the ESP32 slave preparing to send to host. + * + * @param handle Handle of a ``essl`` device. + * @param out_rx_size Output of data size to read from slave. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_get_rx_data_size(essl_handle_t handle, uint32_t *out_rx_size, uint32_t wait_ms); + + +/** Reset the counters of this component. Usually you don't need to do this unless you know the slave is reset. + * + * @param handle Handle of a ``essl`` device. + */ +esp_err_t essl_reset_cnt(essl_handle_t handle); + +/** Send a packet to the ESP32 slave. The slave receive the packet into buffers whose size is ``buffer_size`` (configured during initialization). + * + * @param handle Handle of a ``essl`` device. + * @param start Start address of the packet to send + * @param length Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - ESP_ERR_TIMEOUT No buffer to use, or error ftrom SDMMC host controller + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_send_packet(essl_handle_t handle, const void *start, size_t length, uint32_t wait_ms); + +/** Get a packet from ESP32 slave. + * + * @param handle Handle of a ``essl`` device. + * @param[out] out_data Data output address + * @param size The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ``ESP_ERR_NOT_FINISHED`` + * @param[out] out_length Output of length the data actually received from slave. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success, all the data are read from the slave. + * - ESP_ERR_NOT_FINISHED Read success, while there're data remaining. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_get_packet(essl_handle_t handle, void *out_data, size_t size, size_t *out_length, uint32_t wait_ms); + +/** Write general purpose R/W registers (8-bit) of ESP32 slave. + * + * @param handle Handle of a ``essl`` device. + * @param addr Address of register to write. Valid address: 0-59. + * @param value Value to write to the register. + * @param value_o Output of the returned written value. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @note sdio 28-31 are reserved, the lower API helps to skip. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Address not valid. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_write_reg(essl_handle_t handle, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t wait_ms); + +/** Read general purpose R/W registers (8-bit) of ESP32 slave. + * + * @param handle Handle of a ``essl`` device. + * @param add Address of register to read. Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). + * @param value_o Output value read from the register. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Address not valid. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_read_reg(essl_handle_t handle, uint8_t add, uint8_t *value_o, uint32_t wait_ms); + +/** wait for an interrupt of the slave + * + * @param handle Handle of a ``essl`` device. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_ERR_NOT_SUPPORTED Currently our driver doesnot support SDIO with SPI interface. + * - ESP_OK If interrupt triggered. + * - ESP_ERR_TIMEOUT No interrupts before timeout. + */ +esp_err_t essl_wait_int(essl_handle_t handle, uint32_t wait_ms); + +/** Clear interrupt bits of ESP32 slave. All the bits set in the mask will be cleared, while other bits will stay the same. + * + * @param handle Handle of a ``essl`` device. + * @param intr_mask Mask of interrupt bits to clear. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_clear_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms); + +/** Get interrupt bits of ESP32 slave. + * + * @param handle Handle of a ``essl`` device. + * @param intr_raw Output of the raw interrupt bits. Set to NULL if only masked bits are read. + * @param intr_st Output of the masked interrupt bits. set to NULL if only raw bits are read. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - ESP_INVALID_ARG if both ``intr_raw`` and ``intr_st`` are NULL. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_get_intr(essl_handle_t handle, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms); + +/** Set interrupt enable bits of ESP32 slave. The slave only sends interrupt on the line when there is a bit both the raw status and the enable are set. + * + * @param handle Handle of a ``essl`` device. + * @param ena_mask Mask of the interrupt bits to enable. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_set_intr_ena(essl_handle_t handle, uint32_t ena_mask, uint32_t wait_ms); + +/** Get interrupt enable bits of ESP32 slave. + * + * @param handle Handle of a ``essl`` device. + * @param ena_mask_o Output of interrupt bit enable mask. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_get_intr_ena(essl_handle_t handle, uint32_t *ena_mask_o, uint32_t wait_ms); + +/** Send interrupts to slave. Each bit of the interrupt will be triggered. + * + * @param handle Handle of a ``essl`` device. + * @param intr_mask Mask of interrupt bits to send to slave. + * @param wait_ms Millisecond to wait before timeout, will not wait at all if set to 0-9. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_send_slave_intr(essl_handle_t handle, uint32_t intr_mask, uint32_t wait_ms); diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_sdio.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_sdio.h new file mode 100644 index 00000000..93fa2823 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_sdio.h @@ -0,0 +1,248 @@ +// Copyright 2015-2019 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. + +// ESP SDIO slave link used by the ESP host to communicate with ESP32 SDIO slave. + +#pragma once + +#include "esp_err.h" +#include "esp_serial_slave_link/essl.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "driver/sdmmc_defs.h" + +/// Configuration for the essl SDIO device +typedef struct { + sdmmc_card_t *card; ///< The initialized sdmmc card pointer of the slave. + int recv_buffer_size; ///< The pre-negotiated recv buffer size used by both the host and the slave. +} essl_sdio_config_t; + +/** + * @brief Initialize the ESSL SDIO device and get its handle. + * + * @param out_handle Output of the handle. + * @param config Configuration for the ESSL SDIO device. + * @return + * - ESP_OK: on success + * - ESP_ERR_NO_MEM: memory exhausted. + */ +esp_err_t essl_sdio_init_dev(essl_handle_t *out_handle, const essl_sdio_config_t *config); + +/** + * @brief Deinitialize and free the space used by the ESSL SDIO device. + * + * @param handle Handle of the ESSL SDIO device to deinit. + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_ARG: wrong handle passed + */ +esp_err_t essl_sdio_deinit_dev(essl_handle_t handle); + +//Please call `essl_` functions witout `sdio` instead of calling these functions directly. +/** @cond */ +/** + * SDIO Initialize process of a ESP32 slave device. + * + * @param arg Context of the ``essl`` component. Send to other functions later. + * @param wait_ms Time to wait before operation is done, in ms. + * + * @return + * - ESP_OK if success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_init(void *arg, uint32_t wait_ms); + +/** + * Wait for interrupt of a ESP32 slave device. + * + * @param arg Context of the ``essl`` component. + * @param wait_ms Time to wait before operation is done, in ms. + * + * @return + * - ESP_OK if success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_wait_for_ready(void *arg, uint32_t wait_ms); + +/** + * Get buffer num for the host to send data to the slave. The buffers are size of ``buffer_size``. + * + * @param arg Context of the component. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +uint32_t essl_sdio_get_tx_buffer_num(void *arg); + +/** Get amount of data the ESP32 slave preparing to send to host. + * + * @param arg Context of the component. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +uint32_t essl_sdio_get_rx_data_size(void *arg); + +/** + * Send a packet to the ESP32 slave. The slave receive the packet into buffers whose size is ``buffer_size`` in the arg. + * + * @param arg Context of the component. + * @param start Start address of the packet to send + * @param length Length of data to send, if the packet is over-size, the it will be divided into blocks and hold into different buffers automatically. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - ESP_ERR_TIMEOUT No buffer to use, or error ftrom SDMMC host controller + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_send_packet(void *arg, const void *start, size_t length, uint32_t wait_ms); + +/** + * Get a packet from ESP32 slave. + * + * @param arg Context of the component. + * @param[out] out_data Data output address + * @param size The size of the output buffer, if the buffer is smaller than the size of data to receive from slave, the driver returns ``ESP_ERR_NOT_FINISHED`` + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success, all the data are read from the slave. + * - ESP_ERR_NOT_FINISHED Read success, while there're data remaining. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_get_packet(void *arg, void *out_data, size_t size, uint32_t wait_ms); + +/** + * Wait for the interrupt from the SDIO slave. + * + * @param arg Context of the component. + * @param wait_ms Time to wait before timeout, in ms. + * @return + * - ESP_ERR_NOT_SUPPORTED: if the interrupt line is not initialized properly. + * - ESP_OK: if interrupt happened + * - ESP_ERR_TIMEOUT: if timeout before interrupt happened. + * - or other values returned from the `io_int_wait` member of the `card->host` structure. + */ +esp_err_t essl_sdio_wait_int(void *arg, uint32_t wait_ms); + +/** + * Clear interrupt bits of ESP32 slave. All the bits set in the mask will be cleared, while other bits will stay the same. + * + * @param arg Context of the component. + * @param intr_mask Mask of interrupt bits to clear. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_clear_intr(void *arg, uint32_t intr_mask, uint32_t wait_ms); + +/** + * Get interrupt bits of ESP32 slave. + * + * @param arg Context of the component. + * @param intr_raw Output of the raw interrupt bits. Set to NULL if only masked bits are read. + * @param intr_st Output of the masked interrupt bits. set to NULL if only raw bits are read. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - ESP_INVALID_ARG if both ``intr_raw`` and ``intr_st`` are NULL. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_get_intr(void *arg, uint32_t *intr_raw, uint32_t *intr_st, uint32_t wait_ms); + +/** + * Set interrupt enable bits of ESP32 slave. The slave only sends interrupt on the line when there is a bit both the raw status and the enable are set. + * + * @param arg Context of the component. + * @param ena_mask Mask of the interrupt bits to enable. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_set_intr_ena(void *arg, uint32_t ena_mask, uint32_t wait_ms); + +/** + * Get interrupt enable bits of ESP32 slave. + * + * @param arg Context of the component. + * @param ena_mask_o Output of interrupt bit enable mask. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_get_intr_ena(void *arg, uint32_t *ena_mask_o, uint32_t wait_ms); + +/** + * Write general purpose R/W registers (8-bit) of ESP32 slave. + * + * @param arg Context of the component. + * @param addr Address of register to write. Valid address: 0-27, 32-63 (28-31 reserved). + * @param value Value to write to the register. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Address not valid. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_write_reg(void *arg, uint8_t addr, uint8_t value, uint8_t *value_o, uint32_t wait_ms); + +/** + * Read general purpose R/W registers (8-bit) of ESP32 slave. + * + * @param arg Context of the component. + * @param add Address of register to read. Valid address: 0-27, 32-63 (28-31 reserved, return interrupt bits on read). + * @param value Output value read from the register. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Address not valid. + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_read_reg(void *arg, uint8_t add, uint8_t *value_o, uint32_t wait_ms); + +/** + * Send interrupts to slave. Each bit of the interrupt will be triggered. + * + * @param arg Context of the component. + * @param intr_mask Mask of interrupt bits to send to slave. + * @param wait_ms Time to wait before timeout, in ms. + * + * @return + * - ESP_OK Success + * - One of the error codes from SDMMC host controller + */ +esp_err_t essl_sdio_send_slave_intr(void *arg, uint32_t intr_mask, uint32_t wait_ms); + +/** + * @brief Reset the counter on the host side. + * + * @note Only call when you know the slave has reset its counter, or there will be inconsistent between the master and the slave. + * + * @param arg Context of the component. + */ +void essl_sdio_reset_cnt(void *arg); + +/** @endcond */ diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_spi.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_spi.h new file mode 100644 index 00000000..b7889100 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/esp_serial_slave_link/essl_spi.h @@ -0,0 +1,165 @@ +// Copyright 2010-2020 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. + +#pragma once + +#include "esp_err.h" +#include "esp_serial_slave_link/essl.h" + + +#ifdef __cplusplus +extern "C" +{ +#endif + +//////////////////////////////////////////////////////////////////////////////// +// Basic commands to communicate with the SPI Slave HD on ESP32-S2 +//////////////////////////////////////////////////////////////////////////////// + +/** + * @brief Read the shared buffer from the slave. + * + * @note ``out_data`` should be prepared in words and in the DRAM. The buffer may be written in words + * by the DMA. When a byte is written, the remaining bytes in the same word will also be + * overwritten, even the ``len`` is shorter than a word. + * + * @param spi SPI device handle representing the slave + * @param out_data Buffer for read data, strongly suggested to be in the DRAM and align to 4 + * @param addr Address of the slave shared buffer + * @param len Length to read + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: on success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_rdbuf(spi_device_handle_t spi, uint8_t *out_data, int addr, int len, uint32_t flags); + +/** + * @brief Write the shared buffer of the slave. + * + * @note ``out_data`` should be prepared in words and in the DRAM. The buffer may be written in words + * by the DMA. When a byte is written, the remaining bytes in the same word will also be + * overwritten, even the ``len`` is shorter than a word. + * + * @param spi SPI device handle representing the slave + * @param data Buffer for data to send, strongly suggested to be in the DRAM and align to 4 + * @param addr Address of the slave shared buffer, + * @param len Length to write + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_wrbuf(spi_device_handle_t spi, const uint8_t *data, int addr, int len, uint32_t flags); + +/** + * @brief Receive long buffer in segments from the slave through its DMA. + * + * @note This function combines several :cpp:func:`essl_spi_rddma_seg` and one + * :cpp:func:`essl_spi_rddma_done` at the end. Used when the slave is working in segment mode. + * + * @param spi SPI device handle representing the slave + * @param out_data Buffer to hold the received data, strongly suggested to be in the DRAM and align to 4 + * @param len Total length of data to receive. + * @param seg_len Length of each segment, which is not larger than the maximum transaction length + * allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send + * all data in one segment (the ``rddma_done`` will still be sent.) + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_rddma(spi_device_handle_t spi, uint8_t *out_data, int len, int seg_len, uint32_t flags); + +/** + * @brief Read one data segment from the slave through its DMA. + * + * @note To read long buffer, call :cpp:func:`essl_spi_rddma` instead. + * + * @param spi SPI device handle representing the slave + * @param out_data Buffer to hold the received data, strongly suggested to be in the DRAM and align to 4 + * @param seg_len Length of this segment + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_rddma_seg(spi_device_handle_t spi, uint8_t *out_data, int seg_len, uint32_t flags); + +/** + * @brief Send the ``rddma_done`` command to the slave. Upon receiving this command, the slave will + * stop sending the current buffer even there are data unsent, and maybe prepare the next buffer to + * send. + * + * @note This is required only when the slave is working in segment mode. + * + * @param spi SPI device handle representing the slave + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_rddma_done(spi_device_handle_t spi, uint32_t flags); + +/** + * @brief Send long buffer in segments to the slave through its DMA. + * + * @note This function combines several :cpp:func:`essl_spi_wrdma_seg` and one + * :cpp:func:`essl_spi_wrdma_done` at the end. Used when the slave is working in segment mode. + * + * @param spi SPI device handle representing the slave + * @param data Buffer for data to send, strongly suggested to be in the DRAM and align to 4 + * @param len Total length of data to send. + * @param seg_len Length of each segment, which is not larger than the maximum transaction length + * allowed for the spi device. Suggested to be multiples of 4. When set < 0, means send + * all data in one segment (the ``wrdma_done`` will still be sent.) + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_wrdma(spi_device_handle_t spi, const uint8_t *data, int len, int seg_len, uint32_t flags); + +/** + * @brief Send one data segment to the slave through its DMA. + * + * @note To send long buffer, call :cpp:func:`essl_spi_wrdma` instead. + * + * @param spi SPI device handle representing the slave + * @param data Buffer for data to send, strongly suggested to be in the DRAM and align to 4 + * @param seg_len Length of this segment + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_wrdma_seg(spi_device_handle_t spi, const uint8_t *data, int seg_len, uint32_t flags); + +/** + * @brief Send the ``wrdma_done`` command to the slave. Upon receiving this command, the slave will + * stop receiving, process the received data, and maybe prepare the next buffer to receive. + * + * @note This is required only when the slave is working in segment mode. + * + * @param spi SPI device handle representing the slave + * @param flags `SPI_TRANS_*` flags to control the transaction mode of the transaction to send. + * @return + * - ESP_OK: success + * - or other return value from :cpp:func:`spi_device_transmit`. + */ +esp_err_t essl_spi_wrdma_done(spi_device_handle_t spi, uint32_t flags); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32c3_defs.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32c3_defs.h new file mode 100644 index 00000000..3dfd4a14 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32c3_defs.h @@ -0,0 +1,38 @@ +// Copyright 2010-2020 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. + + +#pragma once + +// NOTE: From the view of master +#define CMD_HD_WRBUF_REG 0x01 +#define CMD_HD_RDBUF_REG 0x02 +#define CMD_HD_WRDMA_REG 0x03 +#define CMD_HD_RDDMA_REG 0x04 + +#define CMD_HD_ONEBIT_MODE 0x00 +#define CMD_HD_DOUT_MODE 0x10 +#define CMD_HD_QOUT_MODE 0x20 +#define CMD_HD_DIO_MODE 0x50 +#define CMD_HD_QIO_MODE 0xA0 + +#define CMD_HD_SEG_END_REG 0x05 +#define CMD_HD_EN_QPI_REG 0x06 +#define CMD_HD_WR_END_REG 0x07 +#define CMD_HD_INT0_REG 0x08 +#define CMD_HD_INT1_REG 0x09 +#define CMD_HD_INT2_REG 0x0A +#define CMD_HD_EX_QPI_REG 0xDD + +#define SPI_SLAVE_HD_BUFFER_SIZE 64 diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s2_defs.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s2_defs.h new file mode 100644 index 00000000..49ba82dd --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s2_defs.h @@ -0,0 +1,38 @@ +// Copyright 2010-2020 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. + + +#pragma once + +// NOTE: From the view of master +#define CMD_HD_WRBUF_REG 0x01 +#define CMD_HD_RDBUF_REG 0x02 +#define CMD_HD_WRDMA_REG 0x03 +#define CMD_HD_RDDMA_REG 0x04 + +#define CMD_HD_ONEBIT_MODE 0x00 +#define CMD_HD_DOUT_MODE 0x10 +#define CMD_HD_QOUT_MODE 0x20 +#define CMD_HD_DIO_MODE 0x50 +#define CMD_HD_QIO_MODE 0xA0 + +#define CMD_HD_SEG_END_REG 0x05 +#define CMD_HD_EN_QPI_REG 0x06 +#define CMD_HD_WR_END_REG 0x07 +#define CMD_HD_INT0_REG 0x08 +#define CMD_HD_INT1_REG 0x09 +#define CMD_HD_INT2_REG 0x0A +#define CMD_HD_EX_QPI_REG 0xDD + +#define SPI_SLAVE_HD_BUFFER_SIZE 72 diff --git a/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s3_defs.h b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s3_defs.h new file mode 100644 index 00000000..3dfd4a14 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_serial_slave_link/include/essl_spi/esp32s3_defs.h @@ -0,0 +1,38 @@ +// Copyright 2010-2020 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. + + +#pragma once + +// NOTE: From the view of master +#define CMD_HD_WRBUF_REG 0x01 +#define CMD_HD_RDBUF_REG 0x02 +#define CMD_HD_WRDMA_REG 0x03 +#define CMD_HD_RDDMA_REG 0x04 + +#define CMD_HD_ONEBIT_MODE 0x00 +#define CMD_HD_DOUT_MODE 0x10 +#define CMD_HD_QOUT_MODE 0x20 +#define CMD_HD_DIO_MODE 0x50 +#define CMD_HD_QIO_MODE 0xA0 + +#define CMD_HD_SEG_END_REG 0x05 +#define CMD_HD_EN_QPI_REG 0x06 +#define CMD_HD_WR_END_REG 0x07 +#define CMD_HD_INT0_REG 0x08 +#define CMD_HD_INT1_REG 0x09 +#define CMD_HD_INT2_REG 0x0A +#define CMD_HD_EX_QPI_REG 0xDD + +#define SPI_SLAVE_HD_BUFFER_SIZE 64 diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_async_memcpy.h b/tools/sdk/esp32c3/include/esp_system/include/esp_async_memcpy.h new file mode 100644 index 00000000..67194e44 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_async_memcpy.h @@ -0,0 +1,115 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "esp_err.h" + +/** + * @brief Type of async memcpy handle + * + */ +typedef struct async_memcpy_context_t *async_memcpy_t; + +/** + * @brief Type of async memcpy event object + * + */ +typedef struct { + void *data; /*!< Event data */ +} async_memcpy_event_t; + +/** + * @brief Type of async memcpy interrupt callback function + * + * @param mcp_hdl Handle of async memcpy + * @param event Event object, which contains related data, reserved for future + * @param cb_args User defined arguments, passed from esp_async_memcpy function + * @return Whether a high priority task is woken up by the callback function + * + * @note User can call OS primitives (semaphore, mutex, etc) in the callback function. + * Keep in mind, if any OS primitive wakes high priority task up, the callback should return true. + */ +typedef bool (*async_memcpy_isr_cb_t)(async_memcpy_t mcp_hdl, async_memcpy_event_t *event, void *cb_args); + +/** + * @brief Type of async memcpy configuration + * + */ +typedef struct { + uint32_t backlog; /*!< Maximum number of streams that can be handled simultaneously */ + uint32_t flags; /*!< Extra flags to control async memcpy feature */ +} async_memcpy_config_t; + +/** + * @brief Default configuration for async memcpy + * + */ +#define ASYNC_MEMCPY_DEFAULT_CONFIG() \ + { \ + .backlog = 8, \ + .flags = 0, \ + } + +/** + * @brief Install async memcpy driver + * + * @param[in] config Configuration of async memcpy + * @param[out] asmcp Handle of async memcpy that returned from this API. If driver installation is failed, asmcp would be assigned to NULL. + * @return + * - ESP_OK: Install async memcpy driver successfully + * - ESP_ERR_INVALID_ARG: Install async memcpy driver failed because of invalid argument + * - ESP_ERR_NO_MEM: Install async memcpy driver failed because out of memory + * - ESP_FAIL: Install async memcpy driver failed because of other error + */ +esp_err_t esp_async_memcpy_install(const async_memcpy_config_t *config, async_memcpy_t *asmcp); + +/** + * @brief Uninstall async memcpy driver + * + * @param[in] asmcp Handle of async memcpy driver that returned from esp_async_memcpy_install + * @return + * - ESP_OK: Uninstall async memcpy driver successfully + * - ESP_ERR_INVALID_ARG: Uninstall async memcpy driver failed because of invalid argument + * - ESP_FAIL: Uninstall async memcpy driver failed because of other error + */ +esp_err_t esp_async_memcpy_uninstall(async_memcpy_t asmcp); + +/** + * @brief Send an asynchronous memory copy request + * + * @param[in] asmcp Handle of async memcpy driver that returned from esp_async_memcpy_install + * @param[in] dst Destination address (copy to) + * @param[in] src Source address (copy from) + * @param[in] n Number of bytes to copy + * @param[in] cb_isr Callback function, which got invoked in interrupt context. Set to NULL can bypass the callback. + * @param[in] cb_args User defined argument to be passed to the callback function + * @return + * - ESP_OK: Send memory copy request successfully + * - ESP_ERR_INVALID_ARG: Send memory copy request failed because of invalid argument + * - ESP_FAIL: Send memory copy request failed because of other error + * + * @note The callback function is invoked in interrupt context, never do blocking jobs in the callback. + */ +esp_err_t esp_async_memcpy(async_memcpy_t asmcp, void *dst, void *src, size_t n, async_memcpy_isr_cb_t cb_isr, void *cb_args); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_debug_helpers.h b/tools/sdk/esp32c3/include/esp_system/include/esp_debug_helpers.h new file mode 100644 index 00000000..a802cb40 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_debug_helpers.h @@ -0,0 +1,122 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef __ASSEMBLER__ + +#include +#include "esp_err.h" +#include "soc/soc.h" // [refactor-todo] IDF-2297 +#include "esp_cpu.h" + +/* + * @brief Structure used for backtracing + * + * This structure stores the backtrace information of a particular stack frame + * (i.e. the PC and SP). This structure is used iteratively with the + * esp_cpu_get_next_backtrace_frame() function to traverse each frame within a + * single stack. The next_pc represents the PC of the current frame's caller, thus + * a next_pc of 0 indicates that the current frame is the last frame on the stack. + * + * @note Call esp_backtrace_get_start() to obtain initialization values for + * this structure + */ +typedef struct { + uint32_t pc; /* PC of the current frame */ + uint32_t sp; /* SP of the current frame */ + uint32_t next_pc; /* PC of the current frame's caller */ +} esp_backtrace_frame_t; + +/** + * @brief If an OCD is connected over JTAG. set breakpoint 0 to the given function + * address. Do nothing otherwise. + * @param fn Pointer to the target breakpoint position + */ +void esp_set_breakpoint_if_jtag(void *fn); + +/** + * Get the first frame of the current stack's backtrace + * + * Given the following function call flow (B -> A -> X -> esp_backtrace_get_start), + * this function will do the following. + * - Flush CPU registers and window frames onto the current stack + * - Return PC and SP of function A (i.e. start of the stack's backtrace) + * - Return PC of function B (i.e. next_pc) + * + * @note This function is implemented in assembly + * + * @param[out] pc PC of the first frame in the backtrace + * @param[out] sp SP of the first frame in the backtrace + * @param[out] next_pc PC of the first frame's caller + */ +extern void esp_backtrace_get_start(uint32_t *pc, uint32_t *sp, uint32_t *next_pc); + +/** + * Get the next frame on a stack for backtracing + * + * Given a stack frame(i), this function will obtain the next stack frame(i-1) + * on the same call stack (i.e. the caller of frame(i)). This function is meant to be + * called iteratively when doing a backtrace. + * + * Entry Conditions: Frame structure containing valid SP and next_pc + * Exit Conditions: + * - Frame structure updated with SP and PC of frame(i-1). next_pc now points to frame(i-2). + * - If a next_pc of 0 is returned, it indicates that frame(i-1) is last frame on the stack + * + * @param[inout] frame Pointer to frame structure + * + * @return + * - True if the SP and PC of the next frame(i-1) are sane + * - False otherwise + */ +bool esp_backtrace_get_next_frame(esp_backtrace_frame_t *frame); + +/** + * @brief Print the backtrace of the current stack + * + * @param depth The maximum number of stack frames to print (should be > 0) + * + * @return + * - ESP_OK Backtrace successfully printed to completion or to depth limit + * - ESP_FAIL Backtrace is corrupted + */ +esp_err_t esp_backtrace_print(int depth); + +/** + * @brief Set a watchpoint to break/panic when a certain memory range is accessed. + * Superseded by esp_cpu_set_watchpoint in esp_cpu.h. + */ +static inline __attribute__((deprecated)) esp_err_t esp_set_watchpoint(int no, void *adr, int size, int flags) +{ + return esp_cpu_set_watchpoint(no, adr, size, flags); +} + +/** + * @brief Set a watchpoint to break/panic when a certain memory range is accessed. + * Superseded by esp_cpu_clear_watchpoint in esp_cpu.h. + */ +static inline __attribute__((deprecated)) void esp_clear_watchpoint(int no) +{ + esp_cpu_clear_watchpoint(no); +} + +#endif +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_expression_with_stack.h b/tools/sdk/esp32c3/include/esp_system/include/esp_expression_with_stack.h new file mode 100644 index 00000000..456e5db1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_expression_with_stack.h @@ -0,0 +1,49 @@ +// Copyright 2015-2019 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. +#pragma once + +#include +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "esp_debug_helpers.h" +#include "esp_log.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef void (*shared_stack_function)(void); + +#define ESP_EXECUTE_EXPRESSION_WITH_STACK(lock, stack, stack_size, expression) \ + esp_execute_shared_stack_function(lock, stack, stack_size, expression) + +/** + * @brief Calls user defined shared stack space function + * @param lock Mutex object to protect in case of shared stack + * @param stack Pointer to user alocated stack + * @param stack_size Size of current stack in bytes + * @param function pointer to the shared stack function to be executed + * @note if either lock, stack or stack size is invalid, the expression will + * be called using the current stack. + */ +void esp_execute_shared_stack_function(SemaphoreHandle_t lock, + void *stack, + size_t stack_size, + shared_stack_function function); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_freertos_hooks.h b/tools/sdk/esp32c3/include/esp_system/include/esp_freertos_hooks.h new file mode 100644 index 00000000..290d580b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_freertos_hooks.h @@ -0,0 +1,134 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_FREERTOS_HOOKS_H__ +#define __ESP_FREERTOS_HOOKS_H__ + +#include + +#include "freertos/portmacro.h" + +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* + Definitions for the tickhook and idlehook callbacks +*/ +typedef bool (*esp_freertos_idle_cb_t)(void); +typedef void (*esp_freertos_tick_cb_t)(void); + +/** + * @brief Register a callback to be called from the specified core's idle hook. + * The callback should return true if it should be called by the idle hook + * once per interrupt (or FreeRTOS tick), and return false if it should + * be called repeatedly as fast as possible by the idle hook. + * + * @warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL + * A FUNCTION THAT MIGHT BLOCK. + * + * @param[in] new_idle_cb Callback to be called + * @param[in] cpuid id of the core + * + * @return + * - ESP_OK: Callback registered to the specified core's idle hook + * - ESP_ERR_NO_MEM: No more space on the specified core's idle hook to register callback + * - ESP_ERR_INVALID_ARG: cpuid is invalid + */ +esp_err_t esp_register_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t new_idle_cb, UBaseType_t cpuid); + +/** + * @brief Register a callback to the idle hook of the core that calls this function. + * The callback should return true if it should be called by the idle hook + * once per interrupt (or FreeRTOS tick), and return false if it should + * be called repeatedly as fast as possible by the idle hook. + * + * @warning Idle callbacks MUST NOT, UNDER ANY CIRCUMSTANCES, CALL + * A FUNCTION THAT MIGHT BLOCK. + * + * @param[in] new_idle_cb Callback to be called + * + * @return + * - ESP_OK: Callback registered to the calling core's idle hook + * - ESP_ERR_NO_MEM: No more space on the calling core's idle hook to register callback + */ +esp_err_t esp_register_freertos_idle_hook(esp_freertos_idle_cb_t new_idle_cb); + +/** + * @brief Register a callback to be called from the specified core's tick hook. + * + * @param[in] new_tick_cb Callback to be called + * @param[in] cpuid id of the core + * + * @return + * - ESP_OK: Callback registered to specified core's tick hook + * - ESP_ERR_NO_MEM: No more space on the specified core's tick hook to register the callback + * - ESP_ERR_INVALID_ARG: cpuid is invalid + */ +esp_err_t esp_register_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t new_tick_cb, UBaseType_t cpuid); + +/** + * @brief Register a callback to be called from the calling core's tick hook. + * + * @param[in] new_tick_cb Callback to be called + * + * @return + * - ESP_OK: Callback registered to the calling core's tick hook + * - ESP_ERR_NO_MEM: No more space on the calling core's tick hook to register the callback + */ +esp_err_t esp_register_freertos_tick_hook(esp_freertos_tick_cb_t new_tick_cb); + +/** + * @brief Unregister an idle callback from the idle hook of the specified core + * + * @param[in] old_idle_cb Callback to be unregistered + * @param[in] cpuid id of the core + */ +void esp_deregister_freertos_idle_hook_for_cpu(esp_freertos_idle_cb_t old_idle_cb, UBaseType_t cpuid); + +/** + * @brief Unregister an idle callback. If the idle callback is registered to + * the idle hooks of both cores, the idle hook will be unregistered from + * both cores + * + * @param[in] old_idle_cb Callback to be unregistered + */ +void esp_deregister_freertos_idle_hook(esp_freertos_idle_cb_t old_idle_cb); + +/** + * @brief Unregister a tick callback from the tick hook of the specified core + * + * @param[in] old_tick_cb Callback to be unregistered + * @param[in] cpuid id of the core + */ +void esp_deregister_freertos_tick_hook_for_cpu(esp_freertos_tick_cb_t old_tick_cb, UBaseType_t cpuid); + +/** + * @brief Unregister a tick callback. If the tick callback is registered to the + * tick hooks of both cores, the tick hook will be unregistered from + * both cores + * + * @param[in] old_tick_cb Callback to be unregistered + */ +void esp_deregister_freertos_tick_hook(esp_freertos_tick_cb_t old_tick_cb); + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_int_wdt.h b/tools/sdk/esp32c3/include/esp_system/include/esp_int_wdt.h new file mode 100644 index 00000000..2bda5d85 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_int_wdt.h @@ -0,0 +1,67 @@ +// Copyright 2015-2018 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. + +#ifndef __ESP_INT_WDT_H +#define __ESP_INT_WDT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup Watchdog_APIs + * @{ + */ + +/* +This routine enables a watchdog to catch instances of processes disabling +interrupts for too long, or code within interrupt handlers taking too long. +It does this by setting up a watchdog which gets fed from the FreeRTOS +task switch interrupt. When this watchdog times out, initially it will call +a high-level interrupt routine that will panic FreeRTOS in order to allow +for forensic examination of the state of the both CPUs. When this interrupt +handler is not called and the watchdog times out a second time, it will +reset the SoC. + +This uses the TIMERG1 WDT. +*/ + + +/** + * @brief Initialize the non-CPU-specific parts of interrupt watchdog. + * This is called in the init code if the interrupt watchdog + * is enabled in menuconfig. + * + */ +void esp_int_wdt_init(void); + +/** + * @brief Enable the interrupt watchdog on the current CPU. This is called + * in the init code by both CPUs if the interrupt watchdog is enabled + * in menuconfig. + * + */ +void esp_int_wdt_cpu_init(void); + + + +/** + * @} + */ + + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_intr_alloc.h b/tools/sdk/esp32c3/include/esp_system/include/esp_intr_alloc.h new file mode 100644 index 00000000..33f70b95 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_intr_alloc.h @@ -0,0 +1,322 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** @addtogroup Intr_Alloc + * @{ + */ + + +/** @brief Interrupt allocation flags + * + * These flags can be used to specify which interrupt qualities the + * code calling esp_intr_alloc* needs. + * + */ + +//Keep the LEVELx values as they are here; they match up with (1<3 + * is requested, because these types of interrupts aren't C-callable. + * @param arg Optional argument for passed to the interrupt handler + * @param ret_handle Pointer to an intr_handle_t to store a handle that can later be + * used to request details or free the interrupt. Can be NULL if no handle + * is required. + * + * @return ESP_ERR_INVALID_ARG if the combination of arguments is invalid. + * ESP_ERR_NOT_FOUND No free interrupt found with the specified flags + * ESP_OK otherwise + */ +esp_err_t esp_intr_alloc(int source, int flags, intr_handler_t handler, void *arg, intr_handle_t *ret_handle); + + +/** + * @brief Allocate an interrupt with the given parameters. + * + * + * This essentially does the same as esp_intr_alloc, but allows specifying a register and mask + * combo. For shared interrupts, the handler is only called if a read from the specified + * register, ANDed with the mask, returns non-zero. By passing an interrupt status register + * address and a fitting mask, this can be used to accelerate interrupt handling in the case + * a shared interrupt is triggered; by checking the interrupt statuses first, the code can + * decide which ISRs can be skipped + * + * @param source The interrupt source. One of the ETS_*_INTR_SOURCE interrupt mux + * sources, as defined in soc/soc.h, or one of the internal + * ETS_INTERNAL_*_INTR_SOURCE sources as defined in this header. + * @param flags An ORred mask of the ESP_INTR_FLAG_* defines. These restrict the + * choice of interrupts that this routine can choose from. If this value + * is 0, it will default to allocating a non-shared interrupt of level + * 1, 2 or 3. If this is ESP_INTR_FLAG_SHARED, it will allocate a shared + * interrupt of level 1. Setting ESP_INTR_FLAG_INTRDISABLED will return + * from this function with the interrupt disabled. + * @param intrstatusreg The address of an interrupt status register + * @param intrstatusmask A mask. If a read of address intrstatusreg has any of the bits + * that are 1 in the mask set, the ISR will be called. If not, it will be + * skipped. + * @param handler The interrupt handler. Must be NULL when an interrupt of level >3 + * is requested, because these types of interrupts aren't C-callable. + * @param arg Optional argument for passed to the interrupt handler + * @param ret_handle Pointer to an intr_handle_t to store a handle that can later be + * used to request details or free the interrupt. Can be NULL if no handle + * is required. + * + * @return ESP_ERR_INVALID_ARG if the combination of arguments is invalid. + * ESP_ERR_NOT_FOUND No free interrupt found with the specified flags + * ESP_OK otherwise + */ +esp_err_t esp_intr_alloc_intrstatus(int source, int flags, uint32_t intrstatusreg, uint32_t intrstatusmask, intr_handler_t handler, void *arg, intr_handle_t *ret_handle); + + +/** + * @brief Disable and free an interrupt. + * + * Use an interrupt handle to disable the interrupt and release the resources associated with it. + * If the current core is not the core that registered this interrupt, this routine will be assigned to + * the core that allocated this interrupt, blocking and waiting until the resource is successfully released. + * + * @note + * When the handler shares its source with other handlers, the interrupt status + * bits it's responsible for should be managed properly before freeing it. see + * ``esp_intr_disable`` for more details. Please do not call this function in ``esp_ipc_call_blocking``. + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * + * @return ESP_ERR_INVALID_ARG the handle is NULL + * ESP_FAIL failed to release this handle + * ESP_OK otherwise + */ +esp_err_t esp_intr_free(intr_handle_t handle); + + +/** + * @brief Get CPU number an interrupt is tied to + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * + * @return The core number where the interrupt is allocated + */ +int esp_intr_get_cpu(intr_handle_t handle); + +/** + * @brief Get the allocated interrupt for a certain handle + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * + * @return The interrupt number + */ +int esp_intr_get_intno(intr_handle_t handle); + +/** + * @brief Disable the interrupt associated with the handle + * + * @note + * 1. For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the + * CPU the interrupt is allocated on. Other interrupts have no such restriction. + * 2. When several handlers sharing a same interrupt source, interrupt status bits, which are + * handled in the handler to be disabled, should be masked before the disabling, or handled + * in other enabled interrupts properly. Miss of interrupt status handling will cause infinite + * interrupt calls and finally system crash. + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * + * @return ESP_ERR_INVALID_ARG if the combination of arguments is invalid. + * ESP_OK otherwise + */ +esp_err_t esp_intr_disable(intr_handle_t handle); + +/** + * @brief Enable the interrupt associated with the handle + * + * @note For local interrupts (ESP_INTERNAL_* sources), this function has to be called on the + * CPU the interrupt is allocated on. Other interrupts have no such restriction. + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * + * @return ESP_ERR_INVALID_ARG if the combination of arguments is invalid. + * ESP_OK otherwise + */ +esp_err_t esp_intr_enable(intr_handle_t handle); + +/** + * @brief Set the "in IRAM" status of the handler. + * + * @note Does not work on shared interrupts. + * + * @param handle The handle, as obtained by esp_intr_alloc or esp_intr_alloc_intrstatus + * @param is_in_iram Whether the handler associated with this handle resides in IRAM. + * Handlers residing in IRAM can be called when cache is disabled. + * + * @return ESP_ERR_INVALID_ARG if the combination of arguments is invalid. + * ESP_OK otherwise + */ +esp_err_t esp_intr_set_in_iram(intr_handle_t handle, bool is_in_iram); + +/** + * @brief Disable interrupts that aren't specifically marked as running from IRAM + */ +void esp_intr_noniram_disable(void); + +/** + * @brief Re-enable interrupts disabled by esp_intr_noniram_disable + */ +void esp_intr_noniram_enable(void); + +/** + * @brief enable the interrupt source based on its number + * @param inum interrupt number from 0 to 31 + */ +void esp_intr_enable_source(int inum); + +/** + * @brief disable the interrupt source based on its number + * @param inum interrupt number from 0 to 31 + */ +void esp_intr_disable_source(int inum); + +/** + * @brief Get the lowest interrupt level from the flags + * @param flags The same flags that pass to `esp_intr_alloc_intrstatus` API + */ +static inline int esp_intr_flags_to_level(int flags) +{ + return __builtin_ffs((flags & ESP_INTR_FLAG_LEVELMASK) >> 1) + 1; +} + +/**@}*/ + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/crosscore_int.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/crosscore_int.h new file mode 100644 index 00000000..bac4afba --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/crosscore_int.h @@ -0,0 +1,71 @@ +// Copyright 2015-2016 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. +#ifndef __ESP_CROSSCORE_INT_H +#define __ESP_CROSSCORE_INT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Initialize the crosscore interrupt system for this CPU. + * This needs to be called once on every CPU that is used + * by FreeRTOS. + * + * If multicore FreeRTOS support is enabled, this will be + * called automatically by the startup code and should not + * be called manually. + */ +void esp_crosscore_int_init(void); + + +/** + * Send an interrupt to a CPU indicating it should yield its + * currently running task in favour of a higher-priority task + * that presumably just woke up. + * + * This is used internally by FreeRTOS in multicore mode + * and should not be called by the user. + * + * @param core_id Core that should do the yielding + */ +void esp_crosscore_int_send_yield(int core_id); + + +/** + * Send an interrupt to a CPU indicating it should update its + * CCOMPARE1 value due to a frequency switch. + * + * This is used internally when dynamic frequency switching is + * enabled, and should not be called from application code. + * + * @param core_id Core that should update its CCOMPARE1 value + */ +void esp_crosscore_int_send_freq_switch(int core_id); + +/** + * Send an interrupt to a CPU indicating it should print its current backtrace + * + * This is use internally by the Task Watchdog to dump the backtrace of the + * opposite core and should not be called from application code. + * + * @param core_id Core that should print its backtrace + */ +void esp_crosscore_int_send_print_backtrace(int core_id); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/dbg_stubs.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/dbg_stubs.h new file mode 100644 index 00000000..f3f5fba3 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/dbg_stubs.h @@ -0,0 +1,58 @@ +// Copyright 2017 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. +#ifndef ESP_DBG_STUBS_H_ +#define ESP_DBG_STUBS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_err.h" + +/** + * Debug stubs entries IDs + */ +typedef enum { + ESP_DBG_STUB_CONTROL_DATA, ///< stubs descriptor entry + ESP_DBG_STUB_ENTRY_FIRST, + ESP_DBG_STUB_ENTRY_GCOV ///< GCOV entry + = ESP_DBG_STUB_ENTRY_FIRST, + ESP_DBG_STUB_ENTRY_MAX +} esp_dbg_stub_id_t; + +/** + * @brief Initializes debug stubs. + * + * @note Must be called after esp_apptrace_init() if app tracing is enabled. + */ +void esp_dbg_stubs_init(void); + +/** + * @brief Initializes application tracing module. + * + * @note Should be called before any esp_apptrace_xxx call. + * + * @param id Stub ID. + * @param entry Stub entry. Usually it is stub entry function address, + * but can be any value meaningfull for OpenOCD command/code. + * + * @return ESP_OK on success, otherwise see esp_err_t + */ +esp_err_t esp_dbg_stub_entry_set(esp_dbg_stub_id_t id, uint32_t entry); + +#ifdef __cplusplus +} +#endif + +#endif //ESP_DBG_STUBS_H_ diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/panic_internal.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/panic_internal.h new file mode 100644 index 00000000..d43a705a --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/panic_internal.h @@ -0,0 +1,97 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include +#include + +#include "soc/soc_caps.h" + +#include "sdkconfig.h" + + +#ifdef __cplusplus +extern "C" { +#endif + +extern bool g_panic_abort; + +extern void *g_exc_frames[SOC_CPU_CORES_NUM]; + +// Function to print longer amounts of information such as the details +// and backtrace field of panic_info_t. These functions should limit themselves +// to printing to the console and should do other more involved processing, +// and must be aware that the main logic in panic.c has a watchdog timer active. +typedef void (*panic_info_dump_fn_t)(const void* frame); + +// Non architecture specific exceptions (generally valid for all targets). +// Can be used to convey to the main logic what exception is being +// dealt with to perform some actions, without knowing the underlying +// architecture/chip-specific exception. +typedef enum { + PANIC_EXCEPTION_DEBUG, + PANIC_EXCEPTION_IWDT, + PANIC_EXCEPTION_TWDT, + PANIC_EXCEPTION_ABORT, + PANIC_EXCEPTION_FAULT, // catch-all for all types of faults +} panic_exception_t; + +typedef struct { + int core; // core which triggered panic + panic_exception_t exception; // non-architecture-specific exception code + const char* reason; // exception string + const char* description; // short description of the exception + panic_info_dump_fn_t details; // more details on the exception + panic_info_dump_fn_t state; // processor state, usually the contents of the registers + const void* addr; // instruction address that triggered the exception + const void* frame; // reference to the frame + bool pseudo_excause; // flag indicating that exception cause has special meaning +} panic_info_t; + +#define PANIC_INFO_DUMP(info, dump_fn) {if ((info)->dump_fn) (*(info)->dump_fn)((info->frame));} + +// Create own print functions, since printf might be broken, and can be silenced +// when CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT +#if !CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT +void panic_print_char(char c); +void panic_print_str(const char *str); +void panic_print_dec(int d); +void panic_print_hex(int h); +#else +#define panic_print_char(c) +#define panic_print_str(str) +#define panic_print_dec(d) +#define panic_print_hex(h) +#endif + +void __attribute__((noreturn)) panic_abort(const char *details); + +void panic_arch_fill_info(void *frame, panic_info_t *info); + +void panic_soc_fill_info(void *frame, panic_info_t *info); + +void panic_print_registers(const void *frame, int core); + +void panic_print_backtrace(const void *frame, int core); + +uint32_t panic_get_address(const void* frame); + +void panic_set_address(void *frame, uint32_t addr); + +uint32_t panic_get_cause(const void* frame); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/sleep_modes.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/sleep_modes.h new file mode 100644 index 00000000..e1584a8b --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/sleep_modes.h @@ -0,0 +1,40 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU +/** + * @brief CPU Power down low-level initialize + * + * @param enable enable or disable CPU power down during light sleep + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM not enough retention memory + */ +esp_err_t esp_sleep_cpu_pd_low_init(bool enable); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/startup_internal.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/startup_internal.h new file mode 100644 index 00000000..42b901cb --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/startup_internal.h @@ -0,0 +1,73 @@ +// Copyright 2015-2018 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. + +#pragma once + +#include "esp_attr.h" + +#include "soc/soc_caps.h" +#include "hal/cpu_hal.h" + +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +extern bool g_spiram_ok; // [refactor-todo] better way to communicate this from port layer to common startup code + +// Port layer defines the entry point. It then transfer control to a `sys_startup_fn_t`, stored in this +// array, one per core. +typedef void (*sys_startup_fn_t)(void); + +#if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE +extern sys_startup_fn_t g_startup_fn[SOC_CPU_CORES_NUM]; +#else +extern sys_startup_fn_t g_startup_fn[1]; +#endif + +// Utility to execute `sys_startup_fn_t` for the current core. +#define SYS_STARTUP_FN() ((*g_startup_fn[(cpu_hal_get_core_id())])()) + +#if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE +void startup_resume_other_cores(void); +#endif + +typedef struct { + void (*fn)(void); + uint32_t cores; +} esp_system_init_fn_t; + +/* + * Declare an component initialization function that will execute on the specified cores (ex. if BIT0 == 1, will execute + * on CORE0, CORE1 if BIT1 and so on). + * + * @note Initialization functions should be placed in a compilation unit where at least one other + * symbol is referenced 'meaningfully' in another compilation unit, otherwise this gets discarded during linking. (By + * 'meaningfully' we mean the reference should not itself get optimized out by the compiler/discarded by the linker). + */ +#define ESP_SYSTEM_INIT_FN(f, c, ...) \ +static void __attribute__((used)) __VA_ARGS__ __esp_system_init_fn_##f(void); \ +static __attribute__((used)) esp_system_init_fn_t _SECTION_ATTR_IMPL(".esp_system_init_fn", f) \ + esp_system_init_fn_##f = { .fn = ( __esp_system_init_fn_##f), .cores = (c) }; \ +static __attribute__((used)) __VA_ARGS__ void __esp_system_init_fn_##f(void) // [refactor-todo] this can be made public API if we allow components to declare init functions, + // instead of calling them explicitly + +extern uint64_t g_startup_time; // Startup time that serves as the point of origin for system time. Should be set by the entry + // function in the port layer. May be 0 as well if this is not backed by a persistent counter, in which case + // startup time = system time = 0 at the point the entry function sets this variable. + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/system_internal.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/system_internal.h new file mode 100644 index 00000000..2125fa7f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/system_internal.h @@ -0,0 +1,81 @@ +// Copyright 2018 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_system.h" + +#define MWDT0_TICK_PRESCALER 40000 +#define MWDT0_TICKS_PER_US 500 +#define MWDT1_TICK_PRESCALER 40000 +#define MWDT1_TICKS_PER_US 500 + +/** + * @brief Internal function to restart PRO and APP CPUs. + * + * @note This function should not be called from FreeRTOS applications. + * Use esp_restart instead. + * + * This is an internal function called by esp_restart. It is called directly + * by the panic handler and brownout detector interrupt. + */ +void esp_restart_noos(void) __attribute__ ((noreturn)); + +/** + * @brief Similar to esp_restart_noos, but resets all the digital peripherals. + */ +void esp_restart_noos_dig(void) __attribute__ ((noreturn)); + +/** + * @brief Internal function to set reset reason hint + * + * The hint is used do distinguish different reset reasons when software reset + * is performed. + * + * The hint is stored in RTC store register, RTC_RESET_CAUSE_REG. + * + * @param hint Desired esp_reset_reason_t value for the real reset reason + */ +void esp_reset_reason_set_hint(esp_reset_reason_t hint); + +/** + * @brief Internal function to get the reset hint value + * @return - Reset hint value previously stored into RTC_RESET_CAUSE_REG using + * esp_reset_reason_set_hint function + * - ESP_RST_UNKNOWN if the value in RTC_RESET_CAUSE_REG is invalid + */ +esp_reset_reason_t esp_reset_reason_get_hint(void); + +/** + * @brief Get the time in microseconds since startup + * + * @returns time since g_startup_time; definition should be fixed by system time provider + * no matter the underlying timer used. + */ +int64_t esp_system_get_time(void); + +/** + * @brief Get the resolution of the time returned by `esp_system_get_time`. + * + * @returns the resolution in nanoseconds + */ +uint32_t esp_system_get_time_resolution(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_private/usb_console.h b/tools/sdk/esp32c3/include/esp_system/include/esp_private/usb_console.h new file mode 100644 index 00000000..1e9536f4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_private/usb_console.h @@ -0,0 +1,73 @@ +// Copyright 2019-2020 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. + +#pragma once + +#include +#include +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file usb_console.h + * This file contains definitions of low-level USB console functions. + * These functions are not considered to be a public interface and + * should not be called by applications directly. + * Application interface to the USB console is provided either by + * "cdcacm" VFS driver, or by the USB CDC driver in TinyUSB. + */ + + +/** + * RX/TX callback function type + * @param arg callback-specific context pointer + */ +typedef void (*esp_usb_console_cb_t)(void* arg); + +/** + * Initialize USB console output using ROM USB CDC driver. + * This function is called by the early startup code if USB CDC is + * selected as the console output option. + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM + * - other error codes from the interrupt allocator + */ +esp_err_t esp_usb_console_init(void); + +/** + * Write a buffer to USB CDC + * @param buf data to write + * @param size size of the data, in bytes + * @return -1 on error, otherwise the number of bytes + */ +ssize_t esp_usb_console_write_buf(const char* buf, size_t size); + +ssize_t esp_usb_console_flush(void); + +ssize_t esp_usb_console_read_buf(char* buf, size_t buf_size); + +bool esp_usb_console_read_available(void); + +bool esp_usb_console_write_available(void); + +esp_err_t esp_usb_console_set_cb(esp_usb_console_cb_t rx_cb, esp_usb_console_cb_t tx_cb, void* arg); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_sleep.h b/tools/sdk/esp32c3/include/esp_system/include/esp_sleep.h new file mode 100644 index 00000000..d84933cd --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_sleep.h @@ -0,0 +1,503 @@ +// Copyright 2015-2017 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. + +#pragma once + +#include +#include "esp_err.h" + +#include "hal/touch_sensor_types.h" +#include "hal/gpio_types.h" + +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Logic function used for EXT1 wakeup mode. + */ +typedef enum { + ESP_EXT1_WAKEUP_ALL_LOW = 0, //!< Wake the chip when all selected GPIOs go low + ESP_EXT1_WAKEUP_ANY_HIGH = 1 //!< Wake the chip when any of the selected GPIOs go high +} esp_sleep_ext1_wakeup_mode_t; + +#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP +typedef enum { + ESP_GPIO_WAKEUP_GPIO_LOW = 0, + ESP_GPIO_WAKEUP_GPIO_HIGH = 1 +} esp_deepsleep_gpio_wake_up_mode_t; +#endif + +/** + * @brief Power domains which can be powered down in sleep mode + */ +typedef enum { + ESP_PD_DOMAIN_RTC_PERIPH, //!< RTC IO, sensors and ULP co-processor + ESP_PD_DOMAIN_RTC_SLOW_MEM, //!< RTC slow memory + ESP_PD_DOMAIN_RTC_FAST_MEM, //!< RTC fast memory + ESP_PD_DOMAIN_XTAL, //!< XTAL oscillator + ESP_PD_DOMAIN_CPU, //!< CPU core + ESP_PD_DOMAIN_VDDSDIO, //!< VDD_SDIO + ESP_PD_DOMAIN_MAX //!< Number of domains +} esp_sleep_pd_domain_t; + +/** + * @brief Power down options + */ +typedef enum { + ESP_PD_OPTION_OFF, //!< Power down the power domain in sleep mode + ESP_PD_OPTION_ON, //!< Keep power domain enabled during sleep mode + ESP_PD_OPTION_AUTO //!< Keep power domain enabled in sleep mode, if it is needed by one of the wakeup options. Otherwise power it down. +} esp_sleep_pd_option_t; + +/** + * @brief Sleep wakeup cause + */ +typedef enum { + ESP_SLEEP_WAKEUP_UNDEFINED, //!< In case of deep sleep, reset was not caused by exit from deep sleep + ESP_SLEEP_WAKEUP_ALL, //!< Not a wakeup cause, used to disable all wakeup sources with esp_sleep_disable_wakeup_source + ESP_SLEEP_WAKEUP_EXT0, //!< Wakeup caused by external signal using RTC_IO + ESP_SLEEP_WAKEUP_EXT1, //!< Wakeup caused by external signal using RTC_CNTL + ESP_SLEEP_WAKEUP_TIMER, //!< Wakeup caused by timer + ESP_SLEEP_WAKEUP_TOUCHPAD, //!< Wakeup caused by touchpad + ESP_SLEEP_WAKEUP_ULP, //!< Wakeup caused by ULP program + ESP_SLEEP_WAKEUP_GPIO, //!< Wakeup caused by GPIO (light sleep only) + ESP_SLEEP_WAKEUP_UART, //!< Wakeup caused by UART (light sleep only) + ESP_SLEEP_WAKEUP_WIFI, //!< Wakeup caused by WIFI (light sleep only) + ESP_SLEEP_WAKEUP_COCPU, //!< Wakeup caused by COCPU int + ESP_SLEEP_WAKEUP_COCPU_TRAP_TRIG, //!< Wakeup caused by COCPU crash + ESP_SLEEP_WAKEUP_BT, //!< Wakeup caused by BT (light sleep only) +} esp_sleep_source_t; + +/* Leave this type define for compatibility */ +typedef esp_sleep_source_t esp_sleep_wakeup_cause_t; + +/** + * @brief Disable wakeup source + * + * This function is used to deactivate wake up trigger for source + * defined as parameter of the function. + * + * @note This function does not modify wake up configuration in RTC. + * It will be performed in esp_sleep_start function. + * + * See docs/sleep-modes.rst for details. + * + * @param source - number of source to disable of type esp_sleep_source_t + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if trigger was not active + */ +esp_err_t esp_sleep_disable_wakeup_source(esp_sleep_source_t source); + +#if SOC_ULP_SUPPORTED +/** + * @brief Enable wakeup by ULP coprocessor + * @note In revisions 0 and 1 of the ESP32, ULP wakeup source + * cannot be used when RTC_PERIPH power domain is forced + * to be powered on (ESP_PD_OPTION_ON) or when + * ext0 wakeup source is used. + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_SUPPORTED if additional current by touch (CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT) is enabled. + * - ESP_ERR_INVALID_STATE if ULP co-processor is not enabled or if wakeup triggers conflict + */ +esp_err_t esp_sleep_enable_ulp_wakeup(void); + +#endif // SOC_ULP_SUPPORTED + +/** + * @brief Enable wakeup by timer + * @param time_in_us time before wakeup, in microseconds + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if value is out of range (TBD) + */ +esp_err_t esp_sleep_enable_timer_wakeup(uint64_t time_in_us); + +#if SOC_TOUCH_SENSOR_NUM > 0 + +/** + * @brief Enable wakeup by touch sensor + * + * @note In revisions 0 and 1 of the ESP32, touch wakeup source + * can not be used when RTC_PERIPH power domain is forced + * to be powered on (ESP_PD_OPTION_ON) or when ext0 wakeup + * source is used. + * + * @note The FSM mode of the touch button should be configured + * as the timer trigger mode. + * + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_SUPPORTED if additional current by touch (CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT) is enabled. + * - ESP_ERR_INVALID_STATE if wakeup triggers conflict + */ +esp_err_t esp_sleep_enable_touchpad_wakeup(void); + +/** + * @brief Get the touch pad which caused wakeup + * + * If wakeup was caused by another source, this function will return TOUCH_PAD_MAX; + * + * @return touch pad which caused wakeup + */ +touch_pad_t esp_sleep_get_touchpad_wakeup_status(void); + +#endif // SOC_TOUCH_SENSOR_NUM > 0 + +/** + * @brief Returns true if a GPIO number is valid for use as wakeup source. + * + * @note For SoCs with RTC IO capability, this can be any valid RTC IO input pin. + * + * @param gpio_num Number of the GPIO to test for wakeup source capability + * + * @return True if this GPIO number will be accepted as a sleep wakeup source. + */ +bool esp_sleep_is_valid_wakeup_gpio(gpio_num_t gpio_num); + +#if SOC_PM_SUPPORT_EXT_WAKEUP + +/** + * @brief Enable wakeup using a pin + * + * This function uses external wakeup feature of RTC_IO peripheral. + * It will work only if RTC peripherals are kept on during sleep. + * + * This feature can monitor any pin which is an RTC IO. Once the pin transitions + * into the state given by level argument, the chip will be woken up. + * + * @note This function does not modify pin configuration. The pin is + * configured in esp_sleep_start, immediately before entering sleep mode. + * + * @note In revisions 0 and 1 of the ESP32, ext0 wakeup source + * can not be used together with touch or ULP wakeup sources. + * + * @param gpio_num GPIO number used as wakeup source. Only GPIOs which are have RTC + * functionality can be used: 0,2,4,12-15,25-27,32-39. + * @param level input level which will trigger wakeup (0=low, 1=high) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the selected GPIO is not an RTC GPIO, + * or the mode is invalid + * - ESP_ERR_INVALID_STATE if wakeup triggers conflict + */ +esp_err_t esp_sleep_enable_ext0_wakeup(gpio_num_t gpio_num, int level); + +/** + * @brief Enable wakeup using multiple pins + * + * This function uses external wakeup feature of RTC controller. + * It will work even if RTC peripherals are shut down during sleep. + * + * This feature can monitor any number of pins which are in RTC IOs. + * Once any of the selected pins goes into the state given by mode argument, + * the chip will be woken up. + * + * @note This function does not modify pin configuration. The pins are + * configured in esp_sleep_start, immediately before + * entering sleep mode. + * + * @note internal pullups and pulldowns don't work when RTC peripherals are + * shut down. In this case, external resistors need to be added. + * Alternatively, RTC peripherals (and pullups/pulldowns) may be + * kept enabled using esp_sleep_pd_config function. + * + * @param mask bit mask of GPIO numbers which will cause wakeup. Only GPIOs + * which are have RTC functionality can be used in this bit map: + * 0,2,4,12-15,25-27,32-39. + * @param mode select logic function used to determine wakeup condition: + * - ESP_EXT1_WAKEUP_ALL_LOW: wake up when all selected GPIOs are low + * - ESP_EXT1_WAKEUP_ANY_HIGH: wake up when any of the selected GPIOs is high + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if any of the selected GPIOs is not an RTC GPIO, + * or mode is invalid + */ +esp_err_t esp_sleep_enable_ext1_wakeup(uint64_t mask, esp_sleep_ext1_wakeup_mode_t mode); + +#endif // SOC_PM_SUPPORT_EXT_WAKEUP + +#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP +/** + * @brief Enable wakeup using specific gpio pins + * + * This function enables an IO pin to wake the chip from deep sleep + * + * @note This function does not modify pin configuration. The pins are + * configured in esp_sleep_start, immediately before + * entering sleep mode. + * + * @note You don't need to care to pull-up or pull-down before using this + * function, because this will be done in esp_sleep_start based on + * param mask you give. BTW, when you use low level to wake up the + * chip, we strongly recommand you to add external registors(pull-up). + * + * @param gpio_pin_mask Bit mask of GPIO numbers which will cause wakeup. Only GPIOs + * which are have RTC functionality can be used in this bit map. + * @param mode Select logic function used to determine wakeup condition: + * - ESP_GPIO_WAKEUP_GPIO_LOW: wake up when the gpio turn to low. + * - ESP_GPIO_WAKEUP_GPIO_HIGH: wake up when the gpio turn to high. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if gpio num is more than 5 or mode is invalid, + */ +esp_err_t esp_deep_sleep_enable_gpio_wakeup(uint64_t gpio_pin_mask, esp_deepsleep_gpio_wake_up_mode_t mode); +#endif +/** + * @brief Enable wakeup from light sleep using GPIOs + * + * Each GPIO supports wakeup function, which can be triggered on either low level + * or high level. Unlike EXT0 and EXT1 wakeup sources, this method can be used + * both for all IOs: RTC IOs and digital IOs. It can only be used to wakeup from + * light sleep though. + * + * To enable wakeup, first call gpio_wakeup_enable, specifying gpio number and + * wakeup level, for each GPIO which is used for wakeup. + * Then call this function to enable wakeup feature. + * + * @note In revisions 0 and 1 of the ESP32, GPIO wakeup source + * can not be used together with touch or ULP wakeup sources. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if wakeup triggers conflict + */ +esp_err_t esp_sleep_enable_gpio_wakeup(void); + +/** + * @brief Enable wakeup from light sleep using UART + * + * Use uart_set_wakeup_threshold function to configure UART wakeup threshold. + * + * Wakeup from light sleep takes some time, so not every character sent + * to the UART can be received by the application. + * + * @note ESP32 does not support wakeup from UART2. + * + * @param uart_num UART port to wake up from + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if wakeup from given UART is not supported + */ +esp_err_t esp_sleep_enable_uart_wakeup(int uart_num); + +/** + * @brief Enable wakeup by WiFi MAC + * @return + * - ESP_OK on success + */ +esp_err_t esp_sleep_enable_wifi_wakeup(void); + + +/** + * @brief Get the bit mask of GPIOs which caused wakeup (ext1) + * + * If wakeup was caused by another source, this function will return 0. + * + * @return bit mask, if GPIOn caused wakeup, BIT(n) will be set + */ +uint64_t esp_sleep_get_ext1_wakeup_status(void); + +#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP +/** + * @brief Get the bit mask of GPIOs which caused wakeup (gpio) + * + * If wakeup was caused by another source, this function will return 0. + * + * @return bit mask, if GPIOn caused wakeup, BIT(n) will be set + */ +uint64_t esp_sleep_get_gpio_wakeup_status(void); +#endif //SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP + +/** + * @brief Set power down mode for an RTC power domain in sleep mode + * + * If not set set using this API, all power domains default to ESP_PD_OPTION_AUTO. + * + * @param domain power domain to configure + * @param option power down option (ESP_PD_OPTION_OFF, ESP_PD_OPTION_ON, or ESP_PD_OPTION_AUTO) + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if either of the arguments is out of range + */ +esp_err_t esp_sleep_pd_config(esp_sleep_pd_domain_t domain, + esp_sleep_pd_option_t option); + +/** + * @brief Enter deep sleep with the configured wakeup options + * + * This function does not return. + */ +void esp_deep_sleep_start(void) __attribute__((noreturn)); + +/** + * @brief Enter light sleep with the configured wakeup options + * + * @return + * - ESP_OK on success (returned after wakeup) + * - ESP_ERR_INVALID_STATE if WiFi or BT is not stopped + */ +esp_err_t esp_light_sleep_start(void); + +/** + * @brief Enter deep-sleep mode + * + * The device will automatically wake up after the deep-sleep time + * Upon waking up, the device calls deep sleep wake stub, and then proceeds + * to load application. + * + * Call to this function is equivalent to a call to esp_deep_sleep_enable_timer_wakeup + * followed by a call to esp_deep_sleep_start. + * + * esp_deep_sleep does not shut down WiFi, BT, and higher level protocol + * connections gracefully. + * Make sure relevant WiFi and BT stack functions are called to close any + * connections and deinitialize the peripherals. These include: + * - esp_bluedroid_disable + * - esp_bt_controller_disable + * - esp_wifi_stop + * + * This function does not return. + * + * @param time_in_us deep-sleep time, unit: microsecond + */ +void esp_deep_sleep(uint64_t time_in_us) __attribute__((noreturn)); + + +/** + * @brief Get the wakeup source which caused wakeup from sleep + * + * @return cause of wake up from last sleep (deep sleep or light sleep) + */ +esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause(void); + + +/** + * @brief Default stub to run on wake from deep sleep. + * + * Allows for executing code immediately on wake from sleep, before + * the software bootloader or ESP-IDF app has started up. + * + * This function is weak-linked, so you can implement your own version + * to run code immediately when the chip wakes from + * sleep. + * + * See docs/deep-sleep-stub.rst for details. + */ +void esp_wake_deep_sleep(void); + +/** + * @brief Function type for stub to run on wake from sleep. + * + */ +typedef void (*esp_deep_sleep_wake_stub_fn_t)(void); + +/** + * @brief Install a new stub at runtime to run on wake from deep sleep + * + * If implementing esp_wake_deep_sleep() then it is not necessary to + * call this function. + * + * However, it is possible to call this function to substitute a + * different deep sleep stub. Any function used as a deep sleep stub + * must be marked RTC_IRAM_ATTR, and must obey the same rules given + * for esp_wake_deep_sleep(). + */ +void esp_set_deep_sleep_wake_stub(esp_deep_sleep_wake_stub_fn_t new_stub); + +/** + * @brief Get current wake from deep sleep stub + * @return Return current wake from deep sleep stub, or NULL if + * no stub is installed. + */ +esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void); + +/** + * @brief The default esp-idf-provided esp_wake_deep_sleep() stub. + * + * See docs/deep-sleep-stub.rst for details. + */ +void esp_default_wake_deep_sleep(void); + +/** + * @brief Disable logging from the ROM code after deep sleep. + * + * Using LSB of RTC_STORE4. + */ +void esp_deep_sleep_disable_rom_logging(void); + +#if SOC_GPIO_SUPPORT_SLP_SWITCH +/** + * @brief Configure to isolate all GPIO pins in sleep state + */ +void esp_sleep_config_gpio_isolate(void); + +/** + * @brief Enable or disable GPIO pins status switching between slept status and waked status. + * @param enable decide whether to switch status or not + */ +void esp_sleep_enable_gpio_switch(bool enable); +#endif + +#if CONFIG_MAC_BB_PD +/** + * @brief Function type for stub to run mac bb power down. + */ +typedef void (* mac_bb_power_down_cb_t)(void); + +/** + * @brief Function type for stub to run mac bb power up. + */ +typedef void (* mac_bb_power_up_cb_t)(void); + +/** + * @brief Registet mac bb power down callback. + * @param cb mac bb power down callback. + * @return + * - ESP_OK on success + */ +esp_err_t esp_register_mac_bb_pd_callback(mac_bb_power_down_cb_t cb); + +/** + * @brief Unregistet mac bb power down callback. + * @param cb mac bb power down callback. + * @return + * - ESP_OK on success + */ +esp_err_t esp_unregister_mac_bb_pd_callback(mac_bb_power_down_cb_t cb); + +/** + * @brief Registet mac bb power up callback. + * @param cb mac bb power up callback. + * @return + * - ESP_OK on success + */ +esp_err_t esp_register_mac_bb_pu_callback(mac_bb_power_up_cb_t cb); + +/** + * @brief Unregistet mac bb power up callback. + * @param cb mac bb power up callback. + * @return + * - ESP_OK on success + */ +esp_err_t esp_unregister_mac_bb_pu_callback(mac_bb_power_up_cb_t cb); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_system.h b/tools/sdk/esp32c3/include/esp_system/include/esp_system.h new file mode 100644 index 00000000..bd9bb1a6 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_system.h @@ -0,0 +1,310 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_SYSTEM_H__ +#define __ESP_SYSTEM_H__ + +#include +#include +#include "esp_err.h" +#include "esp_attr.h" +#include "esp_bit_defs.h" +#include "esp_idf_version.h" + +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ESP_MAC_WIFI_STA, + ESP_MAC_WIFI_SOFTAP, + ESP_MAC_BT, + ESP_MAC_ETH, +} esp_mac_type_t; + +/** @cond */ +#define TWO_UNIVERSAL_MAC_ADDR 2 +#define FOUR_UNIVERSAL_MAC_ADDR 4 +#if CONFIG_IDF_TARGET_ESP32 +#define UNIVERSAL_MAC_ADDR_NUM CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES +#elif CONFIG_IDF_TARGET_ESP32S2 +#define UNIVERSAL_MAC_ADDR_NUM CONFIG_ESP32S2_UNIVERSAL_MAC_ADDRESSES +#elif CONFIG_IDF_TARGET_ESP32S3 +#define UNIVERSAL_MAC_ADDR_NUM CONFIG_ESP32S3_UNIVERSAL_MAC_ADDRESSES +#elif CONFIG_IDF_TARGET_ESP32C3 +#define UNIVERSAL_MAC_ADDR_NUM CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES +#endif +/** @endcond */ + +/** + * @brief Reset reasons + */ +typedef enum { + ESP_RST_UNKNOWN, //!< Reset reason can not be determined + ESP_RST_POWERON, //!< Reset due to power-on event + ESP_RST_EXT, //!< Reset by external pin (not applicable for ESP32) + ESP_RST_SW, //!< Software reset via esp_restart + ESP_RST_PANIC, //!< Software reset due to exception/panic + ESP_RST_INT_WDT, //!< Reset (software or hardware) due to interrupt watchdog + ESP_RST_TASK_WDT, //!< Reset due to task watchdog + ESP_RST_WDT, //!< Reset due to other watchdogs + ESP_RST_DEEPSLEEP, //!< Reset after exiting deep sleep mode + ESP_RST_BROWNOUT, //!< Brownout reset (software or hardware) + ESP_RST_SDIO, //!< Reset over SDIO +} esp_reset_reason_t; + +/** + * Shutdown handler type + */ +typedef void (*shutdown_handler_t)(void); + +/** + * @brief Register shutdown handler + * + * This function allows you to register a handler that gets invoked before + * the application is restarted using esp_restart function. + * @param handle function to execute on restart + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the handler has already been registered + * - ESP_ERR_NO_MEM if no more shutdown handler slots are available + */ +esp_err_t esp_register_shutdown_handler(shutdown_handler_t handle); + +/** + * @brief Unregister shutdown handler + * + * This function allows you to unregister a handler which was previously + * registered using esp_register_shutdown_handler function. + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the given handler hasn't been registered before + */ +esp_err_t esp_unregister_shutdown_handler(shutdown_handler_t handle); + + +/** + * @brief Restart PRO and APP CPUs. + * + * This function can be called both from PRO and APP CPUs. + * After successful restart, CPU reset reason will be SW_CPU_RESET. + * Peripherals (except for WiFi, BT, UART0, SPI1, and legacy timers) are not reset. + * This function does not return. + */ +void esp_restart(void) __attribute__ ((noreturn)); + +/** + * @brief Get reason of last reset + * @return See description of esp_reset_reason_t for explanation of each value. + */ +esp_reset_reason_t esp_reset_reason(void); + +/** + * @brief Get the size of available heap. + * + * Note that the returned value may be larger than the maximum contiguous block + * which can be allocated. + * + * @return Available heap size, in bytes. + */ +uint32_t esp_get_free_heap_size(void); + +/** + * @brief Get the size of available internal heap. + * + * Note that the returned value may be larger than the maximum contiguous block + * which can be allocated. + * + * @return Available internal heap size, in bytes. + */ +uint32_t esp_get_free_internal_heap_size(void); + +/** + * @brief Get the minimum heap that has ever been available + * + * @return Minimum free heap ever available + */ +uint32_t esp_get_minimum_free_heap_size( void ); + +/** + * @brief Get one random 32-bit word from hardware RNG + * + * The hardware RNG is fully functional whenever an RF subsystem is running (ie Bluetooth or WiFi is enabled). For + * random values, call this function after WiFi or Bluetooth are started. + * + * If the RF subsystem is not used by the program, the function bootloader_random_enable() can be called to enable an + * entropy source. bootloader_random_disable() must be called before RF subsystem or I2S peripheral are used. See these functions' + * documentation for more details. + * + * Any time the app is running without an RF subsystem (or bootloader_random) enabled, RNG hardware should be + * considered a PRNG. A very small amount of entropy is available due to pre-seeding while the IDF + * bootloader is running, but this should not be relied upon for any use. + * + * @return Random value between 0 and UINT32_MAX + */ +uint32_t esp_random(void); + +/** + * @brief Fill a buffer with random bytes from hardware RNG + * + * @note This function has the same restrictions regarding available entropy as esp_random() + * + * @param buf Pointer to buffer to fill with random numbers. + * @param len Length of buffer in bytes + */ +void esp_fill_random(void *buf, size_t len); + +/** + * @brief Set base MAC address with the MAC address which is stored in BLK3 of EFUSE or + * external storage e.g. flash and EEPROM. + * + * Base MAC address is used to generate the MAC addresses used by the networking interfaces. + * If using base MAC address stored in BLK3 of EFUSE or external storage, call this API to set base MAC + * address with the MAC address which is stored in BLK3 of EFUSE or external storage before initializing + * WiFi/BT/Ethernet. + * + * @note Base MAC must be a unicast MAC (least significant bit of first byte must be zero). + * + * @note If not using a valid OUI, set the "locally administered" bit + * (bit value 0x02 in the first byte) to avoid collisions. + * + * @param mac base MAC address, length: 6 bytes. + * + * @return ESP_OK on success + * ESP_ERR_INVALID_ARG If mac is NULL or is not a unicast MAC + */ +esp_err_t esp_base_mac_addr_set(const uint8_t *mac); + +/** + * @brief Return base MAC address which is set using esp_base_mac_addr_set. + * + * @param mac base MAC address, length: 6 bytes. + * + * @return ESP_OK on success + * ESP_ERR_INVALID_MAC base MAC address has not been set + */ +esp_err_t esp_base_mac_addr_get(uint8_t *mac); + +/** + * @brief Return base MAC address which was previously written to BLK3 of EFUSE. + * + * Base MAC address is used to generate the MAC addresses used by the networking interfaces. + * This API returns the custom base MAC address which was previously written to BLK3 of EFUSE. + * Writing this EFUSE allows setting of a different (non-Espressif) base MAC address. It is also + * possible to store a custom base MAC address elsewhere, see esp_base_mac_addr_set() for details. + * + * @param mac base MAC address, length: 6 bytes. + * + * @return ESP_OK on success + * ESP_ERR_INVALID_VERSION An invalid MAC version field was read from BLK3 of EFUSE + * ESP_ERR_INVALID_CRC An invalid MAC CRC was read from BLK3 of EFUSE + */ +esp_err_t esp_efuse_mac_get_custom(uint8_t *mac); + +/** + * @brief Return base MAC address which is factory-programmed by Espressif in BLK0 of EFUSE. + * + * @param mac base MAC address, length: 6 bytes. + * + * @return ESP_OK on success + */ +esp_err_t esp_efuse_mac_get_default(uint8_t *mac); + +/** + * @brief Read base MAC address and set MAC address of the interface. + * + * This function first get base MAC address using esp_base_mac_addr_get or reads base MAC address + * from BLK0 of EFUSE. Then set the MAC address of the interface including wifi station, wifi softap, + * bluetooth and ethernet. + * + * @param mac MAC address of the interface, length: 6 bytes. + * @param type type of MAC address, 0:wifi station, 1:wifi softap, 2:bluetooth, 3:ethernet. + * + * @return ESP_OK on success + */ +esp_err_t esp_read_mac(uint8_t* mac, esp_mac_type_t type); + +/** + * @brief Derive local MAC address from universal MAC address. + * + * This function derives a local MAC address from an universal MAC address. + * A `definition of local vs universal MAC address can be found on Wikipedia + * `. + * In ESP32, universal MAC address is generated from base MAC address in EFUSE or other external storage. + * Local MAC address is derived from the universal MAC address. + * + * @param local_mac Derived local MAC address, length: 6 bytes. + * @param universal_mac Source universal MAC address, length: 6 bytes. + * + * @return ESP_OK on success + */ +esp_err_t esp_derive_local_mac(uint8_t* local_mac, const uint8_t* universal_mac); + +/** + * @brief Trigger a software abort + * + * @param details Details that will be displayed during panic handling. + */ +void __attribute__((noreturn)) esp_system_abort(const char* details); + +/** + * @brief Chip models + */ +typedef enum { + CHIP_ESP32 = 1, //!< ESP32 + CHIP_ESP32S2 = 2, //!< ESP32-S2 + CHIP_ESP32S3 = 4, //!< ESP32-S3 + CHIP_ESP32C3 = 5, //!< ESP32-C3 +} esp_chip_model_t; + +/* Chip feature flags, used in esp_chip_info_t */ +#define CHIP_FEATURE_EMB_FLASH BIT(0) //!< Chip has embedded flash memory +#define CHIP_FEATURE_WIFI_BGN BIT(1) //!< Chip has 2.4GHz WiFi +#define CHIP_FEATURE_BLE BIT(4) //!< Chip has Bluetooth LE +#define CHIP_FEATURE_BT BIT(5) //!< Chip has Bluetooth Classic + +/** + * @brief The structure represents information about the chip + */ +typedef struct { + esp_chip_model_t model; //!< chip model, one of esp_chip_model_t + uint32_t features; //!< bit mask of CHIP_FEATURE_x feature flags + uint8_t cores; //!< number of CPU cores + uint8_t revision; //!< chip revision number +} esp_chip_info_t; + +/** + * @brief Fill an esp_chip_info_t structure with information about the chip + * @param[out] out_info structure to be filled + */ +void esp_chip_info(esp_chip_info_t* out_info); + + +#if CONFIG_ESP32_ECO3_CACHE_LOCK_FIX +/** + * @brief Cache lock bug exists or not + * + * @return + * - ture : bug exists + * - false : bug not exists + */ +bool soc_has_cache_lock_bug(void); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_SYSTEM_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_task.h b/tools/sdk/esp32c3/include/esp_system/include/esp_task.h new file mode 100644 index 00000000..105de599 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_task.h @@ -0,0 +1,60 @@ +// Copyright 2015-2016 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. + +/* Notes: + * 1. Put all task priority and stack size definition in this file + * 2. If the task priority is less than 10, use ESP_TASK_PRIO_MIN + X style, + * otherwise use ESP_TASK_PRIO_MAX - X style + * 3. If this is a daemon task, the macro prefix is ESP_TASKD_, otherwise + * it's ESP_TASK_ + * 4. If the configMAX_PRIORITIES is modified, please make all priority are + * greater than 0 + * 5. Make sure esp_task.h is consistent between wifi lib and idf + */ + +#ifndef _ESP_TASK_H_ +#define _ESP_TASK_H_ + +#include "sdkconfig.h" +#include "freertos/FreeRTOS.h" +#include "freertos/FreeRTOSConfig.h" + +#define ESP_TASK_PRIO_MAX (configMAX_PRIORITIES) +#define ESP_TASK_PRIO_MIN (0) + +/* Bt contoller Task */ +/* controller */ +#define ESP_TASK_BT_CONTROLLER_PRIO (ESP_TASK_PRIO_MAX - 2) +#ifdef CONFIG_NEWLIB_NANO_FORMAT +#define TASK_EXTRA_STACK_SIZE (0) +#else +#define TASK_EXTRA_STACK_SIZE (512) +#endif + +#define BT_TASK_EXTRA_STACK_SIZE TASK_EXTRA_STACK_SIZE +#define ESP_TASK_BT_CONTROLLER_STACK (3584 + TASK_EXTRA_STACK_SIZE) + + +/* idf task */ +#define ESP_TASK_TIMER_PRIO (ESP_TASK_PRIO_MAX - 3) +#define ESP_TASK_TIMER_STACK (CONFIG_ESP_TIMER_TASK_STACK_SIZE + TASK_EXTRA_STACK_SIZE) +#define ESP_TASKD_EVENT_PRIO (ESP_TASK_PRIO_MAX - 5) +#define ESP_TASKD_EVENT_STACK (CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE + TASK_EXTRA_STACK_SIZE) +#define ESP_TASK_TCPIP_PRIO (ESP_TASK_PRIO_MAX - 7) +#define ESP_TASK_TCPIP_STACK (CONFIG_LWIP_TCPIP_TASK_STACK_SIZE + TASK_EXTRA_STACK_SIZE) +#define ESP_TASK_MAIN_PRIO (ESP_TASK_PRIO_MIN + 1) +#define ESP_TASK_MAIN_STACK (CONFIG_ESP_MAIN_TASK_STACK_SIZE + TASK_EXTRA_STACK_SIZE) +#define ESP_TASK_MAIN_CORE CONFIG_ESP_MAIN_TASK_AFFINITY + +#endif diff --git a/tools/sdk/esp32c3/include/esp_system/include/esp_task_wdt.h b/tools/sdk/esp32c3/include/esp_system/include/esp_task_wdt.h new file mode 100644 index 00000000..cf64cfc1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_system/include/esp_task_wdt.h @@ -0,0 +1,147 @@ +// Copyright 2015-2016 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. + +#pragma once + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize the Task Watchdog Timer (TWDT) + * + * This function configures and initializes the TWDT. If the TWDT is already + * initialized when this function is called, this function will update the + * TWDT's timeout period and panic configurations instead. After initializing + * the TWDT, any task can elect to be watched by the TWDT by subscribing to it + * using esp_task_wdt_add(). + * + * @param[in] timeout Timeout period of TWDT in seconds + * @param[in] panic Flag that controls whether the panic handler will be + * executed when the TWDT times out + * + * @return + * - ESP_OK: Initialization was successful + * - ESP_ERR_NO_MEM: Initialization failed due to lack of memory + * + * @note esp_task_wdt_init() must only be called after the scheduler + * started + */ +esp_err_t esp_task_wdt_init(uint32_t timeout, bool panic); + +/** + * @brief Deinitialize the Task Watchdog Timer (TWDT) + * + * This function will deinitialize the TWDT. Calling this function whilst tasks + * are still subscribed to the TWDT, or when the TWDT is already deinitialized, + * will result in an error code being returned. + * + * @return + * - ESP_OK: TWDT successfully deinitialized + * - ESP_ERR_INVALID_STATE: Error, tasks are still subscribed to the TWDT + * - ESP_ERR_NOT_FOUND: Error, TWDT has already been deinitialized + */ +esp_err_t esp_task_wdt_deinit(void); + +/** + * @brief Subscribe a task to the Task Watchdog Timer (TWDT) + * + * This function subscribes a task to the TWDT. Each subscribed task must + * periodically call esp_task_wdt_reset() to prevent the TWDT from elapsing its + * timeout period. Failure to do so will result in a TWDT timeout. If the task + * being subscribed is one of the Idle Tasks, this function will automatically + * enable esp_task_wdt_reset() to called from the Idle Hook of the Idle Task. + * Calling this function whilst the TWDT is uninitialized or attempting to + * subscribe an already subscribed task will result in an error code being + * returned. + * + * @param[in] handle Handle of the task. Input NULL to subscribe the current + * running task to the TWDT + * + * @return + * - ESP_OK: Successfully subscribed the task to the TWDT + * - ESP_ERR_INVALID_ARG: Error, the task is already subscribed + * - ESP_ERR_NO_MEM: Error, could not subscribe the task due to lack of + * memory + * - ESP_ERR_INVALID_STATE: Error, the TWDT has not been initialized yet + */ +esp_err_t esp_task_wdt_add(TaskHandle_t handle); + +/** + * @brief Reset the Task Watchdog Timer (TWDT) on behalf of the currently + * running task + * + * This function will reset the TWDT on behalf of the currently running task. + * Each subscribed task must periodically call this function to prevent the + * TWDT from timing out. If one or more subscribed tasks fail to reset the + * TWDT on their own behalf, a TWDT timeout will occur. If the IDLE tasks have + * been subscribed to the TWDT, they will automatically call this function from + * their idle hooks. Calling this function from a task that has not subscribed + * to the TWDT, or when the TWDT is uninitialized will result in an error code + * being returned. + * + * @return + * - ESP_OK: Successfully reset the TWDT on behalf of the currently + * running task + * - ESP_ERR_NOT_FOUND: Error, the current running task has not subscribed + * to the TWDT + * - ESP_ERR_INVALID_STATE: Error, the TWDT has not been initialized yet + */ +esp_err_t esp_task_wdt_reset(void); + +/** + * @brief Unsubscribes a task from the Task Watchdog Timer (TWDT) + * + * This function will unsubscribe a task from the TWDT. After being + * unsubscribed, the task should no longer call esp_task_wdt_reset(). If the + * task is an IDLE task, this function will automatically disable the calling + * of esp_task_wdt_reset() from the Idle Hook. Calling this function whilst the + * TWDT is uninitialized or attempting to unsubscribe an already unsubscribed + * task from the TWDT will result in an error code being returned. + * + * @param[in] handle Handle of the task. Input NULL to unsubscribe the + * current running task. + * + * @return + * - ESP_OK: Successfully unsubscribed the task from the TWDT + * - ESP_ERR_INVALID_ARG: Error, the task is already unsubscribed + * - ESP_ERR_INVALID_STATE: Error, the TWDT has not been initialized yet + */ +esp_err_t esp_task_wdt_delete(TaskHandle_t handle); + +/** + * @brief Query whether a task is subscribed to the Task Watchdog Timer (TWDT) + * + * This function will query whether a task is currently subscribed to the TWDT, + * or whether the TWDT is initialized. + * + * @param[in] handle Handle of the task. Input NULL to query the current + * running task. + * + * @return: + * - ESP_OK: The task is currently subscribed to the TWDT + * - ESP_ERR_NOT_FOUND: The task is currently not subscribed to the TWDT + * - ESP_ERR_INVALID_STATE: The TWDT is not initialized, therefore no tasks + * can be subscribed + */ +esp_err_t esp_task_wdt_status(TaskHandle_t handle); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_timer/include/esp_private/esp_timer_private.h b/tools/sdk/esp32c3/include/esp_timer/include/esp_private/esp_timer_private.h new file mode 100644 index 00000000..ecd42641 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_timer/include/esp_private/esp_timer_private.h @@ -0,0 +1,70 @@ +// Copyright 2017 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. + +#pragma once + +/** + * @file esp_private/esp_timer_private.h + * + * @brief Interface between common and platform-specific parts of esp_timer. + * + * The functions in this header file are implemented for each supported SoC. + * High level functions defined in esp_timer.c call the functions here to + * interact with the hardware. + * + * Note: The functions from this file are marked as private and are used exclusively + * inside the IDF in the power management and sleep files. + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Notify esp_timer implementation that APB frequency has changed + * + * Called by the frequency switching code. + * + * @param apb_ticks_per_us new number of APB clock ticks per microsecond + */ +void esp_timer_private_update_apb_freq(uint32_t apb_ticks_per_us); + +/** + * @brief Adjust current esp_timer time by a certain value + * + * Called from light sleep code to synchronize esp_timer time with RTC time. + * + * @param time_us adjustment to apply to esp_timer time, in microseconds + */ +void esp_timer_private_advance(int64_t time_us); + +/** + * @brief obtain internal critical section used esp_timer implementation + * This can be used when a sequence of calls to esp_timer has to be made, + * and it is necessary that the state of the timer is consistent between + * the calls. Should be treated in the same way as a spinlock. + * Call esp_timer_unlock to release the lock + */ +void esp_timer_private_lock(void); + +/** + * @brief counterpart of esp_timer_lock + */ +void esp_timer_private_unlock(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_timer/include/esp_timer.h b/tools/sdk/esp32c3/include/esp_timer/include/esp_timer.h new file mode 100644 index 00000000..bb8879cd --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_timer/include/esp_timer.h @@ -0,0 +1,240 @@ +// Copyright 2017 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. + +#pragma once + +/** + * @file esp_timer.h + * @brief microsecond-precision 64-bit timer API, replacement for ets_timer + * + * esp_timer APIs allow components to receive callbacks when a hardware timer + * reaches certain value. The timer provides microsecond accuracy and + * up to 64 bit range. Note that while the timer itself provides microsecond + * accuracy, callbacks are dispatched from an auxiliary task. Some time is + * needed to notify this task from timer ISR, and then to invoke the callback. + * If more than one callback needs to be dispatched at any particular time, + * each subsequent callback will be dispatched only when the previous callback + * returns. Therefore, callbacks should not do much work; instead, they should + * use RTOS notification mechanisms (queues, semaphores, event groups, etc.) to + * pass information to other tasks. + * + * To be implemented: it should be possible to request the callback to be called + * directly from the ISR. This reduces the latency, but has potential impact on + * all other callbacks which need to be dispatched. This option should only be + * used for simple callback functions, which do not take longer than a few + * microseconds to run. + * + * Implementation note: on the ESP32, esp_timer APIs use the "legacy" FRC2 + * timer. Timer callbacks are called from a task running on the PRO CPU. + */ + +#include +#include +#include +#include "esp_err.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Opaque type representing a single esp_timer + */ +typedef struct esp_timer* esp_timer_handle_t; + +/** + * @brief Timer callback function type + * @param arg pointer to opaque user-specific data + */ +typedef void (*esp_timer_cb_t)(void* arg); + + +/** + * @brief Method for dispatching timer callback + */ +typedef enum { + ESP_TIMER_TASK, //!< Callback is called from timer task +#ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD + ESP_TIMER_ISR, //!< Callback is called from timer ISR +#endif + ESP_TIMER_MAX, //!< Count of the methods for dispatching timer callback +} esp_timer_dispatch_t; + +/** + * @brief Timer configuration passed to esp_timer_create + */ +typedef struct { + esp_timer_cb_t callback; //!< Function to call when timer expires + void* arg; //!< Argument to pass to the callback + esp_timer_dispatch_t dispatch_method; //!< Call the callback from task or from ISR + const char* name; //!< Timer name, used in esp_timer_dump function + bool skip_unhandled_events; //!< Skip unhandled events for periodic timers +} esp_timer_create_args_t; + +/** + * @brief Initialize esp_timer library + * + * @note This function is called from startup code. Applications do not need + * to call this function before using other esp_timer APIs. + * + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if allocation has failed + * - ESP_ERR_INVALID_STATE if already initialized + * - other errors from interrupt allocator + */ +esp_err_t esp_timer_init(void); + +/** + * @brief De-initialize esp_timer library + * + * @note Normally this function should not be called from applications + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if not yet initialized + */ +esp_err_t esp_timer_deinit(void); + +/** + * @brief Create an esp_timer instance + * + * @note When done using the timer, delete it with esp_timer_delete function. + * + * @param create_args Pointer to a structure with timer creation arguments. + * Not saved by the library, can be allocated on the stack. + * @param[out] out_handle Output, pointer to esp_timer_handle_t variable which + * will hold the created timer handle. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if some of the create_args are not valid + * - ESP_ERR_INVALID_STATE if esp_timer library is not initialized yet + * - ESP_ERR_NO_MEM if memory allocation fails + */ +esp_err_t esp_timer_create(const esp_timer_create_args_t* create_args, + esp_timer_handle_t* out_handle); + +/** + * @brief Start one-shot timer + * + * Timer should not be running when this function is called. + * + * @param timer timer handle created using esp_timer_create + * @param timeout_us timer timeout, in microseconds relative to the current moment + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the handle is invalid + * - ESP_ERR_INVALID_STATE if the timer is already running + */ +esp_err_t esp_timer_start_once(esp_timer_handle_t timer, uint64_t timeout_us); + +/** + * @brief Start a periodic timer + * + * Timer should not be running when this function is called. This function will + * start the timer which will trigger every 'period' microseconds. + * + * @param timer timer handle created using esp_timer_create + * @param period timer period, in microseconds + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the handle is invalid + * - ESP_ERR_INVALID_STATE if the timer is already running + */ +esp_err_t esp_timer_start_periodic(esp_timer_handle_t timer, uint64_t period); + +/** + * @brief Stop the timer + * + * This function stops the timer previously started using esp_timer_start_once + * or esp_timer_start_periodic. + * + * @param timer timer handle created using esp_timer_create + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the timer is not running + */ +esp_err_t esp_timer_stop(esp_timer_handle_t timer); + +/** + * @brief Delete an esp_timer instance + * + * The timer must be stopped before deleting. A one-shot timer which has expired + * does not need to be stopped. + * + * @param timer timer handle allocated using esp_timer_create + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if the timer is running + */ +esp_err_t esp_timer_delete(esp_timer_handle_t timer); + +/** + * @brief Get time in microseconds since boot + * @return number of microseconds since underlying timer has been started + */ +int64_t esp_timer_get_time(void); + +/** + * @brief Get the timestamp when the next timeout is expected to occur + * @return Timestamp of the nearest timer event, in microseconds. + * The timebase is the same as for the values returned by esp_timer_get_time. + */ +int64_t esp_timer_get_next_alarm(void); + +/** + * @brief Dump the list of timers to a stream + * + * If CONFIG_ESP_TIMER_PROFILING option is enabled, this prints the list of all + * the existing timers. Otherwise, only the list active timers is printed. + * + * The format is: + * + * name period alarm times_armed times_triggered total_callback_run_time + * + * where: + * + * name — timer name (if CONFIG_ESP_TIMER_PROFILING is defined), or timer pointer + * period — period of timer, in microseconds, or 0 for one-shot timer + * alarm - time of the next alarm, in microseconds since boot, or 0 if the timer + * is not started + * + * The following fields are printed if CONFIG_ESP_TIMER_PROFILING is defined: + * + * times_armed — number of times the timer was armed via esp_timer_start_X + * times_triggered - number of times the callback was called + * total_callback_run_time - total time taken by callback to execute, across all calls + * + * @param stream stream (such as stdout) to dump the information to + * @return + * - ESP_OK on success + * - ESP_ERR_NO_MEM if can not allocate temporary buffer for the output + */ +esp_err_t esp_timer_dump(FILE* stream); + +#ifdef CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD +/** + * @brief Requests a context switch from a timer callback function. + * + * This only works for a timer that has an ISR dispatch method. + * The context switch will be called after all ISR dispatch timers have been processed. + */ +void esp_timer_isr_dispatch_need_yield(void); +#endif // CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_websocket_client/include/esp_websocket_client.h b/tools/sdk/esp32c3/include/esp_websocket_client/include/esp_websocket_client.h new file mode 100644 index 00000000..5ef08035 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_websocket_client/include/esp_websocket_client.h @@ -0,0 +1,279 @@ +// Copyright 2015-2018 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. + +#ifndef _ESP_WEBSOCKET_CLIENT_H_ +#define _ESP_WEBSOCKET_CLIENT_H_ + + +#include +#include +#include +#include "freertos/FreeRTOS.h" +#include "esp_err.h" +#include "esp_event.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct esp_websocket_client *esp_websocket_client_handle_t; + +ESP_EVENT_DECLARE_BASE(WEBSOCKET_EVENTS); // declaration of the task events family + +/** + * @brief Websocket Client events id + */ +typedef enum { + WEBSOCKET_EVENT_ANY = -1, + WEBSOCKET_EVENT_ERROR = 0, /*!< This event occurs when there are any errors during execution */ + WEBSOCKET_EVENT_CONNECTED, /*!< Once the Websocket has been connected to the server, no data exchange has been performed */ + WEBSOCKET_EVENT_DISCONNECTED, /*!< The connection has been disconnected */ + WEBSOCKET_EVENT_DATA, /*!< When receiving data from the server, possibly multiple portions of the packet */ + WEBSOCKET_EVENT_CLOSED, /*!< The connection has been closed cleanly */ + WEBSOCKET_EVENT_MAX +} esp_websocket_event_id_t; + +/** + * @brief Websocket event data + */ +typedef struct { + const char *data_ptr; /*!< Data pointer */ + int data_len; /*!< Data length */ + uint8_t op_code; /*!< Received opcode */ + esp_websocket_client_handle_t client; /*!< esp_websocket_client_handle_t context */ + void *user_context; /*!< user_data context, from esp_websocket_client_config_t user_data */ + int payload_len; /*!< Total payload length, payloads exceeding buffer will be posted through multiple events */ + int payload_offset; /*!< Actual offset for the data associated with this event */ +} esp_websocket_event_data_t; + +/** + * @brief Websocket Client transport + */ +typedef enum { + WEBSOCKET_TRANSPORT_UNKNOWN = 0x0, /*!< Transport unknown */ + WEBSOCKET_TRANSPORT_OVER_TCP, /*!< Transport over tcp */ + WEBSOCKET_TRANSPORT_OVER_SSL, /*!< Transport over ssl */ +} esp_websocket_transport_t; + +/** + * @brief Websocket client setup configuration + */ +typedef struct { + const char *uri; /*!< Websocket URI, the information on the URI can be overrides the other fields below, if any */ + const char *host; /*!< Domain or IP as string */ + int port; /*!< Port to connect, default depend on esp_websocket_transport_t (80 or 443) */ + const char *username; /*!< Using for Http authentication - Not supported for now */ + const char *password; /*!< Using for Http authentication - Not supported for now */ + const char *path; /*!< HTTP Path, if not set, default is `/` */ + bool disable_auto_reconnect; /*!< Disable the automatic reconnect function when disconnected */ + void *user_context; /*!< HTTP user data context */ + int task_prio; /*!< Websocket task priority */ + int task_stack; /*!< Websocket task stack */ + int buffer_size; /*!< Websocket buffer size */ + const char *cert_pem; /*!< Pointer to certificate data in PEM or DER format for server verify (with SSL), default is NULL, not required to verify the server. PEM-format must have a terminating NULL-character. DER-format requires the length to be passed in cert_len. */ + size_t cert_len; /*!< Length of the buffer pointed to by cert_pem. May be 0 for null-terminated pem */ + const char *client_cert; /*!< Pointer to certificate data in PEM or DER format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_key` has to be provided. PEM-format must have a terminating NULL-character. DER-format requires the length to be passed in client_cert_len. */ + size_t client_cert_len; /*!< Length of the buffer pointed to by client_cert. May be 0 for null-terminated pem */ + const char *client_key; /*!< Pointer to private key data in PEM or DER format for SSL mutual authentication, default is NULL, not required if mutual authentication is not needed. If it is not NULL, also `client_cert` has to be provided. PEM-format must have a terminating NULL-character. DER-format requires the length to be passed in client_key_len */ + size_t client_key_len; /*!< Length of the buffer pointed to by client_key_pem. May be 0 for null-terminated pem */ + esp_websocket_transport_t transport; /*!< Websocket transport type, see `esp_websocket_transport_t */ + char *subprotocol; /*!< Websocket subprotocol */ + char *user_agent; /*!< Websocket user-agent */ + char *headers; /*!< Websocket additional headers */ + int pingpong_timeout_sec; /*!< Period before connection is aborted due to no PONGs received */ + bool disable_pingpong_discon; /*!< Disable auto-disconnect due to no PONG received within pingpong_timeout_sec */ + bool use_global_ca_store; /*!< Use a global ca_store for all the connections in which this bool is set. */ + bool skip_cert_common_name_check;/*!< Skip any validation of server certificate CN field */ + bool keep_alive_enable; /*!< Enable keep-alive timeout */ + int keep_alive_idle; /*!< Keep-alive idle time. Default is 5 (second) */ + int keep_alive_interval; /*!< Keep-alive interval time. Default is 5 (second) */ + int keep_alive_count; /*!< Keep-alive packet retry send count. Default is 3 counts */ + size_t ping_interval_sec; /*!< Websocket ping interval, defaults to 10 seconds if not set */ + struct ifreq *if_name; /*!< The name of interface for data to go through. Use the default interface without setting */ +} esp_websocket_client_config_t; + +/** + * @brief Start a Websocket session + * This function must be the first function to call, + * and it returns a esp_websocket_client_handle_t that you must use as input to other functions in the interface. + * This call MUST have a corresponding call to esp_websocket_client_destroy when the operation is complete. + * + * @param[in] config The configuration + * + * @return + * - `esp_websocket_client_handle_t` + * - NULL if any errors + */ +esp_websocket_client_handle_t esp_websocket_client_init(const esp_websocket_client_config_t *config); + +/** + * @brief Set URL for client, when performing this behavior, the options in the URL will replace the old ones + * Must stop the WebSocket client before set URI if the client has been connected + * + * @param[in] client The client + * @param[in] uri The uri + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_set_uri(esp_websocket_client_handle_t client, const char *uri); + +/** + * @brief Open the WebSocket connection + * + * @param[in] client The client + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_start(esp_websocket_client_handle_t client); + +/** + * @brief Stops the WebSocket connection without websocket closing handshake + * + * This API stops ws client and closes TCP connection directly without sending + * close frames. It is a good practice to close the connection in a clean way + * using esp_websocket_client_close(). + * + * Notes: + * - Cannot be called from the websocket event handler + * + * @param[in] client The client + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_stop(esp_websocket_client_handle_t client); + +/** + * @brief Destroy the WebSocket connection and free all resources. + * This function must be the last function to call for an session. + * It is the opposite of the esp_websocket_client_init function and must be called with the same handle as input that a esp_websocket_client_init call returned. + * This might close all connections this handle has used. + * + * Notes: + * - Cannot be called from the websocket event handler + * + * @param[in] client The client + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_destroy(esp_websocket_client_handle_t client); + +/** + * @brief Generic write data to the WebSocket connection; defaults to binary send + * + * @param[in] client The client + * @param[in] data The data + * @param[in] len The length + * @param[in] timeout Write data timeout in RTOS ticks + * + * @return + * - Number of data was sent + * - (-1) if any errors + */ +int esp_websocket_client_send(esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout); + +/** + * @brief Write binary data to the WebSocket connection (data send with WS OPCODE=02, i.e. binary) + * + * @param[in] client The client + * @param[in] data The data + * @param[in] len The length + * @param[in] timeout Write data timeout in RTOS ticks + * + * @return + * - Number of data was sent + * - (-1) if any errors + */ +int esp_websocket_client_send_bin(esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout); + +/** + * @brief Write textual data to the WebSocket connection (data send with WS OPCODE=01, i.e. text) + * + * @param[in] client The client + * @param[in] data The data + * @param[in] len The length + * @param[in] timeout Write data timeout in RTOS ticks + * + * @return + * - Number of data was sent + * - (-1) if any errors + */ +int esp_websocket_client_send_text(esp_websocket_client_handle_t client, const char *data, int len, TickType_t timeout); + +/** + * @brief Close the WebSocket connection in a clean way + * + * Sequence of clean close initiated by client: + * * Client sends CLOSE frame + * * Client waits until server echos the CLOSE frame + * * Client waits until server closes the connection + * * Client is stopped the same way as by the `esp_websocket_client_stop()` + * + * Notes: + * - Cannot be called from the websocket event handler + * + * @param[in] client The client + * @param[in] timeout Timeout in RTOS ticks for waiting + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_close(esp_websocket_client_handle_t client, TickType_t timeout); + +/** + * @brief Close the WebSocket connection in a clean way with custom code/data + * Closing sequence is the same as for esp_websocket_client_close() + * + * Notes: + * - Cannot be called from the websocket event handler + * + * @param[in] client The client + * @param[in] code Close status code as defined in RFC6455 section-7.4 + * @param[in] data Additional data to closing message + * @param[in] len The length of the additional data + * @param[in] timeout Timeout in RTOS ticks for waiting + * + * @return esp_err_t + */ +esp_err_t esp_websocket_client_close_with_code(esp_websocket_client_handle_t client, int code, const char *data, int len, TickType_t timeout); + +/** + * @brief Check the WebSocket client connection state + * + * @param[in] client The client handle + * + * @return + * - true + * - false + */ +bool esp_websocket_client_is_connected(esp_websocket_client_handle_t client); + +/** + * @brief Register the Websocket Events + * + * @param client The client handle + * @param event The event id + * @param event_handler The callback function + * @param event_handler_arg User context + * @return esp_err_t + */ +esp_err_t esp_websocket_register_events(esp_websocket_client_handle_t client, + esp_websocket_event_id_t event, + esp_event_handler_t event_handler, + void *event_handler_arg); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/esp32c3/include/phy_init_data.h b/tools/sdk/esp32c3/include/esp_wifi/esp32c3/include/phy_init_data.h new file mode 100644 index 00000000..774be4e4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/esp32c3/include/phy_init_data.h @@ -0,0 +1,185 @@ +// Copyright 2016-2020 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. + +#ifndef PHY_INIT_DATA_H +#define PHY_INIT_DATA_H /* don't use #pragma once here, we compile this file sometimes */ +#include "esp_phy_init.h" +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// constrain a value between 'low' and 'high', inclusive +#define LIMIT(val, low, high) ((val < low) ? low : (val > high) ? high : val) + +#define PHY_INIT_MAGIC "PHYINIT" + +// define the lowest tx power as LOWEST_PHY_TX_POWER +#define PHY_TX_POWER_LOWEST LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 52) +#define PHY_TX_POWER_OFFSET 44 +#define PHY_TX_POWER_NUM 5 + +#if CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN +#define PHY_CRC_ALGORITHM 1 +#define PHY_COUNTRY_CODE_LEN 2 +#define PHY_INIT_DATA_TYPE_OFFSET 126 +#define PHY_SUPPORT_MULTIPLE_BIN_OFFSET 125 +#endif + +static const char phy_init_magic_pre[] = PHY_INIT_MAGIC; + +/** + * @brief Structure containing default recommended PHY initialization parameters. + */ +static const esp_phy_init_data_t phy_init_data= { { + 3, + 3, + 0x05, + 0x09, + 0x06, + 0x05, + 0x03, + 0x06, + 0x05, + 0x04, + 0x06, + 0x04, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x05, + 0x09, + 0x06, + 0x05, + 0x03, + 0x06, + 0x05, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0xfc, + 0xfc, + 0xfe, + 0xf0, + 0xf0, + 0xf0, + 0xe0, + 0xe0, + 0xe0, + 0x18, + 0x18, + 0x18, + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 84), + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 72), + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 66), + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 60), + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 56), + LIMIT(CONFIG_ESP32_PHY_MAX_TX_POWER * 4, 0, 52), + 0, + 1, + 1, + 2, + 2, + 3, + 4, + 5, + 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, +} }; + +static const char phy_init_magic_post[] = PHY_INIT_MAGIC; + +#if CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN +/** + * @brief PHY init data control infomation structure + */ +typedef struct { + uint8_t control_info_checksum[4]; /*!< 4-byte control infomation checksum */ + uint8_t multiple_bin_checksum[4]; /*!< 4-byte multiple bin checksum */ + uint8_t check_algorithm; /*!< check algorithm */ + uint8_t version; /*!< PHY init data bin version */ + uint8_t number; /*!< PHY init data bin number */ + uint8_t length[2]; /*!< Length of each PHY init data bin */ + uint8_t reserved[19]; /*!< 19-byte reserved */ +} __attribute__ ((packed)) phy_control_info_data_t; + +/** + * @brief Country corresponds to PHY init data type structure + */ +typedef struct { + char cc[PHY_COUNTRY_CODE_LEN]; + uint8_t type; +} phy_country_to_bin_type_t; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* PHY_INIT_DATA_H */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist.h new file mode 100644 index 00000000..1ff624d9 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist.h @@ -0,0 +1,93 @@ +// Copyright 2015-2018 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. + +#ifndef __ESP_COEXIST_H__ +#define __ESP_COEXIST_H__ + +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief coex prefer value + */ +typedef enum { + ESP_COEX_PREFER_WIFI = 0, /*!< Prefer to WiFi, WiFi will have more opportunity to use RF */ + ESP_COEX_PREFER_BT, /*!< Prefer to bluetooth, bluetooth will have more opportunity to use RF */ + ESP_COEX_PREFER_BALANCE, /*!< Do balance of WiFi and bluetooth */ + ESP_COEX_PREFER_NUM, /*!< Prefer value numbers */ +} esp_coex_prefer_t; + +/** + * @brief coex status type + */ +typedef enum { + ESP_COEX_ST_TYPE_WIFI = 0, + ESP_COEX_ST_TYPE_BLE, + ESP_COEX_ST_TYPE_BT, +} esp_coex_status_type_t; + +#define ESP_COEX_BLE_ST_MESH_CONFIG 0x08 +#define ESP_COEX_BLE_ST_MESH_TRAFFIC 0x10 +#define ESP_COEX_BLE_ST_MESH_STANDBY 0x20 + +#define ESP_COEX_BT_ST_A2DP_STREAMING 0x10 +#define ESP_COEX_BT_ST_A2DP_PAUSED 0x20 + +/** + * @brief Get software coexist version string + * + * @return : version string + */ +const char *esp_coex_version_get(void); + +/** + * @deprecated Use esp_coex_status_bit_set() and esp_coex_status_bit_clear() instead. + * Set coexist preference of performance + * For example, if prefer to bluetooth, then it will make A2DP(play audio via classic bt) + * more smooth while wifi is runnning something. + * If prefer to wifi, it will do similar things as prefer to bluetooth. + * Default, it prefer to balance. + * + * @param prefer : the prefer enumeration value + * @return : ESP_OK - success, other - failed + */ +esp_err_t esp_coex_preference_set(esp_coex_prefer_t prefer); + +/** + * @brief Set coex schm status + * @param type : WIFI/BLE/BT + * @param status : WIFI/BLE/BT STATUS + * @return : ESP_OK - success, other - failed + */ +esp_err_t esp_coex_status_bit_set(esp_coex_status_type_t type, uint32_t status); + +/** + * @brief Clear coex schm status + * @param type : WIFI/BLE/BT + * @param status : WIFI/BLE/BT STATUS + * @return : ESP_OK - success, other - failed + */ +esp_err_t esp_coex_status_bit_clear(esp_coex_status_type_t type, uint32_t status); + + +#ifdef __cplusplus +} +#endif + + +#endif /* __ESP_COEXIST_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_adapter.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_adapter.h new file mode 100644 index 00000000..eaac86d0 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_adapter.h @@ -0,0 +1,63 @@ +// Copyright 2019 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. + +#ifndef __ESP_COEXIST_ADAPTER_H__ +#define __ESP_COEXIST_ADAPTER_H__ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define COEX_ADAPTER_VERSION 0x00000002 +#define COEX_ADAPTER_MAGIC 0xDEADBEAF + +#define COEX_ADAPTER_FUNCS_TIME_BLOCKING 0xffffffff + +typedef struct { + int32_t _version; +#if CONFIG_IDF_TARGET_ESP32 + void *(* _spin_lock_create)(void); + void (* _spin_lock_delete)(void *lock); + uint32_t (*_int_disable)(void *mux); + void (*_int_enable)(void *mux, uint32_t tmp); +#endif + void (*_task_yield_from_isr)(void); + void *(*_semphr_create)(uint32_t max, uint32_t init); + void (*_semphr_delete)(void *semphr); + int32_t (*_semphr_take_from_isr)(void *semphr, void *hptw); + int32_t (*_semphr_give_from_isr)(void *semphr, void *hptw); + int32_t (*_semphr_take)(void *semphr, uint32_t block_time_tick); + int32_t (*_semphr_give)(void *semphr); + int (* _is_in_isr)(void); + void * (* _malloc_internal)(size_t size); + void (* _free)(void *p); +#if CONFIG_IDF_TARGET_ESP32 + void (* _timer_disarm)(void *timer); + void (* _timer_done)(void *ptimer); + void (* _timer_setfn)(void *ptimer, void *pfunction, void *parg); + void (* _timer_arm_us)(void *ptimer, uint32_t us, bool repeat); +#endif + int64_t (* _esp_timer_get_time)(void); + int32_t _magic; +} coex_adapter_funcs_t; + +extern coex_adapter_funcs_t g_coex_adapter_funcs; + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_COEXIST_ADAPTER_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_internal.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_internal.h new file mode 100644 index 00000000..3501f0da --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_coexist_internal.h @@ -0,0 +1,228 @@ +// Copyright 2018-2018 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. + +#ifndef __ESP_COEXIST_INTERNAL_H__ +#define __ESP_COEXIST_INTERNAL_H__ + +#include +#include "esp_coexist_adapter.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + COEX_PREFER_WIFI = 0, + COEX_PREFER_BT, + COEX_PREFER_BALANCE, + COEX_PREFER_NUM, +} coex_prefer_t; + +typedef void (* coex_func_cb_t)(uint32_t event, int sched_cnt); + +/** + * @brief Pre-Init software coexist + * extern function for internal use. + * + * @return Init ok or failed. + */ +esp_err_t coex_pre_init(void); + +/** + * @brief Init software coexist + * extern function for internal use. + * + * @return Init ok or failed. + */ +esp_err_t coex_init(void); + +/** + * @brief De-init software coexist + * extern function for internal use. + */ +void coex_deinit(void); + +/** + * @brief Enable software coexist + * extern function for internal use. + * + * @return Enable ok or failed. + */ +esp_err_t coex_enable(void); + +/** + * @brief Disable software coexist + * extern function for internal use. + */ +void coex_disable(void); + +/** + * @brief Get software coexist version string + * extern function for internal use. + * @return : version string + */ +const char *coex_version_get(void); + +/** + * @brief Coexist performance preference set from libbt.a + * extern function for internal use. + * + * @param prefer : the prefer enumeration value + * @return : ESP_OK - success, other - failed + */ +esp_err_t coex_preference_set(coex_prefer_t prefer); + +/** + * @brief Get software coexist status. + * @return : software coexist status + */ +uint32_t coex_status_get(void); + +/** + * @brief Set software coexist condition. + * @return : software coexist condition + */ +void coex_condition_set(uint32_t type, bool dissatisfy); + +/** + * @brief WiFi requests coexistence. + * + * @param event : WiFi event + * @param latency : WiFi will request coexistence after latency + * @param duration : duration for WiFi to request coexistence + * @return : 0 - success, other - failed + */ +int coex_wifi_request(uint32_t event, uint32_t latency, uint32_t duration); + +/** + * @brief WiFi release coexistence. + * + * @param event : WiFi event + * @return : 0 - success, other - failed + */ +int coex_wifi_release(uint32_t event); + +/** + * @brief Set WiFi channel to coexistence module. + * + * @param primary : WiFi primary channel + * @param secondary : WiFi secondary channel + * @return : 0 - success, other - failed + */ +int coex_wifi_channel_set(uint8_t primary, uint8_t secondary); + +/** + * @brief Get coexistence event duration. + * + * @param event : Coexistence event + * @param duration: Coexistence event duration + * @return : 0 - success, other - failed + */ +int coex_event_duration_get(uint32_t event, uint32_t *duration); + +#if SOC_COEX_HW_PTI +/** + * @brief Get coexistence event priority. + * + * @param event : Coexistence event + * @param pti: Coexistence event priority + * @return : 0 - success, other - failed + */ +int coex_pti_get(uint32_t event, uint8_t *pti); +#endif + +/** + * @brief Clear coexistence status. + * + * @param type : Coexistence status type + * @param status: Coexistence status + */ +void coex_schm_status_bit_clear(uint32_t type, uint32_t status); + +/** + * @brief Set coexistence status. + * + * @param type : Coexistence status type + * @param status: Coexistence status + */ +void coex_schm_status_bit_set(uint32_t type, uint32_t status); + +/** + * @brief Set coexistence scheme interval. + * + * @param interval : Coexistence scheme interval + * @return : 0 - success, other - failed + */ +int coex_schm_interval_set(uint32_t interval); + +/** + * @brief Get coexistence scheme interval. + * + * @return : Coexistence scheme interval + */ +uint32_t coex_schm_interval_get(void); + +/** + * @brief Get current coexistence scheme period. + * + * @return : Coexistence scheme period + */ +uint8_t coex_schm_curr_period_get(void); + +/** + * @brief Get current coexistence scheme phase. + * + * @return : Coexistence scheme phase + */ +void * coex_schm_curr_phase_get(void); + +/** + * @brief Set current coexistence scheme phase index. + * + * @param interval : Coexistence scheme phase index + * @return : 0 - success, other - failed + */ +int coex_schm_curr_phase_idx_set(int idx); + +/** + * @brief Get current coexistence scheme phase index. + * + * @return : Coexistence scheme phase index + */ +int coex_schm_curr_phase_idx_get(void); + +/** + * @brief Register coexistence adapter functions. + * + * @param funcs : coexistence adapter functions + * @return : ESP_OK - success, other - failed + */ +esp_err_t esp_coex_adapter_register(coex_adapter_funcs_t *funcs); + +/** + * @brief Check the MD5 values of the coexistence adapter header files in IDF and WiFi library + * + * @attention 1. It is used for internal CI version check + * + * @return + * - ESP_OK : succeed + * - ESP_WIFI_INVALID_ARG : MD5 check fail + */ +esp_err_t esp_coex_adapter_funcs_md5_check(const char *md5); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_COEXIST_INTERNAL_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh.h new file mode 100644 index 00000000..242e3ad8 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh.h @@ -0,0 +1,1672 @@ +// Copyright 2017-2018 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. + +/* + * Software Stack demonstrated: + * |------------------------------------------------------------------------------| + * | | | + * | | Application | + * | |-----------------------------------------------------------------| + * | | | Protocols: | | | | | + * | | Mesh Stack | HTTP, DNS, | | | Other | | + * | RTOS: | (Networking, | DHCP, ... | | | Components | | + * | (freeRTOS) | self-healing, |------------| | | | | + * | | flow control, | Network Stack: | | | | + * | | ...) | (LwIP) | | | | + * | |-----------------------------------| |---------------| | + * | | | | + * | | Wi-Fi Driver | | + * | |--------------------------------------------------| | + * | | | + * | | Platform HAL | + * |------------------------------------------------------------------------------| + * + * System Events delivery: + * + * |---------------| + * | | default handler + * | Wi-Fi stack | events |---------------------| + * | | -------------> | | + * |---------------| | | + * | event task | + * |---------------| events | | + * | | -------------> | | + * | LwIP stack | |---------------------| + * | |--------| + * |---------------| | + * | mesh event callback handler + * | |----------------------------| + * |-----> | | + * |---------------| | application | + * | | events | task | + * | mesh stack | -------------> | | + * | | |----------------------------| + * |---------------| + * + * + * Mesh Stack + * + * Mesh event defines almost all system events applications tasks need. + * Mesh event contains Wi-Fi connection states on station interface, children connection states on softAP interface and etc.. + * Applications need to register a mesh event callback handler by API esp_mesh_set_config() firstly. + * This handler is to receive events posted from mesh stack and LwIP stack. + * Applications could add relative handler for each event. + * Examples: + * (1) Applications could use Wi-Fi station connect states to decide when to send data to its parent, to the root or to external IP network; + * (2) Applications could use Wi-Fi softAP states to decide when to send data to its children. + * + * In present implementation, applications are able to access mesh stack directly without having to go through LwIP stack. + * Applications use esp_mesh_send() and esp_mesh_recv() to send and receive messages over the mesh network. + * In mesh stack design, normal devices don't require LwIP stack. But since IDF hasn't supported system without initializing LwIP stack yet, + * applications still need to do LwIP initialization and two more things are required to be done + * (1) stop DHCP server on softAP interface by default + * (2) stop DHCP client on station interface by default. + * Examples: + * tcpip_adapter_init(); + * tcpip_adapter_dhcps_stop(TCPIP_ADAPTER_IF_AP); + * tcpip_adapter_dhcpc_stop(TCPIP_ADAPTER_IF_STA); + * + * Over the mesh network, only the root is able to access external IP network. + * In application mesh event handler, once a device becomes a root, start DHCP client immediately whether DHCP is chosen. + */ + +#ifndef __ESP_MESH_H__ +#define __ESP_MESH_H__ + +#include "esp_err.h" +#include "esp_wifi.h" +#include "esp_wifi_types.h" +#include "esp_mesh_internal.h" +#include "lwip/ip_addr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************* + * Constants + *******************************************************/ +#define MESH_ROOT_LAYER (1) /**< root layer value */ +#define MESH_MTU (1500) /**< max transmit unit(in bytes) */ +#define MESH_MPS (1472) /**< max payload size(in bytes) */ +/** + * @brief Mesh error code definition + */ +#define ESP_ERR_MESH_WIFI_NOT_START (ESP_ERR_MESH_BASE + 1) /**< Wi-Fi isn't started */ +#define ESP_ERR_MESH_NOT_INIT (ESP_ERR_MESH_BASE + 2) /**< mesh isn't initialized */ +#define ESP_ERR_MESH_NOT_CONFIG (ESP_ERR_MESH_BASE + 3) /**< mesh isn't configured */ +#define ESP_ERR_MESH_NOT_START (ESP_ERR_MESH_BASE + 4) /**< mesh isn't started */ +#define ESP_ERR_MESH_NOT_SUPPORT (ESP_ERR_MESH_BASE + 5) /**< not supported yet */ +#define ESP_ERR_MESH_NOT_ALLOWED (ESP_ERR_MESH_BASE + 6) /**< operation is not allowed */ +#define ESP_ERR_MESH_NO_MEMORY (ESP_ERR_MESH_BASE + 7) /**< out of memory */ +#define ESP_ERR_MESH_ARGUMENT (ESP_ERR_MESH_BASE + 8) /**< illegal argument */ +#define ESP_ERR_MESH_EXCEED_MTU (ESP_ERR_MESH_BASE + 9) /**< packet size exceeds MTU */ +#define ESP_ERR_MESH_TIMEOUT (ESP_ERR_MESH_BASE + 10) /**< timeout */ +#define ESP_ERR_MESH_DISCONNECTED (ESP_ERR_MESH_BASE + 11) /**< disconnected with parent on station interface */ +#define ESP_ERR_MESH_QUEUE_FAIL (ESP_ERR_MESH_BASE + 12) /**< queue fail */ +#define ESP_ERR_MESH_QUEUE_FULL (ESP_ERR_MESH_BASE + 13) /**< queue full */ +#define ESP_ERR_MESH_NO_PARENT_FOUND (ESP_ERR_MESH_BASE + 14) /**< no parent found to join the mesh network */ +#define ESP_ERR_MESH_NO_ROUTE_FOUND (ESP_ERR_MESH_BASE + 15) /**< no route found to forward the packet */ +#define ESP_ERR_MESH_OPTION_NULL (ESP_ERR_MESH_BASE + 16) /**< no option found */ +#define ESP_ERR_MESH_OPTION_UNKNOWN (ESP_ERR_MESH_BASE + 17) /**< unknown option */ +#define ESP_ERR_MESH_XON_NO_WINDOW (ESP_ERR_MESH_BASE + 18) /**< no window for software flow control on upstream */ +#define ESP_ERR_MESH_INTERFACE (ESP_ERR_MESH_BASE + 19) /**< low-level Wi-Fi interface error */ +#define ESP_ERR_MESH_DISCARD_DUPLICATE (ESP_ERR_MESH_BASE + 20) /**< discard the packet due to the duplicate sequence number */ +#define ESP_ERR_MESH_DISCARD (ESP_ERR_MESH_BASE + 21) /**< discard the packet */ +#define ESP_ERR_MESH_VOTING (ESP_ERR_MESH_BASE + 22) /**< vote in progress */ +#define ESP_ERR_MESH_XMIT (ESP_ERR_MESH_BASE + 23) /**< XMIT */ +#define ESP_ERR_MESH_QUEUE_READ (ESP_ERR_MESH_BASE + 24) /**< error in reading queue */ +#define ESP_ERR_MESH_PS (ESP_ERR_MESH_BASE + 25) /**< mesh PS is not specified as enable or disable */ +#define ESP_ERR_MESH_RECV_RELEASE (ESP_ERR_MESH_BASE + 26) /**< release esp_mesh_recv_toDS */ + +/** + * @brief Flags bitmap for esp_mesh_send() and esp_mesh_recv() + */ +#define MESH_DATA_ENC (0x01) /**< data encrypted (Unimplemented) */ +#define MESH_DATA_P2P (0x02) /**< point-to-point delivery over the mesh network */ +#define MESH_DATA_FROMDS (0x04) /**< receive from external IP network */ +#define MESH_DATA_TODS (0x08) /**< identify this packet is target to external IP network */ +#define MESH_DATA_NONBLOCK (0x10) /**< esp_mesh_send() non-block */ +#define MESH_DATA_DROP (0x20) /**< in the situation of the root having been changed, identify this packet can be dropped by new root */ +#define MESH_DATA_GROUP (0x40) /**< identify this packet is target to a group address */ + +/** + * @brief Option definitions for esp_mesh_send() and esp_mesh_recv() + */ +#define MESH_OPT_SEND_GROUP (7) /**< data transmission by group; used with esp_mesh_send() and shall have payload */ +#define MESH_OPT_RECV_DS_ADDR (8) /**< return a remote IP address; used with esp_mesh_send() and esp_mesh_recv() */ + +/** + * @brief Flag of mesh networking IE + */ +#define MESH_ASSOC_FLAG_VOTE_IN_PROGRESS (0x02) /**< vote in progress */ +#define MESH_ASSOC_FLAG_NETWORK_FREE (0x08) /**< no root in current network */ +#define MESH_ASSOC_FLAG_ROOTS_FOUND (0x20) /**< root conflict is found */ +#define MESH_ASSOC_FLAG_ROOT_FIXED (0x40) /**< fixed root */ + + +/** + * @brief Mesh PS (Power Save) duty cycle type + */ +#define MESH_PS_DEVICE_DUTY_REQUEST (0x01) /**< requests to join a network PS without specifying a device duty cycle. After the + device joins the network, a network duty cycle will be provided by the network */ +#define MESH_PS_DEVICE_DUTY_DEMAND (0x04) /**< requests to join a network PS and specifies a demanded device duty cycle */ +#define MESH_PS_NETWORK_DUTY_MASTER (0x80) /**< indicates the device is the NWK-DUTY-MASTER (network duty cycle master) */ + +/** + * @brief Mesh PS (Power Save) duty cycle applied rule + */ +#define MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE (0) /** the specified network duty is applied to the entire network <*/ +#define MESH_PS_NETWORK_DUTY_APPLIED_UPLINK (1) /** the specified network duty is applied to only the up-link path <*/ + +/******************************************************* + * Enumerations + *******************************************************/ +/** + * @brief Enumerated list of mesh event id + */ +typedef enum { + MESH_EVENT_STARTED, /**< mesh is started */ + MESH_EVENT_STOPPED, /**< mesh is stopped */ + MESH_EVENT_CHANNEL_SWITCH, /**< channel switch */ + MESH_EVENT_CHILD_CONNECTED, /**< a child is connected on softAP interface */ + MESH_EVENT_CHILD_DISCONNECTED, /**< a child is disconnected on softAP interface */ + MESH_EVENT_ROUTING_TABLE_ADD, /**< routing table is changed by adding newly joined children */ + MESH_EVENT_ROUTING_TABLE_REMOVE, /**< routing table is changed by removing leave children */ + MESH_EVENT_PARENT_CONNECTED, /**< parent is connected on station interface */ + MESH_EVENT_PARENT_DISCONNECTED, /**< parent is disconnected on station interface */ + MESH_EVENT_NO_PARENT_FOUND, /**< no parent found */ + MESH_EVENT_LAYER_CHANGE, /**< layer changes over the mesh network */ + MESH_EVENT_TODS_STATE, /**< state represents whether the root is able to access external IP network */ + MESH_EVENT_VOTE_STARTED, /**< the process of voting a new root is started either by children or by the root */ + MESH_EVENT_VOTE_STOPPED, /**< the process of voting a new root is stopped */ + MESH_EVENT_ROOT_ADDRESS, /**< the root address is obtained. It is posted by mesh stack automatically. */ + MESH_EVENT_ROOT_SWITCH_REQ, /**< root switch request sent from a new voted root candidate */ + MESH_EVENT_ROOT_SWITCH_ACK, /**< root switch acknowledgment responds the above request sent from current root */ + MESH_EVENT_ROOT_ASKED_YIELD, /**< the root is asked yield by a more powerful existing root. If self organized is disabled + and this device is specified to be a root by users, users should set a new parent + for this device. if self organized is enabled, this device will find a new parent + by itself, users could ignore this event. */ + MESH_EVENT_ROOT_FIXED, /**< when devices join a network, if the setting of Fixed Root for one device is different + from that of its parent, the device will update the setting the same as its parent's. + Fixed Root Setting of each device is variable as that setting changes of the root. */ + MESH_EVENT_SCAN_DONE, /**< if self-organized networking is disabled, user can call esp_wifi_scan_start() to trigger + this event, and add the corresponding scan done handler in this event. */ + MESH_EVENT_NETWORK_STATE, /**< network state, such as whether current mesh network has a root. */ + MESH_EVENT_STOP_RECONNECTION, /**< the root stops reconnecting to the router and non-root devices stop reconnecting to their parents. */ + MESH_EVENT_FIND_NETWORK, /**< when the channel field in mesh configuration is set to zero, mesh stack will perform a + full channel scan to find a mesh network that can join, and return the channel value + after finding it. */ + MESH_EVENT_ROUTER_SWITCH, /**< if users specify BSSID of the router in mesh configuration, when the root connects to another + router with the same SSID, this event will be posted and the new router information is attached. */ + MESH_EVENT_PS_PARENT_DUTY, /**< parent duty */ + MESH_EVENT_PS_CHILD_DUTY, /**< child duty */ + MESH_EVENT_PS_DEVICE_DUTY, /**< device duty */ + MESH_EVENT_MAX, +} mesh_event_id_t; + +/** @brief ESP-MESH event base declaration */ +ESP_EVENT_DECLARE_BASE(MESH_EVENT); + +/** + * @brief Device type + */ +typedef enum { + MESH_IDLE, /**< hasn't joined the mesh network yet */ + MESH_ROOT, /**< the only sink of the mesh network. Has the ability to access external IP network */ + MESH_NODE, /**< intermediate device. Has the ability to forward packets over the mesh network */ + MESH_LEAF, /**< has no forwarding ability */ + MESH_STA, /**< connect to router with a standlone Wi-Fi station mode, no network expansion capability */ +} mesh_type_t; + +/** + * @brief Protocol of transmitted application data + */ +typedef enum { + MESH_PROTO_BIN, /**< binary */ + MESH_PROTO_HTTP, /**< HTTP protocol */ + MESH_PROTO_JSON, /**< JSON format */ + MESH_PROTO_MQTT, /**< MQTT protocol */ + MESH_PROTO_AP, /**< IP network mesh communication of node's AP interface */ + MESH_PROTO_STA, /**< IP network mesh communication of node's STA interface */ +} mesh_proto_t; + +/** + * @brief For reliable transmission, mesh stack provides three type of services + */ +typedef enum { + MESH_TOS_P2P, /**< provide P2P (point-to-point) retransmission on mesh stack by default */ + MESH_TOS_E2E, /**< provide E2E (end-to-end) retransmission on mesh stack (Unimplemented) */ + MESH_TOS_DEF, /**< no retransmission on mesh stack */ +} mesh_tos_t; + +/** + * @brief Vote reason + */ +typedef enum { + MESH_VOTE_REASON_ROOT_INITIATED = 1, /**< vote is initiated by the root */ + MESH_VOTE_REASON_CHILD_INITIATED, /**< vote is initiated by children */ +} mesh_vote_reason_t; + +/** + * @brief Mesh disconnect reason code + */ +typedef enum { + MESH_REASON_CYCLIC = 100, /**< cyclic is detected */ + MESH_REASON_PARENT_IDLE, /**< parent is idle */ + MESH_REASON_LEAF, /**< the connected device is changed to a leaf */ + MESH_REASON_DIFF_ID, /**< in different mesh ID */ + MESH_REASON_ROOTS, /**< root conflict is detected */ + MESH_REASON_PARENT_STOPPED, /**< parent has stopped the mesh */ + MESH_REASON_SCAN_FAIL, /**< scan fail */ + MESH_REASON_IE_UNKNOWN, /**< unknown IE */ + MESH_REASON_WAIVE_ROOT, /**< waive root */ + MESH_REASON_PARENT_WORSE, /**< parent with very poor RSSI */ + MESH_REASON_EMPTY_PASSWORD, /**< use an empty password to connect to an encrypted parent */ + MESH_REASON_PARENT_UNENCRYPTED, /**< connect to an unencrypted parent/router */ +} mesh_disconnect_reason_t; + +/** + * @brief Mesh topology + */ +typedef enum { + MESH_TOPO_TREE, /**< tree topology */ + MESH_TOPO_CHAIN, /**< chain topology */ +} esp_mesh_topology_t; + +/******************************************************* + * Structures + *******************************************************/ +/** + * @brief IP address and port + */ +typedef struct { + ip4_addr_t ip4; /**< IP address */ + uint16_t port; /**< port */ +} __attribute__((packed)) mip_t; + +/** + * @brief Mesh address + */ +typedef union { + uint8_t addr[6]; /**< mac address */ + mip_t mip; /**< mip address */ +} mesh_addr_t; + +/** + * @brief Channel switch information + */ +typedef struct { + uint8_t channel; /**< new channel */ +} mesh_event_channel_switch_t; + +/** + * @brief Parent connected information + */ +typedef struct { + wifi_event_sta_connected_t connected; /**< parent information, same as Wi-Fi event SYSTEM_EVENT_STA_CONNECTED does */ + uint16_t self_layer; /**< layer */ + uint8_t duty; /**< parent duty */ +} mesh_event_connected_t; + +/** + * @brief No parent found information + */ +typedef struct { + int scan_times; /**< scan times being through */ +} mesh_event_no_parent_found_t; + +/** + * @brief Layer change information + */ +typedef struct { + uint16_t new_layer; /**< new layer */ +} mesh_event_layer_change_t; + +/** + * @brief The reachability of the root to a DS (distribute system) + */ +typedef enum { + MESH_TODS_UNREACHABLE, /**< the root isn't able to access external IP network */ + MESH_TODS_REACHABLE, /**< the root is able to access external IP network */ +} mesh_event_toDS_state_t; + +/** + * @brief vote started information + */ +typedef struct { + int reason; /**< vote reason, vote could be initiated by children or by the root itself */ + int attempts; /**< max vote attempts before stopped */ + mesh_addr_t rc_addr; /**< root address specified by users via API esp_mesh_waive_root() */ +} mesh_event_vote_started_t; + +/** + * @brief find a mesh network that this device can join + */ +typedef struct { + uint8_t channel; /**< channel number of the new found network */ + uint8_t router_bssid[6]; /**< router BSSID */ +} mesh_event_find_network_t; + +/** + * @brief Root address + */ +typedef mesh_addr_t mesh_event_root_address_t; + +/** + * @brief Parent disconnected information + */ +typedef wifi_event_sta_disconnected_t mesh_event_disconnected_t; + +/** + * @brief Child connected information + */ +typedef wifi_event_ap_staconnected_t mesh_event_child_connected_t; + +/** + * @brief Child disconnected information + */ +typedef wifi_event_ap_stadisconnected_t mesh_event_child_disconnected_t; + +/** + * @brief Root switch request information + */ +typedef struct { + int reason; /**< root switch reason, generally root switch is initialized by users via API esp_mesh_waive_root() */ + mesh_addr_t rc_addr; /**< the address of root switch requester */ +} mesh_event_root_switch_req_t; + +/** + * @brief Other powerful root address + */ +typedef struct { + int8_t rssi; /**< rssi with router */ + uint16_t capacity; /**< the number of devices in current network */ + uint8_t addr[6]; /**< other powerful root address */ +} mesh_event_root_conflict_t; + +/** + * @brief Routing table change + */ +typedef struct { + uint16_t rt_size_new; /**< the new value */ + uint16_t rt_size_change; /**< the changed value */ +} mesh_event_routing_table_change_t; + +/** + * @brief Root fixed + */ +typedef struct { + bool is_fixed; /**< status */ +} mesh_event_root_fixed_t; + +/** + * @brief Scan done event information + */ +typedef struct { + uint8_t number; /**< the number of APs scanned */ +} mesh_event_scan_done_t; + +/** + * @brief Network state information + */ +typedef struct { + bool is_rootless; /**< whether current mesh network has a root */ +} mesh_event_network_state_t; + +/** + * @brief New router information + */ +typedef wifi_event_sta_connected_t mesh_event_router_switch_t; + +/** + * @brief PS duty information + */ +typedef struct { + uint8_t duty; /**< parent or child duty */ + mesh_event_child_connected_t child_connected; /**< child info */ +} mesh_event_ps_duty_t; + +/** + * @brief Mesh event information + */ +typedef union { + mesh_event_channel_switch_t channel_switch; /**< channel switch */ + mesh_event_child_connected_t child_connected; /**< child connected */ + mesh_event_child_disconnected_t child_disconnected; /**< child disconnected */ + mesh_event_routing_table_change_t routing_table; /**< routing table change */ + mesh_event_connected_t connected; /**< parent connected */ + mesh_event_disconnected_t disconnected; /**< parent disconnected */ + mesh_event_no_parent_found_t no_parent; /**< no parent found */ + mesh_event_layer_change_t layer_change; /**< layer change */ + mesh_event_toDS_state_t toDS_state; /**< toDS state, devices shall check this state firstly before trying to send packets to + external IP network. This state indicates right now whether the root is capable of sending + packets out. If not, devices had better to wait until this state changes to be + MESH_TODS_REACHABLE. */ + mesh_event_vote_started_t vote_started; /**< vote started */ + mesh_event_root_address_t root_addr; /**< root address */ + mesh_event_root_switch_req_t switch_req; /**< root switch request */ + mesh_event_root_conflict_t root_conflict; /**< other powerful root */ + mesh_event_root_fixed_t root_fixed; /**< fixed root */ + mesh_event_scan_done_t scan_done; /**< scan done */ + mesh_event_network_state_t network_state; /**< network state, such as whether current mesh network has a root. */ + mesh_event_find_network_t find_network; /**< network found that can join */ + mesh_event_router_switch_t router_switch; /**< new router information */ + mesh_event_ps_duty_t ps_duty; /**< PS duty information */ +} mesh_event_info_t; + +/** + * @brief Mesh option + */ +typedef struct { + uint8_t type; /**< option type */ + uint16_t len; /**< option length */ + uint8_t *val; /**< option value */ +} __attribute__((packed)) mesh_opt_t; + +/** + * @brief Mesh data for esp_mesh_send() and esp_mesh_recv() + */ +typedef struct { + uint8_t *data; /**< data */ + uint16_t size; /**< data size */ + mesh_proto_t proto; /**< data protocol */ + mesh_tos_t tos; /**< data type of service */ +} mesh_data_t; + +/** + * @brief Router configuration + */ +typedef struct { + uint8_t ssid[32]; /**< SSID */ + uint8_t ssid_len; /**< length of SSID */ + uint8_t bssid[6]; /**< BSSID, if this value is specified, users should also specify "allow_router_switch". */ + uint8_t password[64]; /**< password */ + bool allow_router_switch; /**< if the BSSID is specified and this value is also set, when the router of this specified BSSID + fails to be found after "fail" (mesh_attempts_t) times, the whole network is allowed to switch + to another router with the same SSID. The new router might also be on a different channel. + The default value is false. + There is a risk that if the password is different between the new switched router and the previous + one, the mesh network could be established but the root will never connect to the new switched router. */ +} mesh_router_t; + +/** + * @brief Mesh softAP configuration + */ +typedef struct { + uint8_t password[64]; /**< mesh softAP password */ + uint8_t max_connection; /**< max number of stations allowed to connect in, max 10 */ +} mesh_ap_cfg_t; + +/** + * @brief Mesh initialization configuration + */ +typedef struct { + uint8_t channel; /**< channel, the mesh network on */ + bool allow_channel_switch; /**< if this value is set, when "fail" (mesh_attempts_t) times is reached, device will change to + a full channel scan for a network that could join. The default value is false. */ + mesh_addr_t mesh_id; /**< mesh network identification */ + mesh_router_t router; /**< router configuration */ + mesh_ap_cfg_t mesh_ap; /**< mesh softAP configuration */ + const mesh_crypto_funcs_t *crypto_funcs; /**< crypto functions */ +} mesh_cfg_t; + +/** + * @brief Vote address configuration + */ +typedef union { + int attempts; /**< max vote attempts before a new root is elected automatically by mesh network. (min:15, 15 by default) */ + mesh_addr_t rc_addr; /**< a new root address specified by users for API esp_mesh_waive_root() */ +} mesh_rc_config_t; + +/** + * @brief Vote + */ +typedef struct { + float percentage; /**< vote percentage threshold for approval of being a root */ + bool is_rc_specified; /**< if true, rc_addr shall be specified (Unimplemented). + if false, attempts value shall be specified to make network start root election. */ + mesh_rc_config_t config; /**< vote address configuration */ +} mesh_vote_t; + +/** + * @brief The number of packets pending in the queue waiting to be sent by the mesh stack + */ +typedef struct { + int to_parent; /**< to parent queue */ + int to_parent_p2p; /**< to parent (P2P) queue */ + int to_child; /**< to child queue */ + int to_child_p2p; /**< to child (P2P) queue */ + int mgmt; /**< management queue */ + int broadcast; /**< broadcast and multicast queue */ +} mesh_tx_pending_t; + +/** + * @brief The number of packets available in the queue waiting to be received by applications + */ +typedef struct { + int toDS; /**< to external DS */ + int toSelf; /**< to self */ +} mesh_rx_pending_t; + +/******************************************************* + * Variable Declaration + *******************************************************/ +/* mesh IE crypto callback function */ +extern const mesh_crypto_funcs_t g_wifi_default_mesh_crypto_funcs; + +#define MESH_INIT_CONFIG_DEFAULT() { \ + .crypto_funcs = &g_wifi_default_mesh_crypto_funcs, \ +} + +/******************************************************* + * Function Definitions + *******************************************************/ +/** + * @brief Mesh initialization + * - Check whether Wi-Fi is started. + * - Initialize mesh global variables with default values. + * + * @attention This API shall be called after Wi-Fi is started. + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_init(void); + +/** + * @brief Mesh de-initialization + * + * - Release resources and stop the mesh + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_deinit(void); + +/** + * @brief Start mesh + * - Initialize mesh IE. + * - Start mesh network management service. + * - Create TX and RX queues according to the configuration. + * - Register mesh packets receive callback. + * + * @attention  This API shall be called after mesh initialization and configuration. + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_MESH_NOT_INIT + * - ESP_ERR_MESH_NOT_CONFIG + * - ESP_ERR_MESH_NO_MEMORY + */ +esp_err_t esp_mesh_start(void); + +/** + * @brief Stop mesh + * - Deinitialize mesh IE. + * - Disconnect with current parent. + * - Disassociate all currently associated children. + * - Stop mesh network management service. + * - Unregister mesh packets receive callback. + * - Delete TX and RX queues. + * - Release resources. + * - Restore Wi-Fi softAP to default settings if Wi-Fi dual mode is enabled. + * - Set Wi-Fi Power Save type to WIFI_PS_NONE. + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_stop(void); + +/** + * @brief Send a packet over the mesh network + * - Send a packet to any device in the mesh network. + * - Send a packet to external IP network. + * + * @attention This API is not reentrant. + * + * @param[in] to the address of the final destination of the packet + * - If the packet is to the root, set this parameter to NULL. + * - If the packet is to an external IP network, set this parameter to the IPv4:PORT combination. + * This packet will be delivered to the root firstly, then the root will forward this packet to the final IP server address. + * @param[in] data pointer to a sending mesh packet + * - Field size should not exceed MESH_MPS. Note that the size of one mesh packet should not exceed MESH_MTU. + * - Field proto should be set to data protocol in use (default is MESH_PROTO_BIN for binary). + * - Field tos should be set to transmission tos (type of service) in use (default is MESH_TOS_P2P for point-to-point reliable). + * @param[in] flag bitmap for data sent + * - Speed up the route search + * - If the packet is to the root and "to" parameter is NULL, set this parameter to 0. + * - If the packet is to an internal device, MESH_DATA_P2P should be set. + * - If the packet is to the root ("to" parameter isn't NULL) or to external IP network, MESH_DATA_TODS should be set. + * - If the packet is from the root to an internal device, MESH_DATA_FROMDS should be set. + * - Specify whether this API is block or non-block, block by default + * - If needs non-block, MESH_DATA_NONBLOCK should be set. + * - In the situation of the root change, MESH_DATA_DROP identifies this packet can be dropped by the new root + * for upstream data to external IP network, we try our best to avoid data loss caused by the root change, but + * there is a risk that the new root is running out of memory because most of memory is occupied by the pending data which + * isn't read out in time by esp_mesh_recv_toDS(). + * + * Generally, we suggest esp_mesh_recv_toDS() is called after a connection with IP network is created. Thus data outgoing + * to external IP network via socket is just from reading esp_mesh_recv_toDS() which avoids unnecessary memory copy. + * + * @param[in] opt options + * - In case of sending a packet to a certain group, MESH_OPT_SEND_GROUP is a good choice. + * In this option, the value field should be set to the target receiver addresses in this group. + * - Root sends a packet to an internal device, this packet is from external IP network in case the receiver device responds + * this packet, MESH_OPT_RECV_DS_ADDR is required to attach the target DS address. + * @param[in] opt_count option count + * - Currently, this API only takes one option, so opt_count is only supported to be 1. + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_DISCONNECTED + * - ESP_ERR_MESH_OPT_UNKNOWN + * - ESP_ERR_MESH_EXCEED_MTU + * - ESP_ERR_MESH_NO_MEMORY + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_QUEUE_FULL + * - ESP_ERR_MESH_NO_ROUTE_FOUND + * - ESP_ERR_MESH_DISCARD + */ +esp_err_t esp_mesh_send(const mesh_addr_t *to, const mesh_data_t *data, + int flag, const mesh_opt_t opt[], int opt_count); + +/** + * @brief Receive a packet targeted to self over the mesh network + * + * @attention Mesh RX queue should be checked regularly to avoid running out of memory. + * - Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications. + * + * @param[out] from the address of the original source of the packet + * @param[out] data pointer to the received mesh packet + * - Field proto is the data protocol in use. Should follow it to parse the received data. + * - Field tos is the transmission tos (type of service) in use. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_FROMDS represents data from external IP network + * - MESH_DATA_TODS represents data directed upward within the mesh network + * + * flag could be MESH_DATA_FROMDS or MESH_DATA_TODS. + * @param[out] opt options desired to receive + * - MESH_OPT_RECV_DS_ADDR attaches the DS address + * @param[in] opt_count option count desired to receive + * - Currently, this API only takes one option, so opt_count is only supported to be 1. + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_DISCARD + */ +esp_err_t esp_mesh_recv(mesh_addr_t *from, mesh_data_t *data, int timeout_ms, + int *flag, mesh_opt_t opt[], int opt_count); + +/** + * @brief Receive a packet targeted to external IP network + * - Root uses this API to receive packets destined to external IP network + * - Root forwards the received packets to the final destination via socket. + * - If no socket connection is ready to send out the received packets and this esp_mesh_recv_toDS() + * hasn't been called by applications, packets from the whole mesh network will be pending in toDS queue. + * + * Use esp_mesh_get_rx_pending() to check the number of packets available in the queue waiting + * to be received by applications in case of running out of memory in the root. + * + * Using esp_mesh_set_xon_qsize() users may configure the RX queue size, default:32. If this size is too large, + * and esp_mesh_recv_toDS() isn't called in time, there is a risk that a great deal of memory is occupied + * by the pending packets. If this size is too small, it will impact the efficiency on upstream. How to + * decide this value depends on the specific application scenarios. + * + * @attention This API is only called by the root. + * + * @param[out] from the address of the original source of the packet + * @param[out] to the address contains remote IP address and port (IPv4:PORT) + * @param[out] data pointer to the received packet + * - Contain the protocol and applications should follow it to parse the data. + * @param[in] timeout_ms wait time if a packet isn't immediately available (0:no wait, portMAX_DELAY:wait forever) + * @param[out] flag bitmap for data received + * - MESH_DATA_TODS represents the received data target to external IP network. Root shall forward this data to external IP network via the association with router. + * + * flag could be MESH_DATA_TODS. + * @param[out] opt options desired to receive + * @param[in] opt_count option count desired to receive + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_TIMEOUT + * - ESP_ERR_MESH_DISCARD + * - ESP_ERR_MESH_RECV_RELEASE + */ +esp_err_t esp_mesh_recv_toDS(mesh_addr_t *from, mesh_addr_t *to, + mesh_data_t *data, int timeout_ms, int *flag, mesh_opt_t opt[], + int opt_count); + +/** + * @brief Set mesh stack configuration + * - Use MESH_INIT_CONFIG_DEFAULT() to initialize the default values, mesh IE is encrypted by default. + * - Mesh network is established on a fixed channel (1-14). + * - Mesh event callback is mandatory. + * - Mesh ID is an identifier of an MBSS. Nodes with the same mesh ID can communicate with each other. + * - Regarding to the router configuration, if the router is hidden, BSSID field is mandatory. + * + * If BSSID field isn't set and there exists more than one router with same SSID, there is a risk that more + * roots than one connected with different BSSID will appear. It means more than one mesh network is established + * with the same mesh ID. + * + * Root conflict function could eliminate redundant roots connected with the same BSSID, but couldn't handle roots + * connected with different BSSID. Because users might have such requirements of setting up routers with same SSID + * for the future replacement. But in that case, if the above situations happen, please make sure applications + * implement forward functions on the root to guarantee devices in different mesh networks can communicate with each other. + * max_connection of mesh softAP is limited by the max number of Wi-Fi softAP supported (max:10). + * + * @attention This API shall be called before mesh is started after mesh is initialized. + * + * @param[in] config pointer to mesh stack configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_config(const mesh_cfg_t *config); + +/** + * @brief Get mesh stack configuration + * + * @param[out] config pointer to mesh stack configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_config(mesh_cfg_t *config); + +/** + * @brief Get router configuration + * + * @attention This API is used to dynamically modify the router configuration after mesh is configured. + * + * @param[in] router pointer to router configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_router(const mesh_router_t *router); + +/** + * @brief Get router configuration + * + * @param[out] router pointer to router configuration + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_router(mesh_router_t *router); + +/** + * @brief Set mesh network ID + * + * @attention This API is used to dynamically modify the mesh network ID. + * + * @param[in] id pointer to mesh network ID + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT: invalid argument + */ +esp_err_t esp_mesh_set_id(const mesh_addr_t *id); + +/** + * @brief Get mesh network ID + * + * @param[out] id pointer to mesh network ID + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_id(mesh_addr_t *id); + +/** + * @brief Designate device type over the mesh network + * - MESH_IDLE: designates a device as a self-organized node for a mesh network + * - MESH_ROOT: designates the root node for a mesh network + * - MESH_LEAF: designates a device as a standalone Wi-Fi station that connects to a parent + * - MESH_STA: designates a device as a standalone Wi-Fi station that connects to a router + * + * @param[in] type device type + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_type(mesh_type_t type); + +/** + * @brief Get device type over mesh network + * + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @return mesh type + * + */ +mesh_type_t esp_mesh_get_type(void); + +/** + * @brief Set network max layer value + * - for tree topology, the max is 25. + * - for chain topology, the max is 1000. + * - Network max layer limits the max hop count. + * + * @attention This API shall be called before mesh is started. + * + * @param[in] max_layer max layer value + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_max_layer(int max_layer); + +/** + * @brief Get max layer value + * + * @return max layer value + */ +int esp_mesh_get_max_layer(void); + +/** + * @brief Set mesh softAP password + * + * @attention This API shall be called before mesh is started. + * + * @param[in] pwd pointer to the password + * @param[in] len password length + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_ap_password(const uint8_t *pwd, int len); + +/** + * @brief Set mesh softAP authentication mode + * + * @attention This API shall be called before mesh is started. + * + * @param[in] authmode authentication mode + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_ap_authmode(wifi_auth_mode_t authmode); + +/** + * @brief Get mesh softAP authentication mode + * + * @return authentication mode + */ +wifi_auth_mode_t esp_mesh_get_ap_authmode(void); + +/** + * @brief Set mesh softAP max connection value + * + * @attention This API shall be called before mesh is started. + * + * @param[in] connections the number of max connections + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_ap_connections(int connections); + +/** + * @brief Get mesh softAP max connection configuration + * + * @return the number of max connections + */ +int esp_mesh_get_ap_connections(void); + +/** + * @brief Get current layer value over the mesh network + * + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @return layer value + * + */ +int esp_mesh_get_layer(void); + +/** + * @brief Get the parent BSSID + * + * @attention This API shall be called after having received the event MESH_EVENT_PARENT_CONNECTED. + * + * @param[out] bssid pointer to parent BSSID + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_parent_bssid(mesh_addr_t *bssid); + +/** + * @brief Return whether the device is the root node of the network + * + * @return true/false + */ +bool esp_mesh_is_root(void); + +/** + * @brief Enable/disable self-organized networking + * - Self-organized networking has three main functions: + * select the root node; + * find a preferred parent; + * initiate reconnection if a disconnection is detected. + * - Self-organized networking is enabled by default. + * - If self-organized is disabled, users should set a parent for the device via esp_mesh_set_parent(). + * + * @attention This API is used to dynamically modify whether to enable the self organizing. + * + * @param[in] enable enable or disable self-organized networking + * @param[in] select_parent Only valid when self-organized networking is enabled. + * - if select_parent is set to true, the root will give up its mesh root status and search for a new parent + * like other non-root devices. + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_self_organized(bool enable, bool select_parent); + +/** + * @brief Return whether enable self-organized networking or not + * + * @return true/false + */ +bool esp_mesh_get_self_organized(void); + +/** + * @brief Cause the root device to give up (waive) its mesh root status + * - A device is elected root primarily based on RSSI from the external router. + * - If external router conditions change, users can call this API to perform a root switch. + * - In this API, users could specify a desired root address to replace itself or specify an attempts value + * to ask current root to initiate a new round of voting. During the voting, a better root candidate would + * be expected to find to replace the current one. + * - If no desired root candidate, the vote will try a specified number of attempts (at least 15). If no better + * root candidate is found, keep the current one. If a better candidate is found, the new better one will + * send a root switch request to the current root, current root will respond with a root switch acknowledgment. + * - After that, the new candidate will connect to the router to be a new root, the previous root will disconnect + * with the router and choose another parent instead. + * + * Root switch is completed with minimal disruption to the whole mesh network. + * + * @attention This API is only called by the root. + * + * @param[in] vote vote configuration + * - If this parameter is set NULL, the vote will perform the default 15 times. + * + * - Field percentage threshold is 0.9 by default. + * - Field is_rc_specified shall be false. + * - Field attempts shall be at least 15 times. + * @param[in] reason only accept MESH_VOTE_REASON_ROOT_INITIATED for now + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_QUEUE_FULL + * - ESP_ERR_MESH_DISCARD + * - ESP_FAIL + */ +esp_err_t esp_mesh_waive_root(const mesh_vote_t *vote, int reason); + +/** + * @brief Set vote percentage threshold for approval of being a root (default:0.9) + * - During the networking, only obtaining vote percentage reaches this threshold, + * the device could be a root. + * + * @attention This API shall be called before mesh is started. + * + * @param[in] percentage vote percentage threshold + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_vote_percentage(float percentage); + +/** + * @brief Get vote percentage threshold for approval of being a root + * + * @return percentage threshold + */ +float esp_mesh_get_vote_percentage(void); + +/** + * @brief Set mesh softAP associate expired time (default:10 seconds) + * - If mesh softAP hasn't received any data from an associated child within this time, + * mesh softAP will take this child inactive and disassociate it. + * - If mesh softAP is encrypted, this value should be set a greater value, such as 30 seconds. + * + * @param[in] seconds the expired time + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_ap_assoc_expire(int seconds); + +/** + * @brief Get mesh softAP associate expired time + * + * @return seconds + */ +int esp_mesh_get_ap_assoc_expire(void); + +/** + * @brief Get total number of devices in current network (including the root) + * + * @attention The returned value might be incorrect when the network is changing. + ** + * @return total number of devices (including the root) + */ +int esp_mesh_get_total_node_num(void); + +/** + * @brief Get the number of devices in this device's sub-network (including self) + * + * @return the number of devices over this device's sub-network (including self) + */ +int esp_mesh_get_routing_table_size(void); + +/** + * @brief Get routing table of this device's sub-network (including itself) + * + * @param[out] mac pointer to routing table + * @param[in] len routing table size(in bytes) + * @param[out] size pointer to the number of devices in routing table (including itself) + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_routing_table(mesh_addr_t *mac, int len, int *size); + +/** + * @brief Post the toDS state to the mesh stack + * + * @attention This API is only for the root. + * + * @param[in] reachable this state represents whether the root is able to access external IP network + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_post_toDS_state(bool reachable); + +/** + * @brief Return the number of packets pending in the queue waiting to be sent by the mesh stack + * + * @param[out] pending pointer to the TX pending + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_tx_pending(mesh_tx_pending_t *pending); + +/** + * @brief Return the number of packets available in the queue waiting to be received by applications + * + * @param[out] pending pointer to the RX pending + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_get_rx_pending(mesh_rx_pending_t *pending); + +/** + * @brief Return the number of packets could be accepted from the specified address + * + * @param[in] addr self address or an associate children address + * @param[out] xseqno_in sequence number of the last received packet from the specified address + * + * @return the number of upQ for a certain address + */ +int esp_mesh_available_txupQ_num(const mesh_addr_t *addr, uint32_t *xseqno_in); + +/** + * @brief Set the number of queue + * + * @attention This API shall be called before mesh is started. + * + * @param[in] qsize default:32 (min:16) + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_xon_qsize(int qsize); + +/** + * @brief Get queue size + * + * @return the number of queue + */ +int esp_mesh_get_xon_qsize(void); + +/** + * @brief Set whether allow more than one root existing in one network + * + * @param[in] allowed allow or not + * + * @return + * - ESP_OK + * - ESP_WIFI_ERR_NOT_INIT + * - ESP_WIFI_ERR_NOT_START + */ +esp_err_t esp_mesh_allow_root_conflicts(bool allowed); + +/** + * @brief Check whether allow more than one root to exist in one network + * + * @return true/false + */ +bool esp_mesh_is_root_conflicts_allowed(void); + +/** + * @brief Set group ID addresses + * + * @param[in] addr pointer to new group ID addresses + * @param[in] num the number of group ID addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_group_id(const mesh_addr_t *addr, int num); + +/** + * @brief Delete group ID addresses + * + * @param[in] addr pointer to deleted group ID address + * @param[in] num the number of group ID addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_delete_group_id(const mesh_addr_t *addr, int num); + +/** + * @brief Get the number of group ID addresses + * + * @return the number of group ID addresses + */ +int esp_mesh_get_group_num(void); + +/** + * @brief Get group ID addresses + * + * @param[out] addr pointer to group ID addresses + * @param[in] num the number of group ID addresses + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_get_group_list(mesh_addr_t *addr, int num); + +/** + * @brief Check whether the specified group address is my group + * + * @return true/false + */ +bool esp_mesh_is_my_group(const mesh_addr_t *addr); + +/** + * @brief Set mesh network capacity (max:1000, default:300) + * + * @attention This API shall be called before mesh is started. + * + * @param[in] num mesh network capacity + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_ALLOWED + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_capacity_num(int num); + +/** + * @brief Get mesh network capacity + * + * @return mesh network capacity + */ +int esp_mesh_get_capacity_num(void); + +/** + * @brief Set mesh IE crypto functions + * + * @attention This API can be called at any time after mesh is initialized. + * + * @param[in] crypto_funcs crypto functions for mesh IE + * - If crypto_funcs is set to NULL, mesh IE is no longer encrypted. + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_ie_crypto_funcs(const mesh_crypto_funcs_t *crypto_funcs); + +/** + * @brief Set mesh IE crypto key + * + * @attention This API can be called at any time after mesh is initialized. + * + * @param[in] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_ie_crypto_key(const char *key, int len); + +/** + * @brief Get mesh IE crypto key + * + * @param[out] key ASCII crypto key + * @param[in] len length in bytes, range:8~64 + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + */ +esp_err_t esp_mesh_get_ie_crypto_key(char *key, int len); + +/** + * @brief Set delay time before starting root healing + * + * @param[in] delay_ms delay time in milliseconds + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_root_healing_delay(int delay_ms); + +/** + * @brief Get delay time before network starts root healing + * + * @return delay time in milliseconds + */ +int esp_mesh_get_root_healing_delay(void); + +/** + * @brief Enable network Fixed Root Setting + * - Enabling fixed root disables automatic election of the root node via voting. + * - All devices in the network shall use the same Fixed Root Setting (enabled or disabled). + * - If Fixed Root is enabled, users should make sure a root node is designated for the network. + * + * @param[in] enable enable or not + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_fix_root(bool enable); + +/** + * @brief Check whether network Fixed Root Setting is enabled + * - Enable/disable network Fixed Root Setting by API esp_mesh_fix_root(). + * - Network Fixed Root Setting also changes with the "flag" value in parent networking IE. + * + * @return true/false + */ +bool esp_mesh_is_root_fixed(void); + +/** + * @brief Set a specified parent for the device + * + * @attention This API can be called at any time after mesh is configured. + * + * @param[in] parent parent configuration, the SSID and the channel of the parent are mandatory. + * - If the BSSID is set, make sure that the SSID and BSSID represent the same parent, + * otherwise the device will never find this specified parent. + * @param[in] parent_mesh_id parent mesh ID, + * - If this value is not set, the original mesh ID is used. + * @param[in] my_type mesh type + * - MESH_STA is not supported. + * - If the parent set for the device is the same as the router in the network configuration, + * then my_type shall set MESH_ROOT and my_layer shall set MESH_ROOT_LAYER. + * @param[in] my_layer mesh layer + * - my_layer of the device may change after joining the network. + * - If my_type is set MESH_NODE, my_layer shall be greater than MESH_ROOT_LAYER. + * - If my_type is set MESH_LEAF, the device becomes a standalone Wi-Fi station and no longer + * has the ability to extend the network. + * + * @return + * - ESP_OK + * - ESP_ERR_ARGUMENT + * - ESP_ERR_MESH_NOT_CONFIG + */ +esp_err_t esp_mesh_set_parent(const wifi_config_t *parent, const mesh_addr_t *parent_mesh_id, mesh_type_t my_type, int my_layer); + +/** + * @brief Get mesh networking IE length of one AP + * + * @param[out] len mesh networking IE length + * + * @return + * - ESP_OK + * - ESP_ERR_WIFI_NOT_INIT + * - ESP_ERR_WIFI_ARG + * - ESP_ERR_WIFI_FAIL + */ +esp_err_t esp_mesh_scan_get_ap_ie_len(int *len); + +/** + * @brief Get AP record + * + * @attention Different from esp_wifi_scan_get_ap_records(), this API only gets one of APs scanned each time. + * See "manual_networking" example. + * + * @param[out] ap_record pointer to one AP record + * @param[out] buffer pointer to the mesh networking IE of this AP + * + * @return + * - ESP_OK + * - ESP_ERR_WIFI_NOT_INIT + * - ESP_ERR_WIFI_ARG + * - ESP_ERR_WIFI_FAIL + */ +esp_err_t esp_mesh_scan_get_ap_record(wifi_ap_record_t *ap_record, void *buffer); + +/** + * @brief Flush upstream packets pending in to_parent queue and to_parent_p2p queue + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_flush_upstream_packets(void); + +/** + * @brief Get the number of nodes in the subnet of a specific child + * + * @param[in] child_mac an associated child address of this device + * @param[out] nodes_num pointer to the number of nodes in the subnet of a specific child + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_subnet_nodes_num(const mesh_addr_t *child_mac, int *nodes_num); + +/** + * @brief Get nodes in the subnet of a specific child + * + * @param[in] child_mac an associated child address of this device + * @param[out] nodes pointer to nodes in the subnet of a specific child + * @param[in] nodes_num the number of nodes in the subnet of a specific child + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_NOT_START + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_subnet_nodes_list(const mesh_addr_t *child_mac, mesh_addr_t *nodes, int nodes_num); + +/** + * @brief Disconnect from current parent + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_disconnect(void); + +/** + * @brief Connect to current parent + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_connect(void); + +/** + * @brief Flush scan result + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_flush_scan_result(void); + +/** + * @brief Cause the root device to add Channel Switch Announcement Element (CSA IE) to beacon + * - Set the new channel + * - Set how many beacons with CSA IE will be sent before changing a new channel + * - Enable the channel switch function + * + * @attention This API is only called by the root. + * + * @param[in] new_bssid the new router BSSID if the router changes + * @param[in] csa_newchan the new channel number to which the whole network is moving + * @param[in] csa_count channel switch period(beacon count), unit is based on beacon interval of its softAP, the default value is 15. + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_switch_channel(const uint8_t *new_bssid, int csa_newchan, int csa_count); + +/** + * @brief Get the router BSSID + * + * @param[out] router_bssid pointer to the router BSSID + * + * @return + * - ESP_OK + * - ESP_ERR_WIFI_NOT_INIT + * - ESP_ERR_WIFI_ARG + */ +esp_err_t esp_mesh_get_router_bssid(uint8_t *router_bssid); + +/** + * @brief Get the TSF time + * + * @return the TSF time + */ +int64_t esp_mesh_get_tsf_time(void); + +/** + * @brief Set mesh topology. The default value is MESH_TOPO_TREE + * - MESH_TOPO_CHAIN supports up to 1000 layers + * + * @attention This API shall be called before mesh is started. + * + * @param[in] topo MESH_TOPO_TREE or MESH_TOPO_CHAIN + * + * @return + * - ESP_OK + * - ESP_MESH_ERR_ARGUMENT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_set_topology(esp_mesh_topology_t topo); + +/** + * @brief Get mesh topology + * + * @return MESH_TOPO_TREE or MESH_TOPO_CHAIN + */ +esp_mesh_topology_t esp_mesh_get_topology(void); + +/** + * @brief Enable mesh Power Save function + * + * @attention This API shall be called before mesh is started. + * + * @return + * - ESP_OK + * - ESP_ERR_WIFI_NOT_INIT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_enable_ps(void); + +/** + * @brief Disable mesh Power Save function + * + * @attention This API shall be called before mesh is started. + * + * @return + * - ESP_OK + * - ESP_ERR_WIFI_NOT_INIT + * - ESP_ERR_MESH_NOT_ALLOWED + */ +esp_err_t esp_mesh_disable_ps(void); + +/** + * @brief Check whether the mesh Power Save function is enabled + * + * @return true/false + */ +bool esp_mesh_is_ps_enabled(void); + +/** + * @brief Check whether the device is in active state + * - If the device is not in active state, it will neither transmit nor receive frames. + * + * @return true/false + */ +bool esp_mesh_is_device_active(void); + +/** + * @brief Set the device duty cycle and type + * - The range of dev_duty values is 1 to 100. The default value is 10. + * - dev_duty = 100, the PS will be stopped. + * - dev_duty is better to not less than 5. + * - dev_duty_type could be MESH_PS_DEVICE_DUTY_REQUEST or MESH_PS_DEVICE_DUTY_DEMAND. + * - If dev_duty_type is set to MESH_PS_DEVICE_DUTY_REQUEST, the device will use a nwk_duty provided by the network. + * - If dev_duty_type is set to MESH_PS_DEVICE_DUTY_DEMAND, the device will use the specified dev_duty. + * + * @attention This API can be called at any time after mesh is started. + * + * @param[in] dev_duty device duty cycle + * @param[in] dev_duty_type device PS duty cycle type, not accept MESH_PS_NETWORK_DUTY_MASTER + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_active_duty_cycle(int dev_duty, int dev_duty_type); + +/** + * @brief Get device duty cycle and type + * + * @param[out] dev_duty device duty cycle + * @param[out] dev_duty_type device PS duty cycle type + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_active_duty_cycle(int* dev_duty, int* dev_duty_type); + +/** + * @brief Set the network duty cycle, duration and rule + * - The range of nwk_duty values is 1 to 100. The default value is 10. + * - nwk_duty is the network duty cycle the entire network or the up-link path will use. A device that successfully + * sets the nwk_duty is known as a NWK-DUTY-MASTER. + * - duration_mins specifies how long the specified nwk_duty will be used. Once duration_mins expires, the root will take + * over as the NWK-DUTY-MASTER. If an existing NWK-DUTY-MASTER leaves the network, the root will take over as the + * NWK-DUTY-MASTER again. + * - duration_mins = (-1) represents nwk_duty will be used until a new NWK-DUTY-MASTER with a different nwk_duty appears. + * - Only the root can set duration_mins to (-1). + * - If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE, the nwk_duty will be used by the entire network. + * - If applied_rule is set to MESH_PS_NETWORK_DUTY_APPLIED_UPLINK, the nwk_duty will only be used by the up-link path nodes. + * - The root does not accept MESH_PS_NETWORK_DUTY_APPLIED_UPLINK. + * - A nwk_duty with duration_mins(-1) set by the root is the default network duty cycle used by the entire network. + * + * @attention This API can be called at any time after mesh is started. + * - In self-organized network, if this API is called before mesh is started in all devices, (1)nwk_duty shall be set to the + * same value for all devices; (2)duration_mins shall be set to (-1); (3)applied_rule shall be set to + * MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE; after the voted root appears, the root will become the NWK-DUTY-MASTER and broadcast + * the nwk_duty and its identity of NWK-DUTY-MASTER. + * - If the root is specified (FIXED-ROOT), call this API in the root to provide a default nwk_duty for the entire network. + * - After joins the network, any device can call this API to change the nwk_duty, duration_mins or applied_rule. + * + * @param[in] nwk_duty network duty cycle + * @param[in] duration_mins duration (unit: minutes) + * @param[in] applied_rule only support MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_network_duty_cycle(int nwk_duty, int duration_mins, int applied_rule); + +/** + * @brief Get the network duty cycle, duration, type and rule + * + * @param[out] nwk_duty current network duty cycle + * @param[out] duration_mins the duration of current nwk_duty + * @param[out] dev_duty_type if it includes MESH_PS_DEVICE_DUTY_MASTER, this device is the current NWK-DUTY-MASTER. + * @param[out] applied_rule MESH_PS_NETWORK_DUTY_APPLIED_ENTIRE + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_network_duty_cycle(int* nwk_duty, int* duration_mins, int* dev_duty_type, int* applied_rule); + +/** + * @brief Get the running active duty cycle + * - The running active duty cycle of the root is 100. + * - If duty type is set to MESH_PS_DEVICE_DUTY_REQUEST, the running active duty cycle is nwk_duty provided by the network. + * - If duty type is set to MESH_PS_DEVICE_DUTY_DEMAND, the running active duty cycle is dev_duty specified by the users. + * - In a mesh network, devices are typically working with a certain duty-cycle (transmitting, receiving and sleep) to + * reduce the power consumption. The running active duty cycle decides the amount of awake time within a beacon interval. + * At each start of beacon interval, all devices wake up, broadcast beacons, and transmit packets if they do have pending + * packets for their parents or for their children. Note that Low-duty-cycle means devices may not be active in most of + * the time, the latency of data transmission might be greater. + * + * @return the running active duty cycle + */ +int esp_mesh_get_running_active_duty_cycle(void); + +/** + * @brief Duty signaling + * + * @param[in] fwd_times the times of forwarding duty signaling packets + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_ps_duty_signaling(int fwd_times); + +#ifdef __cplusplus +} +#endif +#endif /* __ESP_MESH_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh_internal.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh_internal.h new file mode 100644 index 00000000..e967dbaa --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_mesh_internal.h @@ -0,0 +1,310 @@ +// Copyright 2017-2018 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. + +#ifndef __ESP_MESH_INTERNAL_H__ +#define __ESP_MESH_INTERNAL_H__ + +#include "esp_err.h" +#include "esp_mesh.h" +#include "esp_wifi.h" +#include "esp_wifi_types.h" +#include "esp_private/wifi.h" +#include "esp_wifi_crypto_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/******************************************************* + * Constants + *******************************************************/ + +/******************************************************* + * Structures + *******************************************************/ +typedef struct { + int scan; /**< minimum scan times before being a root, default:10 */ + int vote; /**< max vote times in self-healing, default:1000 */ + int fail; /**< parent selection fail times, if the scan times reach this value, + device will disconnect with associated children and join self-healing. default:60 */ + int monitor_ie; /**< acceptable times of parent networking IE change before update its own networking IE. default:3 */ +} mesh_attempts_t; + +typedef struct { + int duration_ms; /* parent weak RSSI monitor duration, if the RSSI continues to be weak during this duration_ms, + device will search for a new parent. */ + int cnx_rssi; /* RSSI threshold for keeping a good connection with parent. + If set a value greater than -120 dBm, a timer will be armed to monitor parent RSSI at a period time of duration_ms. */ + int select_rssi; /* RSSI threshold for parent selection. It should be a value greater than switch_rssi. */ + int switch_rssi; /* Disassociate with current parent and switch to a new parent when the RSSI is greater than this set threshold. */ + int backoff_rssi; /* RSSI threshold for connecting to the root */ +} mesh_switch_parent_t; + +typedef struct { + int high; + int medium; + int low; +} mesh_rssi_threshold_t; + +/** + * @brief Mesh networking IE + */ +typedef struct { + /**< mesh networking IE head */ + uint8_t eid; /**< element ID */ + uint8_t len; /**< element length */ + uint8_t oui[3]; /**< organization identifier */ + /**< mesh networking IE content */ + uint8_t type; /** ESP defined IE type */ + uint8_t encrypted : 1; /**< whether mesh networking IE is encrypted */ + uint8_t version : 7; /**< mesh networking IE version */ + /**< content */ + uint8_t mesh_type; /**< mesh device type */ + uint8_t mesh_id[6]; /**< mesh ID */ + uint8_t layer_cap; /**< max layer */ + uint8_t layer; /**< current layer */ + uint8_t assoc_cap; /**< max connections of mesh AP */ + uint8_t assoc; /**< current connections */ + uint8_t leaf_cap; /**< leaf capacity */ + uint8_t leaf_assoc; /**< the number of current connected leaf */ + uint16_t root_cap; /**< root capacity */ + uint16_t self_cap; /**< self capacity */ + uint16_t layer2_cap; /**< layer2 capacity */ + uint16_t scan_ap_num; /**< the number of scanning APs */ + int8_t rssi; /**< RSSI of the parent */ + int8_t router_rssi; /**< RSSI of the router */ + uint8_t flag; /**< flag of networking */ + uint8_t rc_addr[6]; /**< root address */ + int8_t rc_rssi; /**< root RSSI */ + uint8_t vote_addr[6]; /**< voter address */ + int8_t vote_rssi; /**< vote RSSI of the router */ + uint8_t vote_ttl; /**< vote ttl */ + uint16_t votes; /**< votes */ + uint16_t my_votes; /**< my votes */ + uint8_t reason; /**< reason */ + uint8_t child[6]; /**< child address */ + uint8_t toDS; /**< toDS state */ +} __attribute__((packed)) mesh_assoc_t; + +typedef struct { + uint16_t layer_cap; + uint16_t layer; +} mesh_chain_layer_t; + +typedef struct { + mesh_assoc_t tree; + mesh_chain_layer_t chain; +} __attribute__((packed)) mesh_chain_assoc_t; + +/** + * @brief Mesh PS duties + */ +typedef struct { + uint8_t device; + uint8_t parent; + struct { + bool used; + uint8_t duty; + uint8_t mac[6]; + } child[ESP_WIFI_MAX_CONN_NUM]; +} esp_mesh_ps_duties_t; + +/******************************************************* + * Function Definitions + *******************************************************/ +/** + * @brief Set mesh softAP beacon interval + * + * @param[in] interval beacon interval (msecs) (100 msecs ~ 60000 msecs) + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_WIFI_ARG + */ +esp_err_t esp_mesh_set_beacon_interval(int interval_ms); + +/** + * @brief Get mesh softAP beacon interval + * + * @param[out] interval beacon interval (msecs) + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_beacon_interval(int *interval_ms); + +/** + * @brief Set attempts for mesh self-organized networking + * + * @param[in] attempts + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_set_attempts(mesh_attempts_t *attempts); + +/** + * @brief Get attempts for mesh self-organized networking + * + * @param[out] attempts + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_attempts(mesh_attempts_t *attempts); + +/** + * @brief Set parameters for parent switch + * + * @param[in] paras parameters for parent switch + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_switch_parent_paras(mesh_switch_parent_t *paras); + +/** + * @brief Get parameters for parent switch + * + * @param[out] paras parameters for parent switch + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_switch_parent_paras(mesh_switch_parent_t *paras); + +/** + * @brief Set RSSI threshold + * - The default high RSSI threshold value is -78 dBm. + * - The default medium RSSI threshold value is -82 dBm. + * - The default low RSSI threshold value is -85 dBm. + * + * @param[in] threshold RSSI threshold + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_set_rssi_threshold(const mesh_rssi_threshold_t *threshold); + +/** + * @brief Get RSSI threshold + * + * @param[out] threshold RSSI threshold + * + * @return + * - ESP_OK + * - ESP_ERR_MESH_ARGUMENT + */ +esp_err_t esp_mesh_get_rssi_threshold(mesh_rssi_threshold_t *threshold); + +/** + * @brief Enable the minimum rate to 6 Mbps + * + * @attention This API shall be called before Wi-Fi is started. + * + * @param[in] is_6m enable or not + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_6m_rate(bool is_6m); + +/** + * @brief Print the number of txQ waiting + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_print_txQ_waiting(void); + +/** + * @brief Print the number of rxQ waiting + * + * @return + * - ESP_OK + * - ESP_FAIL + */ +esp_err_t esp_mesh_print_rxQ_waiting(void); + +/** + * @brief Set passive scan time + * + * @param[in] interval_ms passive scan time (msecs) + * + * @return + * - ESP_OK + * - ESP_FAIL + * - ESP_ERR_ARGUMENT + */ +esp_err_t esp_mesh_set_passive_scan_time(int time_ms); + +/** + * @brief Get passive scan time + * + * @return interval_ms passive scan time (msecs) + */ +int esp_mesh_get_passive_scan_time(void); + +/** + * @brief Set announce interval + * - The default short interval is 500 milliseconds. + * - The default long interval is 3000 milliseconds. + * + * @param[in] short_ms shall be greater than the default value + * @param[in] long_ms shall be greater than the default value + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_set_announce_interval(int short_ms, int long_ms); + +/** + * @brief Get announce interval + * + * @param[out] short_ms short interval + * @param[out] long_ms long interval + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_get_announce_interval(int *short_ms, int *long_ms); + +/** + * @brief Get the running duties of device, parent and children + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_ps_get_duties(esp_mesh_ps_duties_t* ps_duties); + +/** + * @brief Enable mesh print scan result + * + * @param[in] enable enable or not + * + * @return + * - ESP_OK + */ +esp_err_t esp_mesh_print_scan_result(bool enable); +#ifdef __cplusplus +} +#endif +#endif /* __ESP_MESH_INTERNAL_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_now.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_now.h new file mode 100644 index 00000000..de41a879 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_now.h @@ -0,0 +1,334 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_NOW_H__ +#define __ESP_NOW_H__ + +#include +#include "esp_err.h" +#include "esp_wifi_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** \defgroup WiFi_APIs WiFi Related APIs + * @brief WiFi APIs + */ + +/** @addtogroup WiFi_APIs + * @{ + */ + +/** \defgroup ESPNOW_APIs ESPNOW APIs + * @brief ESP32 ESPNOW APIs + * + */ + +/** @addtogroup ESPNOW_APIs + * @{ + */ + +#define ESP_ERR_ESPNOW_BASE (ESP_ERR_WIFI_BASE + 100) /*!< ESPNOW error number base. */ +#define ESP_ERR_ESPNOW_NOT_INIT (ESP_ERR_ESPNOW_BASE + 1) /*!< ESPNOW is not initialized. */ +#define ESP_ERR_ESPNOW_ARG (ESP_ERR_ESPNOW_BASE + 2) /*!< Invalid argument */ +#define ESP_ERR_ESPNOW_NO_MEM (ESP_ERR_ESPNOW_BASE + 3) /*!< Out of memory */ +#define ESP_ERR_ESPNOW_FULL (ESP_ERR_ESPNOW_BASE + 4) /*!< ESPNOW peer list is full */ +#define ESP_ERR_ESPNOW_NOT_FOUND (ESP_ERR_ESPNOW_BASE + 5) /*!< ESPNOW peer is not found */ +#define ESP_ERR_ESPNOW_INTERNAL (ESP_ERR_ESPNOW_BASE + 6) /*!< Internal error */ +#define ESP_ERR_ESPNOW_EXIST (ESP_ERR_ESPNOW_BASE + 7) /*!< ESPNOW peer has existed */ +#define ESP_ERR_ESPNOW_IF (ESP_ERR_ESPNOW_BASE + 8) /*!< Interface error */ + +#define ESP_NOW_ETH_ALEN 6 /*!< Length of ESPNOW peer MAC address */ +#define ESP_NOW_KEY_LEN 16 /*!< Length of ESPNOW peer local master key */ + +#define ESP_NOW_MAX_TOTAL_PEER_NUM 20 /*!< Maximum number of ESPNOW total peers */ +#define ESP_NOW_MAX_ENCRYPT_PEER_NUM 6 /*!< Maximum number of ESPNOW encrypted peers */ + +#define ESP_NOW_MAX_DATA_LEN 250 /*!< Maximum length of ESPNOW data which is sent very time */ + +/** + * @brief Status of sending ESPNOW data . + */ +typedef enum { + ESP_NOW_SEND_SUCCESS = 0, /**< Send ESPNOW data successfully */ + ESP_NOW_SEND_FAIL, /**< Send ESPNOW data fail */ +} esp_now_send_status_t; + +/** + * @brief ESPNOW peer information parameters. + */ +typedef struct esp_now_peer_info { + uint8_t peer_addr[ESP_NOW_ETH_ALEN]; /**< ESPNOW peer MAC address that is also the MAC address of station or softap */ + uint8_t lmk[ESP_NOW_KEY_LEN]; /**< ESPNOW peer local master key that is used to encrypt data */ + uint8_t channel; /**< Wi-Fi channel that peer uses to send/receive ESPNOW data. If the value is 0, + use the current channel which station or softap is on. Otherwise, it must be + set as the channel that station or softap is on. */ + wifi_interface_t ifidx; /**< Wi-Fi interface that peer uses to send/receive ESPNOW data */ + bool encrypt; /**< ESPNOW data that this peer sends/receives is encrypted or not */ + void *priv; /**< ESPNOW peer private data */ +} esp_now_peer_info_t; + +/** + * @brief Number of ESPNOW peers which exist currently. + */ +typedef struct esp_now_peer_num { + int total_num; /**< Total number of ESPNOW peers, maximum value is ESP_NOW_MAX_TOTAL_PEER_NUM */ + int encrypt_num; /**< Number of encrypted ESPNOW peers, maximum value is ESP_NOW_MAX_ENCRYPT_PEER_NUM */ +} esp_now_peer_num_t; + +/** + * @brief Callback function of receiving ESPNOW data + * @param mac_addr peer MAC address + * @param data received data + * @param data_len length of received data + */ +typedef void (*esp_now_recv_cb_t)(const uint8_t *mac_addr, const uint8_t *data, int data_len); + +/** + * @brief Callback function of sending ESPNOW data + * @param mac_addr peer MAC address + * @param status status of sending ESPNOW data (succeed or fail) + */ +typedef void (*esp_now_send_cb_t)(const uint8_t *mac_addr, esp_now_send_status_t status); + +/** + * @brief Initialize ESPNOW function + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_INTERNAL : Internal error + */ +esp_err_t esp_now_init(void); + +/** + * @brief De-initialize ESPNOW function + * + * @return + * - ESP_OK : succeed + */ +esp_err_t esp_now_deinit(void); + +/** + * @brief Get the version of ESPNOW + * + * @param version ESPNOW version + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_ARG : invalid argument + */ +esp_err_t esp_now_get_version(uint32_t *version); + +/** + * @brief Register callback function of receiving ESPNOW data + * + * @param cb callback function of receiving ESPNOW data + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_INTERNAL : internal error + */ +esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb); + +/** + * @brief Unregister callback function of receiving ESPNOW data + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + */ +esp_err_t esp_now_unregister_recv_cb(void); + +/** + * @brief Register callback function of sending ESPNOW data + * + * @param cb callback function of sending ESPNOW data + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_INTERNAL : internal error + */ +esp_err_t esp_now_register_send_cb(esp_now_send_cb_t cb); + +/** + * @brief Unregister callback function of sending ESPNOW data + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + */ +esp_err_t esp_now_unregister_send_cb(void); + +/** + * @brief Send ESPNOW data + * + * @attention 1. If peer_addr is not NULL, send data to the peer whose MAC address matches peer_addr + * @attention 2. If peer_addr is NULL, send data to all of the peers that are added to the peer list + * @attention 3. The maximum length of data must be less than ESP_NOW_MAX_DATA_LEN + * @attention 4. The buffer pointed to by data argument does not need to be valid after esp_now_send returns + * + * @param peer_addr peer MAC address + * @param data data to send + * @param len length of data + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_INTERNAL : internal error + * - ESP_ERR_ESPNOW_NO_MEM : out of memory + * - ESP_ERR_ESPNOW_NOT_FOUND : peer is not found + * - ESP_ERR_ESPNOW_IF : current WiFi interface doesn't match that of peer + */ +esp_err_t esp_now_send(const uint8_t *peer_addr, const uint8_t *data, size_t len); + +/** + * @brief Add a peer to peer list + * + * @param peer peer information + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_FULL : peer list is full + * - ESP_ERR_ESPNOW_NO_MEM : out of memory + * - ESP_ERR_ESPNOW_EXIST : peer has existed + */ +esp_err_t esp_now_add_peer(const esp_now_peer_info_t *peer); + +/** + * @brief Delete a peer from peer list + * + * @param peer_addr peer MAC address + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_NOT_FOUND : peer is not found + */ +esp_err_t esp_now_del_peer(const uint8_t *peer_addr); + +/** + * @brief Modify a peer + * + * @param peer peer information + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_FULL : peer list is full + */ +esp_err_t esp_now_mod_peer(const esp_now_peer_info_t *peer); + +/** + * @brief Get a peer whose MAC address matches peer_addr from peer list + * + * @param peer_addr peer MAC address + * @param peer peer information + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_NOT_FOUND : peer is not found + */ +esp_err_t esp_now_get_peer(const uint8_t *peer_addr, esp_now_peer_info_t *peer); + +/** + * @brief Fetch a peer from peer list. Only return the peer which address is unicast, for the multicast/broadcast address, the function will ignore and try to find the next in the peer list. + * + * @param from_head fetch from head of list or not + * @param peer peer information + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + * - ESP_ERR_ESPNOW_NOT_FOUND : peer is not found + */ +esp_err_t esp_now_fetch_peer(bool from_head, esp_now_peer_info_t *peer); + +/** + * @brief Peer exists or not + * + * @param peer_addr peer MAC address + * + * @return + * - true : peer exists + * - false : peer not exists + */ +bool esp_now_is_peer_exist(const uint8_t *peer_addr); + +/** + * @brief Get the number of peers + * + * @param num number of peers + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + */ +esp_err_t esp_now_get_peer_num(esp_now_peer_num_t *num); + +/** + * @brief Set the primary master key + * + * @param pmk primary master key + * + * @attention 1. primary master key is used to encrypt local master key + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + * - ESP_ERR_ESPNOW_ARG : invalid argument + */ +esp_err_t esp_now_set_pmk(const uint8_t *pmk); + +/** + * @brief Set esp_now wake window for sta_disconnected power management + * + * @param window how much microsecond would the chip keep waked each interval, vary from 0 to 65535 + * + * @attention 1. Only when ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is enabled, this configuration could work + * @attention 2. This configuration only work for station mode and disconnected status + * @attention 3. If more than one module has configured its wake_window, chip would choose the largest one to stay waked + * @attention 4. If the gap between interval and window is smaller than 5ms, the chip would keep waked all the time + * @attention 5. If never configured wake_window, the chip would keep waked at disconnected once it uses esp_now + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_ESPNOW_NOT_INIT : ESPNOW is not initialized + */ +esp_err_t esp_now_set_wake_window(uint16_t window); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_NOW_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_phy_init.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_phy_init.h new file mode 100644 index 00000000..f85d8b38 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_phy_init.h @@ -0,0 +1,240 @@ +// Copyright 2015-2016 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. + +#pragma once +#include +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file PHY init parameters and API + */ + + +/** + * @brief Structure holding PHY init parameters + */ +typedef struct { + uint8_t params[128]; /*!< opaque PHY initialization parameters */ +} esp_phy_init_data_t; + +/** + * @brief Opaque PHY calibration data + */ +typedef struct { + uint8_t version[4]; /*!< PHY version */ + uint8_t mac[6]; /*!< The MAC address of the station */ + uint8_t opaque[1894]; /*!< calibration data */ +} esp_phy_calibration_data_t; + +typedef enum { + PHY_RF_CAL_PARTIAL = 0x00000000, /*!< Do part of RF calibration. This should be used after power-on reset. */ + PHY_RF_CAL_NONE = 0x00000001, /*!< Don't do any RF calibration. This mode is only suggested to be used after deep sleep reset. */ + PHY_RF_CAL_FULL = 0x00000002 /*!< Do full RF calibration. Produces best results, but also consumes a lot of time and current. Suggested to be used once. */ +} esp_phy_calibration_mode_t; + +#if CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN +/** + * @brief PHY init data type + */ +typedef enum { + ESP_PHY_INIT_DATA_TYPE_DEFAULT = 0, + ESP_PHY_INIT_DATA_TYPE_SRRC, + ESP_PHY_INIT_DATA_TYPE_FCC, + ESP_PHY_INIT_DATA_TYPE_CE, + ESP_PHY_INIT_DATA_TYPE_NCC, + ESP_PHY_INIT_DATA_TYPE_KCC, + ESP_PHY_INIT_DATA_TYPE_MIC, + ESP_PHY_INIT_DATA_TYPE_IC, + ESP_PHY_INIT_DATA_TYPE_ACMA, + ESP_PHY_INIT_DATA_TYPE_ANATEL, + ESP_PHY_INIT_DATA_TYPE_ISED, + ESP_PHY_INIT_DATA_TYPE_WPC, + ESP_PHY_INIT_DATA_TYPE_OFCA, + ESP_PHY_INIT_DATA_TYPE_IFETEL, + ESP_PHY_INIT_DATA_TYPE_RCM, + ESP_PHY_INIT_DATA_TYPE_NUMBER, +} phy_init_data_type_t; +#endif + +/** + * @brief Get PHY init data + * + * If "Use a partition to store PHY init data" option is set in menuconfig, + * This function will load PHY init data from a partition. Otherwise, + * PHY init data will be compiled into the application itself, and this function + * will return a pointer to PHY init data located in read-only memory (DROM). + * + * If "Use a partition to store PHY init data" option is enabled, this function + * may return NULL if the data loaded from flash is not valid. + * + * @note Call esp_phy_release_init_data to release the pointer obtained using + * this function after the call to esp_wifi_init. + * + * @return pointer to PHY init data structure + */ +const esp_phy_init_data_t* esp_phy_get_init_data(void); + +/** + * @brief Release PHY init data + * @param data pointer to PHY init data structure obtained from + * esp_phy_get_init_data function + */ +void esp_phy_release_init_data(const esp_phy_init_data_t* data); + +/** + * @brief Function called by esp_phy_init to load PHY calibration data + * + * This is a convenience function which can be used to load PHY calibration + * data from NVS. Data can be stored to NVS using esp_phy_store_cal_data_to_nvs + * function. + * + * If calibration data is not present in the NVS, or + * data is not valid (was obtained for a chip with a different MAC address, + * or obtained for a different version of software), this function will + * return an error. + * + * If "Initialize PHY in startup code" option is set in menuconfig, this + * function will be used to load calibration data. To provide a different + * mechanism for loading calibration data, disable + * "Initialize PHY in startup code" option in menuconfig and call esp_phy_init + * function from the application. For an example usage of esp_phy_init and + * this function, see esp_phy_store_cal_data_to_nvs function in cpu_start.c + * + * @param out_cal_data pointer to calibration data structure to be filled with + * loaded data. + * @return ESP_OK on success + */ +esp_err_t esp_phy_load_cal_data_from_nvs(esp_phy_calibration_data_t* out_cal_data); + +/** + * @brief Function called by esp_phy_init to store PHY calibration data + * + * This is a convenience function which can be used to store PHY calibration + * data to the NVS. Calibration data is returned by esp_phy_init function. + * Data saved using this function to the NVS can later be loaded using + * esp_phy_store_cal_data_to_nvs function. + * + * If "Initialize PHY in startup code" option is set in menuconfig, this + * function will be used to store calibration data. To provide a different + * mechanism for storing calibration data, disable + * "Initialize PHY in startup code" option in menuconfig and call esp_phy_init + * function from the application. + * + * @param cal_data pointer to calibration data which has to be saved. + * @return ESP_OK on success + */ +esp_err_t esp_phy_store_cal_data_to_nvs(const esp_phy_calibration_data_t* cal_data); + +/** + * @brief Erase PHY calibration data which is stored in the NVS + * + * This is a function which can be used to trigger full calibration as a last-resort remedy + * if partial calibration is used. It can be called in the application based on some conditions + * (e.g. an option provided in some diagnostic mode). + * + * @return ESP_OK on success + * @return others on fail. Please refer to NVS API return value error number. + */ +esp_err_t esp_phy_erase_cal_data_in_nvs(void); + +/** + * @brief Enable PHY and RF module + * + * PHY and RF module should be enabled in order to use WiFi or BT. + * Now PHY and RF enabling job is done automatically when start WiFi or BT. Users should not + * call this API in their application. + * + */ +void esp_phy_enable(void); + +/** + * @brief Disable PHY and RF module + * + * PHY module should be disabled in order to shutdown WiFi or BT. + * Now PHY and RF disabling job is done automatically when stop WiFi or BT. Users should not + * call this API in their application. + * + */ +void esp_phy_disable(void); + +/** + * @brief Load calibration data from NVS and initialize PHY and RF module + */ +void esp_phy_load_cal_and_init(void); + +#if CONFIG_MAC_BB_PD +/** + * @brief Initialize backup memory for MAC and Baseband power up/down + */ +void esp_mac_bb_pd_mem_init(void); + +/** + * @brief Power up MAC and Baseband + */ +void esp_mac_bb_power_up(void); + +/** + * @brief Power down MAC and Baseband + */ +void esp_mac_bb_power_down(void); +#endif + +/** + * @brief Enable WiFi/BT common clock + * + */ +void esp_phy_common_clock_enable(void); + +/** + * @brief Disable WiFi/BT common clock + * + */ +void esp_phy_common_clock_disable(void); + +/** + * @brief Get the time stamp when PHY/RF was switched on + * @return return 0 if PHY/RF is never switched on. Otherwise return time in + * microsecond since boot when phy/rf was last switched on +*/ +int64_t esp_phy_rf_get_on_ts(void); + +/** + * @brief Update the corresponding PHY init type according to the country code of Wi-Fi. + */ +esp_err_t esp_phy_update_country_info(const char *country); + + +#if CONFIG_ESP32_SUPPORT_MULTIPLE_PHY_INIT_DATA_BIN +/** + * @brief Apply PHY init bin to PHY + * @return ESP_OK on success. + * @return ESP_FAIL on fail. + */ +esp_err_t esp_phy_apply_phy_init_data(uint8_t *init_data); +#endif + +/** + * @brief Get PHY lib version + * @return PHY lib version. + */ +char * get_phy_version_str(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_private.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_private.h new file mode 100644 index 00000000..087a4a16 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_private.h @@ -0,0 +1,25 @@ +// Copyright 2019 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. + +#ifndef _ESP_WIFI_PRIVATE_H +#define _ESP_WIFI_PRIVATE_H + +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "sys/queue.h" +#include "sdkconfig.h" +#include "esp_wifi_crypto_types.h" +#include "esp_private/wifi_os_adapter.h" + + +#endif /* _ESP_WIFI_PRIVATE_H */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_types_private.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_types_private.h new file mode 100644 index 00000000..55c70c77 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/esp_wifi_types_private.h @@ -0,0 +1,25 @@ +// Copyright 2019 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. + +#ifndef _ESP_WIFI_TYPES_PRIVATE_H +#define _ESP_WIFI_TYPES_PRIVATE_H + +#include +#include +#include "sys/queue.h" +#include "esp_err.h" +#include "esp_interface.h" +#include "esp_event_base.h" + +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi.h new file mode 100644 index 00000000..3c5a93a1 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi.h @@ -0,0 +1,616 @@ +// Copyright 2015-2016 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. + +/* + * All the APIs declared here are internal only APIs, it can only be used by + * espressif internal modules, such as SSC, LWIP, TCPIP adapter etc, espressif + * customers are not recommended to use them. + * + * If someone really want to use specified APIs declared in here, please contact + * espressif AE/developer to make sure you know the limitations or risk of + * the API, otherwise you may get unexpected behavior!!! + * + */ + + +#ifndef __ESP_WIFI_INTERNAL_H__ +#define __ESP_WIFI_INTERNAL_H__ + +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" +#include "sys/queue.h" +#include "esp_err.h" +#include "esp_wifi_types.h" +#include "esp_event.h" +#include "esp_wifi.h" +#include "esp_smartconfig.h" +#include "wifi_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + QueueHandle_t handle; /**< FreeRTOS queue handler */ + void *storage; /**< storage for FreeRTOS queue */ +} wifi_static_queue_t; + +/** + * @brief WiFi log level + * + */ +typedef enum { + WIFI_LOG_NONE = 0, + WIFI_LOG_ERROR , /*enabled by default*/ + WIFI_LOG_WARNING, /*enabled by default*/ + WIFI_LOG_INFO, /*enabled by default*/ + WIFI_LOG_DEBUG, /*can be set in menuconfig*/ + WIFI_LOG_VERBOSE, /*can be set in menuconfig*/ +} wifi_log_level_t; + +/** + * @brief WiFi log module definition + * + */ +typedef enum { + WIFI_LOG_MODULE_ALL = 0, /*all log modules */ + WIFI_LOG_MODULE_WIFI, /*logs related to WiFi*/ + WIFI_LOG_MODULE_COEX, /*logs related to WiFi and BT(or BLE) coexist*/ + WIFI_LOG_MODULE_MESH, /*logs related to Mesh*/ +} wifi_log_module_t; + +/** + * @brief FTM Report log levels configuration + * + */ +typedef struct { + uint8_t show_rtt:1; /**< Display all valid Round-Trip-Time readings for FTM frames */ + uint8_t show_diag:1; /**< Display dialogue tokens for all FTM frames with valid readings */ + uint8_t show_t1t2t3t4:1;/**< Display all valid T1, T2, T3, T4 readings considered while calculating RTT */ + uint8_t show_rxrssi:1; /**< Display RSSI for each FTM frame with valid readings */ +} ftm_report_log_level_t; + +/** + * @brief WiFi log submodule definition + * + */ +#define WIFI_LOG_SUBMODULE_ALL (0) /*all log submodules*/ +#define WIFI_LOG_SUBMODULE_INIT (1) /*logs related to initialization*/ +#define WIFI_LOG_SUBMODULE_IOCTL (1<<1) /*logs related to API calling*/ +#define WIFI_LOG_SUBMODULE_CONN (1<<2) /*logs related to connecting*/ +#define WIFI_LOG_SUBMODULE_SCAN (1<<3) /*logs related to scaning*/ + + +/** + * @brief Initialize Wi-Fi Driver + * Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, + * WiFi NVS structure among others. + * + * For the most part, you need not call this function directly. It gets called + * from esp_wifi_init(). + * + * This function may be called, if you only need to initialize the Wi-Fi driver + * without having to use the network stack on top. + * + * @param config provide WiFi init configuration + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_NO_MEM: out of memory + * - others: refer to error code esp_err.h + */ +esp_err_t esp_wifi_init_internal(const wifi_init_config_t *config); + +/** + * @brief Deinitialize Wi-Fi Driver + * Free resource for WiFi driver, such as WiFi control structure, RX/TX buffer, + * WiFi NVS structure among others. + * + * For the most part, you need not call this function directly. It gets called + * from esp_wifi_deinit(). + * + * This function may be called, if you call esp_wifi_init_internal to initialize + * WiFi driver. + * + * @return + * - ESP_OK: succeed + * - others: refer to error code esp_err.h + */ +esp_err_t esp_wifi_deinit_internal(void); + +/** + * @brief free the rx buffer which allocated by wifi driver + * + * @param void* buffer: rx buffer pointer + */ +void esp_wifi_internal_free_rx_buffer(void* buffer); + +/** + * @brief transmit the buffer via wifi driver + * + * This API makes a copy of the input buffer and then forwards the buffer + * copy to WiFi driver. + * + * @param wifi_interface_t wifi_if : wifi interface id + * @param void *buffer : the buffer to be tansmit + * @param uint16_t len : the length of buffer + * + * @return + * - ESP_OK : Successfully transmit the buffer to wifi driver + * - ESP_ERR_NO_MEM: out of memory + * - ESP_ERR_WIFI_ARG: invalid argument + * - ESP_ERR_WIFI_IF : WiFi interface is invalid + * - ESP_ERR_WIFI_CONN : WiFi interface is not created, e.g. send the data to STA while WiFi mode is AP mode + * - ESP_ERR_WIFI_NOT_STARTED : WiFi is not started + * - ESP_ERR_WIFI_STATE : WiFi internal state is not ready, e.g. WiFi is not started + * - ESP_ERR_WIFI_NOT_ASSOC : WiFi is not associated + * - ESP_ERR_WIFI_TX_DISALLOW : WiFi TX is disallowed, e.g. WiFi hasn't pass the authentication + * - ESP_ERR_WIFI_POST : caller fails to post event to WiFi task + */ +int esp_wifi_internal_tx(wifi_interface_t wifi_if, void *buffer, uint16_t len); + +/** + * @brief The net stack buffer reference counter callback function + * + */ +typedef void (*wifi_netstack_buf_ref_cb_t)(void *netstack_buf); + +/** + * @brief The net stack buffer free callback function + * + */ +typedef void (*wifi_netstack_buf_free_cb_t)(void *netstack_buf); + +/** + * @brief transmit the buffer by reference via wifi driver + * + * This API firstly increases the reference counter of the input buffer and + * then forwards the buffer to WiFi driver. The WiFi driver will free the buffer + * after processing it. Use esp_wifi_internal_tx() if the uplayer buffer doesn't + * supports reference counter. + * + * @param wifi_if : wifi interface id + * @param buffer : the buffer to be tansmit + * @param len : the length of buffer + * @param netstack_buf : the netstack buffer related to bufffer + * + * @return + * - ESP_OK : Successfully transmit the buffer to wifi driver + * - ESP_ERR_NO_MEM: out of memory + * - ESP_ERR_WIFI_ARG: invalid argument + * - ESP_ERR_WIFI_IF : WiFi interface is invalid + * - ESP_ERR_WIFI_CONN : WiFi interface is not created, e.g. send the data to STA while WiFi mode is AP mode + * - ESP_ERR_WIFI_NOT_STARTED : WiFi is not started + * - ESP_ERR_WIFI_STATE : WiFi internal state is not ready, e.g. WiFi is not started + * - ESP_ERR_WIFI_NOT_ASSOC : WiFi is not associated + * - ESP_ERR_WIFI_TX_DISALLOW : WiFi TX is disallowed, e.g. WiFi hasn't pass the authentication + * - ESP_ERR_WIFI_POST : caller fails to post event to WiFi task + */ +esp_err_t esp_wifi_internal_tx_by_ref(wifi_interface_t ifx, void *buffer, size_t len, void *netstack_buf); + +/** + * @brief Initialize WAPI function when wpa_supplicant initialize. + * + * This API is privately used, be careful not open to external applicantion. + * + * @return + * - ESP_OK : succeed + * - ESP_ERR_WAPI_INTERNAL : Internal error + */ +esp_err_t esp_wifi_internal_wapi_init(void); + +/** + * @brief De-initialize WAPI function when wpa_supplicant de-initialize. + * + * This API is privately used, be careful not open to external applicantion. + * + * @return + * - ESP_OK : succeed + */ +esp_err_t esp_wifi_internal_wapi_deinit(void); + +/** + * @brief register the net stack buffer reference increasing and free callback + * + * @param ref : net stack buffer reference callback + * @param free: net stack buffer free callback + * + * @return + * - ESP_OK : Successfully transmit the buffer to wifi driver + * - others : failed to register the callback + */ +esp_err_t esp_wifi_internal_reg_netstack_buf_cb(wifi_netstack_buf_ref_cb_t ref, wifi_netstack_buf_free_cb_t free); + + +/** + * @brief The WiFi RX callback function + * + * Each time the WiFi need to forward the packets to high layer, the callback function will be called + */ +typedef esp_err_t (*wifi_rxcb_t)(void *buffer, uint16_t len, void *eb); + +/** + * @brief Set the WiFi RX callback + * + * @attention 1. Currently we support only one RX callback for each interface + * + * @param wifi_interface_t ifx : interface + * @param wifi_rxcb_t fn : WiFi RX callback + * + * @return + * - ESP_OK : succeed + * - others : fail + */ +esp_err_t esp_wifi_internal_reg_rxcb(wifi_interface_t ifx, wifi_rxcb_t fn); + +/** + * @brief Notify WIFI driver that the station got ip successfully + * + * @return + * - ESP_OK : succeed + * - others : fail + */ +esp_err_t esp_wifi_internal_set_sta_ip(void); + +/** + * @brief enable or disable transmitting WiFi MAC frame with fixed rate + * + * @attention 1. If fixed rate is enabled, both management and data frame are transmitted with fixed rate + * @attention 2. Make sure that the receiver is able to receive the frame with the fixed rate if you want the frame to be received + * + * @param ifx : wifi interface + * @param en : false - disable, true - enable + * @param rate : PHY rate + * + * @return + * - ERR_OK : succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start + * - ESP_ERR_WIFI_IF : invalid WiFi interface + * - ESP_ERR_INVALID_ARG : invalid rate + * - ESP_ERR_NOT_SUPPORTED : do not support to set fixed rate if TX AMPDU is enabled + */ +esp_err_t esp_wifi_internal_set_fix_rate(wifi_interface_t ifx, bool en, wifi_phy_rate_t rate); + +/** + * @brief Start SmartConfig, config ESP device to connect AP. You need to broadcast information by phone APP. + * Device sniffer special packets from the air that containing SSID and password of target AP. + * + * @attention 1. This API can be called in station or softAP-station mode. + * @attention 2. Can not call esp_smartconfig_start twice before it finish, please call + * esp_smartconfig_stop first. + * + * @param config pointer to smartconfig start configure structure + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_internal_start(const smartconfig_start_config_t *config); + +/** + * @brief Stop SmartConfig, free the buffer taken by esp_smartconfig_start. + * + * @attention Whether connect to AP succeed or not, this API should be called to free + * memory taken by smartconfig_start. + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_internal_stop(void); + +/** + * @brief Check the MD5 values of the OS adapter header files in IDF and WiFi library + * + * @attention 1. It is used for internal CI version check + * + * @return + * - ESP_OK : succeed + * - ESP_WIFI_INVALID_ARG : MD5 check fail + */ +esp_err_t esp_wifi_internal_osi_funcs_md5_check(const char *md5); + +/** + * @brief Check the MD5 values of the crypto types header files in IDF and WiFi library + * + * @attention 1. It is used for internal CI version check + * + * @return + * - ESP_OK : succeed + * - ESP_WIFI_INVALID_ARG : MD5 check fail + */ +esp_err_t esp_wifi_internal_crypto_funcs_md5_check(const char *md5); + +/** + * @brief Check the MD5 values of the esp_wifi_types.h in IDF and WiFi library + * + * @attention 1. It is used for internal CI version check + * + * @return + * - ESP_OK : succeed + * - ESP_WIFI_INVALID_ARG : MD5 check fail + */ +esp_err_t esp_wifi_internal_wifi_type_md5_check(const char *md5); + +/** + * @brief Check the MD5 values of the esp_wifi.h in IDF and WiFi library + * + * @attention 1. It is used for internal CI version check + * + * @return + * - ESP_OK : succeed + * - ESP_WIFI_INVALID_ARG : MD5 check fail + */ +esp_err_t esp_wifi_internal_esp_wifi_md5_check(const char *md5); + +/** + * @brief Allocate a chunk of memory for WiFi driver + * + * @attention This API is not used for DMA memory allocation. + * + * @param size_t size : Size, in bytes, of the amount of memory to allocate + * + * @return A pointer to the memory allocated on success, NULL on failure + */ +void *wifi_malloc( size_t size ); + +/** + * @brief Reallocate a chunk of memory for WiFi driver + * + * @attention This API is not used for DMA memory allocation. + * + * @param void * ptr : Pointer to previously allocated memory, or NULL for a new allocation. + * @param size_t size : Size, in bytes, of the amount of memory to allocate + * + * @return A pointer to the memory allocated on success, NULL on failure + */ +void *wifi_realloc( void *ptr, size_t size ); + +/** + * @brief Callocate memory for WiFi driver + * + * @attention This API is not used for DMA memory allocation. + * + * @param size_t n : Number of continuing chunks of memory to allocate + * @param size_t size : Size, in bytes, of the amount of memory to allocate + * + * @return A pointer to the memory allocated on success, NULL on failure + */ +void *wifi_calloc( size_t n, size_t size ); + +/** + * @brief Update WiFi MAC time + * + * @param uint32_t time_delta : time duration since the WiFi/BT common clock is disabled + * + * @return Always returns ESP_OK + */ +typedef esp_err_t (* wifi_mac_time_update_cb_t)( uint32_t time_delta ); + +/** + * @brief Update WiFi MAC time + * + * @param uint32_t time_delta : time duration since the WiFi/BT common clock is disabled + * + * @return Always returns ESP_OK + */ +esp_err_t esp_wifi_internal_update_mac_time( uint32_t time_delta ); + +/** + * @brief Set current WiFi log level + * + * @param level Log level. + * + * @return + * - ESP_OK: succeed + * - ESP_FAIL: level is invalid + */ +esp_err_t esp_wifi_internal_set_log_level(wifi_log_level_t level); + +/** + * @brief Set current log module and submodule + * + * @param module Log module + * @param submodule Log submodule + * @param enable enable or disable + * If module == 0 && enable == 0, all log modules are disabled. + * If module == 0 && enable == 1, all log modules are enabled. + * If submodule == 0 && enable == 0, all log submodules are disabled. + * If submodule == 0 && enable == 1, all log submodules are enabled. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_internal_set_log_mod(wifi_log_module_t module, uint32_t submodule, bool enable); + +/** + * @brief Get current WiFi log info + * + * @param log_level the return log level. + * @param log_mod the return log module and submodule + * + * @return + * - ESP_OK: succeed + */ +esp_err_t esp_wifi_internal_get_log(wifi_log_level_t *log_level, uint32_t *log_mod); + +/** + * @brief A general API to set/get WiFi internal configuration, it's for debug only + * + * @param cmd : ioctl command type + * @param cfg : configuration for the command + * + * @return + * - ESP_OK: succeed + * - others: failed + */ +esp_err_t esp_wifi_internal_ioctl(int cmd, wifi_ioctl_config_t *cfg); + +/** + * @brief Get the user-configured channel info + * + * @param ifx : WiFi interface + * @param primary : store the configured primary channel + * @param second : store the configured second channel + * + * @return + * - ESP_OK: succeed + */ +esp_err_t esp_wifi_internal_get_config_channel(wifi_interface_t ifx, uint8_t *primary, uint8_t *second); + +/** + * @brief Get the negotiated channel info after WiFi connection established + * + * @param ifx : WiFi interface + * @param aid : the connection number when a STA connects to the softAP + * @param primary : store the negotiated primary channel + * @param second : store the negotiated second channel + * @attention the aid param is only works when the ESP32 in softAP/softAP+STA mode + * + * @return + * - ESP_OK: succeed + */ +esp_err_t esp_wifi_internal_get_negotiated_channel(wifi_interface_t ifx, uint8_t aid, uint8_t *primary, uint8_t *second); + +/** + * @brief Get the negotiated bandwidth info after WiFi connection established + * + * @param ifx : WiFi interface + * @param bw : store the negotiated bandwidth + * + * @return + * - ESP_OK: succeed + */ +esp_err_t esp_wifi_internal_get_negotiated_bandwidth(wifi_interface_t ifx, uint8_t aid, uint8_t *bw); + +#if SOC_WIFI_HW_TSF +/** + * @brief Check if WiFi TSF is active + * + * @return + * - true: Active + * - false: Not active + */ +bool esp_wifi_internal_is_tsf_active(void); + +/** + * @brief Update WIFI light sleep wake ahead time + * + */ +void esp_wifi_internal_update_light_sleep_wake_ahead_time(uint32_t); +#endif + +#if CONFIG_MAC_BB_PD +/** + * @brief Enable or disable powering down MAC and baseband when Wi-Fi is sleeping. + * + * @param enable : enable or disable + * + * @return + * - ESP_OK: succeed + */ +esp_err_t esp_wifi_internal_set_mac_sleep(bool enable); + +/** + * @brief mac bb sleep. + */ +void pm_mac_sleep(void); + +/** + * @brief mac bb wakeup. + */ +void pm_mac_wakeup(void); +#endif + +/** + * @breif TxDone callback function type. Should be registered using esp_wifi_set_tx_done_cb() + * + * @param ifidx The interface id that the tx callback has been triggered from + * @param data Pointer to the data transmitted + * @param data_len Length of the data transmitted + * @param txStatus True:if the data was transmitted sucessfully False: if data transmission failed + */ +typedef void (* wifi_tx_done_cb_t)(uint8_t ifidx, uint8_t *data, uint16_t *data_len, bool txStatus); + +/** + * @brief Register the txDone callback function of type wifi_tx_done_cb_t + * + * @param cb The callback function + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + */ +esp_err_t esp_wifi_set_tx_done_cb(wifi_tx_done_cb_t cb); + +/** + * @brief Set device spp amsdu attributes + * + * @param ifx: WiFi interface + * @param spp_cap: spp amsdu capable + * @param spp_req: spp amsdu require + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF : invalid WiFi interface + */ +esp_err_t esp_wifi_internal_set_spp_amsdu(wifi_interface_t ifidx, bool spp_cap, bool spp_req); + +/** + * @brief Update WIFI light sleep default parameters + * + * @param min_freq_mhz: minimum frequency of DFS + * @param max_freq_mhz: maximum frequency of DFS + */ +void esp_wifi_internal_update_light_sleep_default_params(int min_freq_mhz, int max_freq_mhz); + +/** + * @brief Set the delay time for wifi to enter the sleep state when light sleep + * + * @param return_to_sleep_delay: minimum timeout time for waiting to receive + * data, when no data is received during the timeout period, + * the wifi enters the sleep process. + */ +void esp_wifi_set_sleep_delay_time(uint32_t return_to_sleep_delay); + +/** + * @brief Set wifi keep alive time + * + * @param keep_alive_time: keep alive time + */ +void esp_wifi_set_keep_alive_time(uint32_t keep_alive_time); + +/** + * @brief Set FTM Report log level + * + * @param log_lvl Log levels configuration + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_NOT_SUPPORTED: No FTM support + */ +esp_err_t esp_wifi_set_ftm_report_log_level(ftm_report_log_level_t *log_lvl); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_WIFI_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_os_adapter.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_os_adapter.h new file mode 100644 index 00000000..b583e916 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_os_adapter.h @@ -0,0 +1,164 @@ +// Copyright 2018 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. + +#ifndef ESP_WIFI_OS_ADAPTER_H_ +#define ESP_WIFI_OS_ADAPTER_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_WIFI_OS_ADAPTER_VERSION 0x00000008 +#define ESP_WIFI_OS_ADAPTER_MAGIC 0xDEADBEAF + +#define OSI_FUNCS_TIME_BLOCKING 0xffffffff + +#define OSI_QUEUE_SEND_FRONT 0 +#define OSI_QUEUE_SEND_BACK 1 +#define OSI_QUEUE_SEND_OVERWRITE 2 + +typedef struct { + int32_t _version; + bool (* _env_is_chip)(void); + void (*_set_intr)(int32_t cpu_no, uint32_t intr_source, uint32_t intr_num, int32_t intr_prio); + void (*_clear_intr)(uint32_t intr_source, uint32_t intr_num); + void (*_set_isr)(int32_t n, void *f, void *arg); + void (*_ints_on)(uint32_t mask); + void (*_ints_off)(uint32_t mask); + bool (* _is_from_isr)(void); + void *(* _spin_lock_create)(void); + void (* _spin_lock_delete)(void *lock); + uint32_t (*_wifi_int_disable)(void *wifi_int_mux); + void (*_wifi_int_restore)(void *wifi_int_mux, uint32_t tmp); + void (*_task_yield_from_isr)(void); + void *(*_semphr_create)(uint32_t max, uint32_t init); + void (*_semphr_delete)(void *semphr); + int32_t (*_semphr_take)(void *semphr, uint32_t block_time_tick); + int32_t (*_semphr_give)(void *semphr); + void *(*_wifi_thread_semphr_get)(void); + void *(*_mutex_create)(void); + void *(*_recursive_mutex_create)(void); + void (*_mutex_delete)(void *mutex); + int32_t (*_mutex_lock)(void *mutex); + int32_t (*_mutex_unlock)(void *mutex); + void *(* _queue_create)(uint32_t queue_len, uint32_t item_size); + void (* _queue_delete)(void *queue); + int32_t (* _queue_send)(void *queue, void *item, uint32_t block_time_tick); + int32_t (* _queue_send_from_isr)(void *queue, void *item, void *hptw); + int32_t (* _queue_send_to_back)(void *queue, void *item, uint32_t block_time_tick); + int32_t (* _queue_send_to_front)(void *queue, void *item, uint32_t block_time_tick); + int32_t (* _queue_recv)(void *queue, void *item, uint32_t block_time_tick); + uint32_t (* _queue_msg_waiting)(void *queue); + void *(* _event_group_create)(void); + void (* _event_group_delete)(void *event); + uint32_t (* _event_group_set_bits)(void *event, uint32_t bits); + uint32_t (* _event_group_clear_bits)(void *event, uint32_t bits); + uint32_t (* _event_group_wait_bits)(void *event, uint32_t bits_to_wait_for, int clear_on_exit, int wait_for_all_bits, uint32_t block_time_tick); + int32_t (* _task_create_pinned_to_core)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle, uint32_t core_id); + int32_t (* _task_create)(void *task_func, const char *name, uint32_t stack_depth, void *param, uint32_t prio, void *task_handle); + void (* _task_delete)(void *task_handle); + void (* _task_delay)(uint32_t tick); + int32_t (* _task_ms_to_tick)(uint32_t ms); + void *(* _task_get_current_task)(void); + int32_t (* _task_get_max_priority)(void); + void *(* _malloc)(unsigned int size); + void (* _free)(void *p); + int32_t (* _event_post)(const char* event_base, int32_t event_id, void* event_data, size_t event_data_size, uint32_t ticks_to_wait); + uint32_t (* _get_free_heap_size)(void); + uint32_t (* _rand)(void); + void (* _dport_access_stall_other_cpu_start_wrap)(void); + void (* _dport_access_stall_other_cpu_end_wrap)(void); + void (* _wifi_apb80m_request)(void); + void (* _wifi_apb80m_release)(void); + void (* _phy_disable)(void); + void (* _phy_enable)(void); +#if CONFIG_IDF_TARGET_ESP32 + void (* _phy_common_clock_enable)(void); + void (* _phy_common_clock_disable)(void); +#endif + int (* _phy_update_country_info)(const char* country); + int (* _read_mac)(uint8_t* mac, uint32_t type); + void (* _timer_arm)(void *timer, uint32_t tmout, bool repeat); + void (* _timer_disarm)(void *timer); + void (* _timer_done)(void *ptimer); + void (* _timer_setfn)(void *ptimer, void *pfunction, void *parg); + void (* _timer_arm_us)(void *ptimer, uint32_t us, bool repeat); + void (* _wifi_reset_mac)(void); + void (* _wifi_clock_enable)(void); + void (* _wifi_clock_disable)(void); + void (* _wifi_rtc_enable_iso)(void); + void (* _wifi_rtc_disable_iso)(void); + int64_t (* _esp_timer_get_time)(void); + int (* _nvs_set_i8)(uint32_t handle, const char* key, int8_t value); + int (* _nvs_get_i8)(uint32_t handle, const char* key, int8_t* out_value); + int (* _nvs_set_u8)(uint32_t handle, const char* key, uint8_t value); + int (* _nvs_get_u8)(uint32_t handle, const char* key, uint8_t* out_value); + int (* _nvs_set_u16)(uint32_t handle, const char* key, uint16_t value); + int (* _nvs_get_u16)(uint32_t handle, const char* key, uint16_t* out_value); + int (* _nvs_open)(const char* name, uint32_t open_mode, uint32_t *out_handle); + void (* _nvs_close)(uint32_t handle); + int (* _nvs_commit)(uint32_t handle); + int (* _nvs_set_blob)(uint32_t handle, const char* key, const void* value, size_t length); + int (* _nvs_get_blob)(uint32_t handle, const char* key, void* out_value, size_t* length); + int (* _nvs_erase_key)(uint32_t handle, const char* key); + int (* _get_random)(uint8_t *buf, size_t len); + int (* _get_time)(void *t); + unsigned long (* _random)(void); +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3 + uint32_t (* _slowclk_cal_get)(void); +#endif + void (* _log_write)(uint32_t level, const char* tag, const char* format, ...); + void (* _log_writev)(uint32_t level, const char* tag, const char* format, va_list args); + uint32_t (* _log_timestamp)(void); + void * (* _malloc_internal)(size_t size); + void * (* _realloc_internal)(void *ptr, size_t size); + void * (* _calloc_internal)(size_t n, size_t size); + void * (* _zalloc_internal)(size_t size); + void * (* _wifi_malloc)(size_t size); + void * (* _wifi_realloc)(void *ptr, size_t size); + void * (* _wifi_calloc)(size_t n, size_t size); + void * (* _wifi_zalloc)(size_t size); + void * (* _wifi_create_queue)(int queue_len, int item_size); + void (* _wifi_delete_queue)(void * queue); + int (* _coex_init)(void); + void (* _coex_deinit)(void); + int (* _coex_enable)(void); + void (* _coex_disable)(void); + uint32_t (* _coex_status_get)(void); + void (* _coex_condition_set)(uint32_t type, bool dissatisfy); + int (* _coex_wifi_request)(uint32_t event, uint32_t latency, uint32_t duration); + int (* _coex_wifi_release)(uint32_t event); + int (* _coex_wifi_channel_set)(uint8_t primary, uint8_t secondary); + int (* _coex_event_duration_get)(uint32_t event, uint32_t *duration); + int (* _coex_pti_get)(uint32_t event, uint8_t *pti); + void (* _coex_schm_status_bit_clear)(uint32_t type, uint32_t status); + void (* _coex_schm_status_bit_set)(uint32_t type, uint32_t status); + int (* _coex_schm_interval_set)(uint32_t interval); + uint32_t (* _coex_schm_interval_get)(void); + uint8_t (* _coex_schm_curr_period_get)(void); + void * (* _coex_schm_curr_phase_get)(void); + int (* _coex_schm_curr_phase_idx_set)(int idx); + int (* _coex_schm_curr_phase_idx_get)(void); + int32_t _magic; +} wifi_osi_funcs_t; + +extern wifi_osi_funcs_t g_wifi_osi_funcs; + +#ifdef __cplusplus +} +#endif + +#endif /* ESP_WIFI_OS_ADAPTER_H_ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_types.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_types.h new file mode 100644 index 00000000..4542492c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_private/wifi_types.h @@ -0,0 +1,54 @@ +// Copyright 2015-2019 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. + +#ifndef _WIFI_TYPES_H +#define _WIFI_TYPES_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief WiFi ioctl command type + * + */ +typedef enum { + WIFI_IOCTL_SET_STA_HT2040_COEX = 1, /**< Set the configuration of STA's HT2040 coexist management */ + WIFI_IOCTL_GET_STA_HT2040_COEX, /**< Get the configuration of STA's HT2040 coexist management */ + WIFI_IOCTL_MAX, +} wifi_ioctl_cmd_t; + +/** + * @brief Configuration for STA's HT2040 coexist management + * + */ +typedef struct { + int enable; /**< Indicate whether STA's HT2040 coexist management is enabled or not */ +} wifi_ht2040_coex_t; + +/** + * @brief Configuration for WiFi ioctl + * + */ +typedef struct { + union { + wifi_ht2040_coex_t ht2040_coex; /**< Configuration of STA's HT2040 coexist management */ + } data; /**< Configuration of ioctl command */ +} wifi_ioctl_config_t; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_smartconfig.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_smartconfig.h new file mode 100644 index 00000000..b70d0c40 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_smartconfig.h @@ -0,0 +1,163 @@ +// Copyright 2015-2016 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. + +#ifndef __ESP_SMARTCONFIG_H__ +#define __ESP_SMARTCONFIG_H__ + +#include +#include +#include "esp_err.h" +#include "esp_event_base.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + SC_TYPE_ESPTOUCH = 0, /**< protocol: ESPTouch */ + SC_TYPE_AIRKISS, /**< protocol: AirKiss */ + SC_TYPE_ESPTOUCH_AIRKISS, /**< protocol: ESPTouch and AirKiss */ + SC_TYPE_ESPTOUCH_V2, /**< protocol: ESPTouch v2*/ +} smartconfig_type_t; + +/** Smartconfig event declarations */ +typedef enum { + SC_EVENT_SCAN_DONE, /*!< ESP32 station smartconfig has finished to scan for APs */ + SC_EVENT_FOUND_CHANNEL, /*!< ESP32 station smartconfig has found the channel of the target AP */ + SC_EVENT_GOT_SSID_PSWD, /*!< ESP32 station smartconfig got the SSID and password */ + SC_EVENT_SEND_ACK_DONE, /*!< ESP32 station smartconfig has sent ACK to cellphone */ +} smartconfig_event_t; + +/** @brief smartconfig event base declaration */ +ESP_EVENT_DECLARE_BASE(SC_EVENT); + +/** Argument structure for SC_EVENT_GOT_SSID_PSWD event */ +typedef struct { + uint8_t ssid[32]; /**< SSID of the AP. Null terminated string. */ + uint8_t password[64]; /**< Password of the AP. Null terminated string. */ + bool bssid_set; /**< whether set MAC address of target AP or not. */ + uint8_t bssid[6]; /**< MAC address of target AP. */ + smartconfig_type_t type; /**< Type of smartconfig(ESPTouch or AirKiss). */ + uint8_t token; /**< Token from cellphone which is used to send ACK to cellphone. */ + uint8_t cellphone_ip[4]; /**< IP address of cellphone. */ +} smartconfig_event_got_ssid_pswd_t; + +/** Configure structure for esp_smartconfig_start */ +typedef struct { + bool enable_log; /**< Enable smartconfig logs. */ + bool esp_touch_v2_enable_crypt; /**< Enable ESPTouch v2 crypt. */ + char *esp_touch_v2_key; /**< ESPTouch v2 crypt key, len should be 16. */ +} smartconfig_start_config_t; + +#define SMARTCONFIG_START_CONFIG_DEFAULT() { \ + .enable_log = false, \ + .esp_touch_v2_enable_crypt = false,\ + .esp_touch_v2_key = NULL \ +}; + +/** + * @brief Get the version of SmartConfig. + * + * @return + * - SmartConfig version const char. + */ +const char *esp_smartconfig_get_version(void); + +/** + * @brief Start SmartConfig, config ESP device to connect AP. You need to broadcast information by phone APP. + * Device sniffer special packets from the air that containing SSID and password of target AP. + * + * @attention 1. This API can be called in station or softAP-station mode. + * @attention 2. Can not call esp_smartconfig_start twice before it finish, please call + * esp_smartconfig_stop first. + * + * @param config pointer to smartconfig start configure structure + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_start(const smartconfig_start_config_t *config); + +/** + * @brief Stop SmartConfig, free the buffer taken by esp_smartconfig_start. + * + * @attention Whether connect to AP succeed or not, this API should be called to free + * memory taken by smartconfig_start. + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_stop(void); + +/** + * @brief Set timeout of SmartConfig process. + * + * @attention Timing starts from SC_STATUS_FIND_CHANNEL status. SmartConfig will restart if timeout. + * + * @param time_s range 15s~255s, offset:45s. + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_esptouch_set_timeout(uint8_t time_s); + +/** + * @brief Set protocol type of SmartConfig. + * + * @attention If users need to set the SmartConfig type, please set it before calling + * esp_smartconfig_start. + * + * @param type Choose from the smartconfig_type_t. + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_set_type(smartconfig_type_t type); + +/** + * @brief Set mode of SmartConfig. default normal mode. + * + * @attention 1. Please call it before API esp_smartconfig_start. + * @attention 2. Fast mode have corresponding APP(phone). + * @attention 3. Two mode is compatible. + * + * @param enable false-disable(default); true-enable; + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_fast_mode(bool enable); + +/** + * @brief Get reserved data of ESPTouch v2. + * + * @param rvd_data reserved data + * @param len length of reserved data + * + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_smartconfig_get_rvd_data(uint8_t *rvd_data, uint8_t len); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi.h new file mode 100644 index 00000000..86dcf637 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi.h @@ -0,0 +1,1225 @@ +// Copyright 2015-2016 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. + + +/* Notes about WiFi Programming + * + * The esp32 WiFi programming model can be depicted as following picture: + * + * + * default handler user handler + * ------------- --------------- --------------- + * | | event | | callback or | | + * | tcpip | ---------> | event | ----------> | application | + * | stack | | task | event | task | + * |-----------| |-------------| |-------------| + * /|\ | + * | | + * event | | + * | | + * | | + * --------------- | + * | | | + * | WiFi Driver |/__________________| + * | |\ API call + * | | + * |-------------| + * + * The WiFi driver can be consider as black box, it knows nothing about the high layer code, such as + * TCPIP stack, application task, event task etc, all it can do is to receive API call from high layer + * or post event queue to a specified Queue, which is initialized by API esp_wifi_init(). + * + * The event task is a daemon task, which receives events from WiFi driver or from other subsystem, such + * as TCPIP stack, event task will call the default callback function on receiving the event. For example, + * on receiving event SYSTEM_EVENT_STA_CONNECTED, it will call tcpip_adapter_start() to start the DHCP + * client in it's default handler. + * + * Application can register it's own event callback function by API esp_event_init, then the application callback + * function will be called after the default callback. Also, if application doesn't want to execute the callback + * in the event task, what it needs to do is to post the related event to application task in the application callback function. + * + * The application task (code) generally mixes all these thing together, it calls APIs to init the system/WiFi and + * handle the events when necessary. + * + */ + +#ifndef __ESP_WIFI_H__ +#define __ESP_WIFI_H__ + +#include +#include +#include "esp_err.h" +#include "esp_wifi_types.h" +#include "esp_event.h" +#include "esp_private/esp_wifi_private.h" +#include "esp_wifi_default.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_ERR_WIFI_NOT_INIT (ESP_ERR_WIFI_BASE + 1) /*!< WiFi driver was not installed by esp_wifi_init */ +#define ESP_ERR_WIFI_NOT_STARTED (ESP_ERR_WIFI_BASE + 2) /*!< WiFi driver was not started by esp_wifi_start */ +#define ESP_ERR_WIFI_NOT_STOPPED (ESP_ERR_WIFI_BASE + 3) /*!< WiFi driver was not stopped by esp_wifi_stop */ +#define ESP_ERR_WIFI_IF (ESP_ERR_WIFI_BASE + 4) /*!< WiFi interface error */ +#define ESP_ERR_WIFI_MODE (ESP_ERR_WIFI_BASE + 5) /*!< WiFi mode error */ +#define ESP_ERR_WIFI_STATE (ESP_ERR_WIFI_BASE + 6) /*!< WiFi internal state error */ +#define ESP_ERR_WIFI_CONN (ESP_ERR_WIFI_BASE + 7) /*!< WiFi internal control block of station or soft-AP error */ +#define ESP_ERR_WIFI_NVS (ESP_ERR_WIFI_BASE + 8) /*!< WiFi internal NVS module error */ +#define ESP_ERR_WIFI_MAC (ESP_ERR_WIFI_BASE + 9) /*!< MAC address is invalid */ +#define ESP_ERR_WIFI_SSID (ESP_ERR_WIFI_BASE + 10) /*!< SSID is invalid */ +#define ESP_ERR_WIFI_PASSWORD (ESP_ERR_WIFI_BASE + 11) /*!< Password is invalid */ +#define ESP_ERR_WIFI_TIMEOUT (ESP_ERR_WIFI_BASE + 12) /*!< Timeout error */ +#define ESP_ERR_WIFI_WAKE_FAIL (ESP_ERR_WIFI_BASE + 13) /*!< WiFi is in sleep state(RF closed) and wakeup fail */ +#define ESP_ERR_WIFI_WOULD_BLOCK (ESP_ERR_WIFI_BASE + 14) /*!< The caller would block */ +#define ESP_ERR_WIFI_NOT_CONNECT (ESP_ERR_WIFI_BASE + 15) /*!< Station still in disconnect status */ + +#define ESP_ERR_WIFI_POST (ESP_ERR_WIFI_BASE + 18) /*!< Failed to post the event to WiFi task */ +#define ESP_ERR_WIFI_INIT_STATE (ESP_ERR_WIFI_BASE + 19) /*!< Invalid WiFi state when init/deinit is called */ +#define ESP_ERR_WIFI_STOP_STATE (ESP_ERR_WIFI_BASE + 20) /*!< Returned when WiFi is stopping */ +#define ESP_ERR_WIFI_NOT_ASSOC (ESP_ERR_WIFI_BASE + 21) /*!< The WiFi connection is not associated */ +#define ESP_ERR_WIFI_TX_DISALLOW (ESP_ERR_WIFI_BASE + 22) /*!< The WiFi TX is disallowed */ + +/** + * @brief WiFi stack configuration parameters passed to esp_wifi_init call. + */ +typedef struct { + system_event_handler_t event_handler; /**< WiFi event handler */ + wifi_osi_funcs_t* osi_funcs; /**< WiFi OS functions */ + wpa_crypto_funcs_t wpa_crypto_funcs; /**< WiFi station crypto functions when connect */ + int static_rx_buf_num; /**< WiFi static RX buffer number */ + int dynamic_rx_buf_num; /**< WiFi dynamic RX buffer number */ + int tx_buf_type; /**< WiFi TX buffer type */ + int static_tx_buf_num; /**< WiFi static TX buffer number */ + int dynamic_tx_buf_num; /**< WiFi dynamic TX buffer number */ + int cache_tx_buf_num; /**< WiFi TX cache buffer number */ + int csi_enable; /**< WiFi channel state information enable flag */ + int ampdu_rx_enable; /**< WiFi AMPDU RX feature enable flag */ + int ampdu_tx_enable; /**< WiFi AMPDU TX feature enable flag */ + int amsdu_tx_enable; /**< WiFi AMSDU TX feature enable flag */ + int nvs_enable; /**< WiFi NVS flash enable flag */ + int nano_enable; /**< Nano option for printf/scan family enable flag */ + int rx_ba_win; /**< WiFi Block Ack RX window size */ + int wifi_task_core_id; /**< WiFi Task Core ID */ + int beacon_max_len; /**< WiFi softAP maximum length of the beacon */ + int mgmt_sbuf_num; /**< WiFi management short buffer number, the minimum value is 6, the maximum value is 32 */ + uint64_t feature_caps; /**< Enables additional WiFi features and capabilities */ + bool sta_disconnected_pm; /**< WiFi Power Management for station at disconnected status */ + int magic; /**< WiFi init magic number, it should be the last field */ +} wifi_init_config_t; + +#ifdef CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM +#define WIFI_STATIC_TX_BUFFER_NUM CONFIG_ESP32_WIFI_STATIC_TX_BUFFER_NUM +#else +#define WIFI_STATIC_TX_BUFFER_NUM 0 +#endif + +#if (CONFIG_ESP32_SPIRAM_SUPPORT || CONFIG_ESP32S2_SPIRAM_SUPPORT || CONFIG_ESP32S3_SPIRAM_SUPPORT) +#define WIFI_CACHE_TX_BUFFER_NUM CONFIG_ESP32_WIFI_CACHE_TX_BUFFER_NUM +#else +#define WIFI_CACHE_TX_BUFFER_NUM 0 +#endif + +#ifdef CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM +#define WIFI_DYNAMIC_TX_BUFFER_NUM CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM +#else +#define WIFI_DYNAMIC_TX_BUFFER_NUM 0 +#endif + +#if CONFIG_ESP32_WIFI_CSI_ENABLED +#define WIFI_CSI_ENABLED 1 +#else +#define WIFI_CSI_ENABLED 0 +#endif + +#if CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED +#define WIFI_AMPDU_RX_ENABLED 1 +#else +#define WIFI_AMPDU_RX_ENABLED 0 +#endif + +#if CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED +#define WIFI_AMPDU_TX_ENABLED 1 +#else +#define WIFI_AMPDU_TX_ENABLED 0 +#endif + +#if CONFIG_ESP32_WIFI_AMSDU_TX_ENABLED +#define WIFI_AMSDU_TX_ENABLED 1 +#else +#define WIFI_AMSDU_TX_ENABLED 0 +#endif + +#if CONFIG_ESP32_WIFI_NVS_ENABLED +#define WIFI_NVS_ENABLED 1 +#else +#define WIFI_NVS_ENABLED 0 +#endif + +#if CONFIG_NEWLIB_NANO_FORMAT +#define WIFI_NANO_FORMAT_ENABLED 1 +#else +#define WIFI_NANO_FORMAT_ENABLED 0 +#endif + +extern const wpa_crypto_funcs_t g_wifi_default_wpa_crypto_funcs; +extern uint64_t g_wifi_feature_caps; + +#define WIFI_INIT_CONFIG_MAGIC 0x1F2F3F4F + +#ifdef CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED +#define WIFI_DEFAULT_RX_BA_WIN CONFIG_ESP32_WIFI_RX_BA_WIN +#else +#define WIFI_DEFAULT_RX_BA_WIN 0 /* unused if ampdu_rx_enable == false */ +#endif + +#if CONFIG_ESP32_WIFI_TASK_PINNED_TO_CORE_1 +#define WIFI_TASK_CORE_ID 1 +#else +#define WIFI_TASK_CORE_ID 0 +#endif + +#ifdef CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN +#define WIFI_SOFTAP_BEACON_MAX_LEN CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN +#else +#define WIFI_SOFTAP_BEACON_MAX_LEN 752 +#endif + +#ifdef CONFIG_ESP32_WIFI_MGMT_SBUF_NUM +#define WIFI_MGMT_SBUF_NUM CONFIG_ESP32_WIFI_MGMT_SBUF_NUM +#else +#define WIFI_MGMT_SBUF_NUM 32 +#endif + +#if CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE +#define WIFI_STA_DISCONNECTED_PM_ENABLED true +#else +#define WIFI_STA_DISCONNECTED_PM_ENABLED false +#endif + +#define CONFIG_FEATURE_WPA3_SAE_BIT (1<<0) +#define CONFIG_FEATURE_CACHE_TX_BUF_BIT (1<<1) +#define CONFIG_FEATURE_FTM_INITIATOR_BIT (1<<2) +#define CONFIG_FEATURE_FTM_RESPONDER_BIT (1<<3) + +#define WIFI_INIT_CONFIG_DEFAULT() { \ + .event_handler = &esp_event_send_internal, \ + .osi_funcs = &g_wifi_osi_funcs, \ + .wpa_crypto_funcs = g_wifi_default_wpa_crypto_funcs, \ + .static_rx_buf_num = CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM,\ + .dynamic_rx_buf_num = CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM,\ + .tx_buf_type = CONFIG_ESP32_WIFI_TX_BUFFER_TYPE,\ + .static_tx_buf_num = WIFI_STATIC_TX_BUFFER_NUM,\ + .dynamic_tx_buf_num = WIFI_DYNAMIC_TX_BUFFER_NUM,\ + .cache_tx_buf_num = WIFI_CACHE_TX_BUFFER_NUM,\ + .csi_enable = WIFI_CSI_ENABLED,\ + .ampdu_rx_enable = WIFI_AMPDU_RX_ENABLED,\ + .ampdu_tx_enable = WIFI_AMPDU_TX_ENABLED,\ + .amsdu_tx_enable = WIFI_AMSDU_TX_ENABLED,\ + .nvs_enable = WIFI_NVS_ENABLED,\ + .nano_enable = WIFI_NANO_FORMAT_ENABLED,\ + .rx_ba_win = WIFI_DEFAULT_RX_BA_WIN,\ + .wifi_task_core_id = WIFI_TASK_CORE_ID,\ + .beacon_max_len = WIFI_SOFTAP_BEACON_MAX_LEN, \ + .mgmt_sbuf_num = WIFI_MGMT_SBUF_NUM, \ + .feature_caps = g_wifi_feature_caps, \ + .sta_disconnected_pm = WIFI_STA_DISCONNECTED_PM_ENABLED, \ + .magic = WIFI_INIT_CONFIG_MAGIC\ +}; + +/** + * @brief Init WiFi + * Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, + * WiFi NVS structure etc, this WiFi also start WiFi task + * + * @attention 1. This API must be called before all other WiFi API can be called + * @attention 2. Always use WIFI_INIT_CONFIG_DEFAULT macro to init the config to default values, this can + * guarantee all the fields got correct value when more fields are added into wifi_init_config_t + * in future release. If you want to set your owner initial values, overwrite the default values + * which are set by WIFI_INIT_CONFIG_DEFAULT, please be notified that the field 'magic' of + * wifi_init_config_t should always be WIFI_INIT_CONFIG_MAGIC! + * + * @param config pointer to WiFi init configuration structure; can point to a temporary variable. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_NO_MEM: out of memory + * - others: refer to error code esp_err.h + */ +esp_err_t esp_wifi_init(const wifi_init_config_t *config); + +/** + * @brief Deinit WiFi + * Free all resource allocated in esp_wifi_init and stop WiFi task + * + * @attention 1. This API should be called if you want to remove WiFi driver from the system + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_deinit(void); + +/** + * @brief Set the WiFi operating mode + * + * Set the WiFi operating mode as station, soft-AP or station+soft-AP, + * The default mode is soft-AP mode. + * + * @param mode WiFi operating mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - others: refer to error code in esp_err.h + */ +esp_err_t esp_wifi_set_mode(wifi_mode_t mode); + +/** + * @brief Get current operating mode of WiFi + * + * @param[out] mode store current WiFi mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_mode(wifi_mode_t *mode); + +/** + * @brief Start WiFi according to current configuration + * If mode is WIFI_MODE_STA, it create station control block and start station + * If mode is WIFI_MODE_AP, it create soft-AP control block and start soft-AP + * If mode is WIFI_MODE_APSTA, it create soft-AP and station control block and start soft-AP and station + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_NO_MEM: out of memory + * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong + * - ESP_FAIL: other WiFi internal errors + */ +esp_err_t esp_wifi_start(void); + +/** + * @brief Stop WiFi + * If mode is WIFI_MODE_STA, it stop station and free station control block + * If mode is WIFI_MODE_AP, it stop soft-AP and free soft-AP control block + * If mode is WIFI_MODE_APSTA, it stop station/soft-AP and free station/soft-AP control block + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_stop(void); + +/** + * @brief Restore WiFi stack persistent settings to default values + * + * This function will reset settings made using the following APIs: + * - esp_wifi_set_bandwidth, + * - esp_wifi_set_protocol, + * - esp_wifi_set_config related + * - esp_wifi_set_mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_restore(void); + +/** + * @brief Connect the ESP32 WiFi station to the AP. + * + * @attention 1. This API only impact WIFI_MODE_STA or WIFI_MODE_APSTA mode + * @attention 2. If the ESP32 is connected to an AP, call esp_wifi_disconnect to disconnect. + * @attention 3. The scanning triggered by esp_wifi_start_scan() will not be effective until connection between ESP32 and the AP is established. + * If ESP32 is scanning and connecting at the same time, ESP32 will abort scanning and return a warning message and error + * number ESP_ERR_WIFI_STATE. + * If you want to do reconnection after ESP32 received disconnect event, remember to add the maximum retry time, otherwise the called + * scan will not work. This is especially true when the AP doesn't exist, and you still try reconnection after ESP32 received disconnect + * event with the reason code WIFI_REASON_NO_AP_FOUND. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + * - ESP_ERR_WIFI_CONN: WiFi internal error, station or soft-AP control block wrong + * - ESP_ERR_WIFI_SSID: SSID of AP which station connects is invalid + */ +esp_err_t esp_wifi_connect(void); + +/** + * @brief Disconnect the ESP32 WiFi station from the AP. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi was not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start + * - ESP_FAIL: other WiFi internal errors + */ +esp_err_t esp_wifi_disconnect(void); + +/** + * @brief Currently this API is just an stub API + * + + * @return + * - ESP_OK: succeed + * - others: fail + */ +esp_err_t esp_wifi_clear_fast_connect(void); + +/** + * @brief deauthenticate all stations or associated id equals to aid + * + * @param aid when aid is 0, deauthenticate all stations, otherwise deauthenticate station whose associated id is aid + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_MODE: WiFi mode is wrong + */ +esp_err_t esp_wifi_deauth_sta(uint16_t aid); + +/** + * @brief Scan all available APs. + * + * @attention If this API is called, the found APs are stored in WiFi driver dynamic allocated memory and the + * will be freed in esp_wifi_scan_get_ap_records, so generally, call esp_wifi_scan_get_ap_records to cause + * the memory to be freed once the scan is done + * @attention The values of maximum active scan time and passive scan time per channel are limited to 1500 milliseconds. + * Values above 1500ms may cause station to disconnect from AP and are not recommended. + * + * @param config configuration of scanning + * @param block if block is true, this API will block the caller until the scan is done, otherwise + * it will return immediately + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi was not started by esp_wifi_start + * - ESP_ERR_WIFI_TIMEOUT: blocking scan is timeout + * - ESP_ERR_WIFI_STATE: wifi still connecting when invoke esp_wifi_scan_start + * - others: refer to error code in esp_err.h + */ +esp_err_t esp_wifi_scan_start(const wifi_scan_config_t *config, bool block); + +/** + * @brief Stop the scan in process + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + */ +esp_err_t esp_wifi_scan_stop(void); + +/** + * @brief Get number of APs found in last scan + * + * @param[out] number store number of APIs found in last scan + * + * @attention This API can only be called when the scan is completed, otherwise it may get wrong value. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_scan_get_ap_num(uint16_t *number); + +/** + * @brief Get AP list found in last scan + * + * @param[inout] number As input param, it stores max AP number ap_records can hold. + * As output param, it receives the actual AP number this API returns. + * @param ap_records wifi_ap_record_t array to hold the found APs + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_NO_MEM: out of memory + */ +esp_err_t esp_wifi_scan_get_ap_records(uint16_t *number, wifi_ap_record_t *ap_records); + + +/** + * @brief Get information of AP which the ESP32 station is associated with + * + * @attention When the obtained country information is empty, it means that the AP does not carry country information + * + * @param ap_info the wifi_ap_record_t to hold AP information + * sta can get the connected ap's phy mode info through the struct member + * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_ap_record_t struct. + * For example, phy_11b = 1 imply that ap support 802.11b mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_CONN: The station interface don't initialized + * - ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status + */ +esp_err_t esp_wifi_sta_get_ap_info(wifi_ap_record_t *ap_info); + +/** + * @brief Set current WiFi power save type + * + * @attention Default power save type is WIFI_PS_MIN_MODEM. + * + * @param type power save type + * + * @return ESP_OK: succeed + */ +esp_err_t esp_wifi_set_ps(wifi_ps_type_t type); + +/** + * @brief Get current WiFi power save type + * + * @attention Default power save type is WIFI_PS_MIN_MODEM. + * + * @param[out] type: store current power save type + * + * @return ESP_OK: succeed + */ +esp_err_t esp_wifi_get_ps(wifi_ps_type_t *type); + +/** + * @brief Set protocol type of specified interface + * The default protocol is (WIFI_PROTOCOL_11B|WIFI_PROTOCOL_11G|WIFI_PROTOCOL_11N) + * + * @attention Currently we only support 802.11b or 802.11bg or 802.11bgn mode + * + * @param ifx interfaces + * @param protocol_bitmap WiFi protocol bitmap + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - others: refer to error codes in esp_err.h + */ +esp_err_t esp_wifi_set_protocol(wifi_interface_t ifx, uint8_t protocol_bitmap); + +/** + * @brief Get the current protocol bitmap of the specified interface + * + * @param ifx interface + * @param[out] protocol_bitmap store current WiFi protocol bitmap of interface ifx + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_INVALID_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ +esp_err_t esp_wifi_get_protocol(wifi_interface_t ifx, uint8_t *protocol_bitmap); + +/** + * @brief Set the bandwidth of ESP32 specified interface + * + * @attention 1. API return false if try to configure an interface that is not enabled + * @attention 2. WIFI_BW_HT40 is supported only when the interface support 11N + * + * @param ifx interface to be configured + * @param bw bandwidth + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_INVALID_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ +esp_err_t esp_wifi_set_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t bw); + +/** + * @brief Get the bandwidth of ESP32 specified interface + * + * @attention 1. API return false if try to get a interface that is not enable + * + * @param ifx interface to be configured + * @param[out] bw store bandwidth of interface ifx + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_bandwidth(wifi_interface_t ifx, wifi_bandwidth_t *bw); + +/** + * @brief Set primary/secondary channel of ESP32 + * + * @attention 1. This API should be called after esp_wifi_start() + * @attention 2. When ESP32 is in STA mode, this API should not be called when STA is scanning or connecting to an external AP + * @attention 3. When ESP32 is in softAP mode, this API should not be called when softAP has connected to external STAs + * @attention 4. When ESP32 is in STA+softAP mode, this API should not be called when in the scenarios described above + * + * @param primary for HT20, primary is the channel number, for HT40, primary is the primary channel + * @param second for HT20, second is ignored, for HT40, second is the second channel + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_set_channel(uint8_t primary, wifi_second_chan_t second); + +/** + * @brief Get the primary/secondary channel of ESP32 + * + * @attention 1. API return false if try to get a interface that is not enable + * + * @param primary store current primary channel + * @param[out] second store current second channel + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second); + +/** + * @brief configure country info + * + * @attention 1. The default country is {.cc="CN", .schan=1, .nchan=13, policy=WIFI_COUNTRY_POLICY_AUTO} + * @attention 2. When the country policy is WIFI_COUNTRY_POLICY_AUTO, the country info of the AP to which + * the station is connected is used. E.g. if the configured country info is {.cc="USA", .schan=1, .nchan=11} + * and the country info of the AP to which the station is connected is {.cc="JP", .schan=1, .nchan=14} + * then the country info that will be used is {.cc="JP", .schan=1, .nchan=14}. If the station disconnected + * from the AP the country info is set back back to the country info of the station automatically, + * {.cc="US", .schan=1, .nchan=11} in the example. + * @attention 3. When the country policy is WIFI_COUNTRY_POLICY_MANUAL, always use the configured country info. + * @attention 4. When the country info is changed because of configuration or because the station connects to a different + * external AP, the country IE in probe response/beacon of the soft-AP is changed also. + * @attention 5. The country configuration is stored into flash. + * @attention 6. This API doesn't validate the per-country rules, it's up to the user to fill in all fields according to + * local regulations. + * @attention 7. When this API is called, the PHY init data will switch to the PHY init data type corresponding to the + * country info. + * + * @param country the configured country info + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_set_country(const wifi_country_t *country); + +/** + * @brief get the current country info + * + * @param country country info + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_country(wifi_country_t *country); + + +/** + * @brief Set MAC address of the ESP32 WiFi station or the soft-AP interface. + * + * @attention 1. This API can only be called when the interface is disabled + * @attention 2. ESP32 soft-AP and station have different MAC addresses, do not set them to be the same. + * @attention 3. The bit 0 of the first byte of ESP32 MAC address can not be 1. For example, the MAC address + * can set to be "1a:XX:XX:XX:XX:XX", but can not be "15:XX:XX:XX:XX:XX". + * + * @param ifx interface + * @param mac the MAC address + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_MAC: invalid mac address + * - ESP_ERR_WIFI_MODE: WiFi mode is wrong + * - others: refer to error codes in esp_err.h + */ +esp_err_t esp_wifi_set_mac(wifi_interface_t ifx, const uint8_t mac[6]); + +/** + * @brief Get mac of specified interface + * + * @param ifx interface + * @param[out] mac store mac of the interface ifx + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_IF: invalid interface + */ +esp_err_t esp_wifi_get_mac(wifi_interface_t ifx, uint8_t mac[6]); + +/** + * @brief The RX callback function in the promiscuous mode. + * Each time a packet is received, the callback function will be called. + * + * @param buf Data received. Type of data in buffer (wifi_promiscuous_pkt_t or wifi_pkt_rx_ctrl_t) indicated by 'type' parameter. + * @param type promiscuous packet type. + * + */ +typedef void (* wifi_promiscuous_cb_t)(void *buf, wifi_promiscuous_pkt_type_t type); + +/** + * @brief Register the RX callback function in the promiscuous mode. + * + * Each time a packet is received, the registered callback function will be called. + * + * @param cb callback + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_promiscuous_rx_cb(wifi_promiscuous_cb_t cb); + +/** + * @brief Enable the promiscuous mode. + * + * @param en false - disable, true - enable + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_promiscuous(bool en); + +/** + * @brief Get the promiscuous mode. + * + * @param[out] en store the current status of promiscuous mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_promiscuous(bool *en); + +/** + * @brief Enable the promiscuous mode packet type filter. + * + * @note The default filter is to filter all packets except WIFI_PKT_MISC + * + * @param filter the packet type filtered in promiscuous mode. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_promiscuous_filter(const wifi_promiscuous_filter_t *filter); + +/** + * @brief Get the promiscuous filter. + * + * @param[out] filter store the current status of promiscuous filter + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_get_promiscuous_filter(wifi_promiscuous_filter_t *filter); + +/** + * @brief Enable subtype filter of the control packet in promiscuous mode. + * + * @note The default filter is to filter none control packet. + * + * @param filter the subtype of the control packet filtered in promiscuous mode. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_promiscuous_ctrl_filter(const wifi_promiscuous_filter_t *filter); + +/** + * @brief Get the subtype filter of the control packet in promiscuous mode. + * + * @param[out] filter store the current status of subtype filter of the control packet in promiscuous mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_get_promiscuous_ctrl_filter(wifi_promiscuous_filter_t *filter); + +/** + * @brief Set the configuration of the ESP32 STA or AP + * + * @attention 1. This API can be called only when specified interface is enabled, otherwise, API fail + * @attention 2. For station configuration, bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP. + * @attention 3. ESP32 is limited to only one channel, so when in the soft-AP+station mode, the soft-AP will adjust its channel automatically to be the same as + * the channel of the ESP32 station. + * + * @param interface interface + * @param conf station or soft-AP configuration + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_MODE: invalid mode + * - ESP_ERR_WIFI_PASSWORD: invalid password + * - ESP_ERR_WIFI_NVS: WiFi internal NVS error + * - others: refer to the erro code in esp_err.h + */ +esp_err_t esp_wifi_set_config(wifi_interface_t interface, wifi_config_t *conf); + +/** + * @brief Get configuration of specified interface + * + * @param interface interface + * @param[out] conf station or soft-AP configuration + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_IF: invalid interface + */ +esp_err_t esp_wifi_get_config(wifi_interface_t interface, wifi_config_t *conf); + +/** + * @brief Get STAs associated with soft-AP + * + * @attention SSC only API + * + * @param[out] sta station list + * ap can get the connected sta's phy mode info through the struct member + * phy_11b,phy_11g,phy_11n,phy_lr in the wifi_sta_info_t struct. + * For example, phy_11b = 1 imply that sta support 802.11b mode + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_WIFI_MODE: WiFi mode is wrong + * - ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid + */ +esp_err_t esp_wifi_ap_get_sta_list(wifi_sta_list_t *sta); + +/** + * @brief Get AID of STA connected with soft-AP + * + * @param mac STA's mac address + * @param[out] aid Store the AID corresponding to STA mac + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + * - ESP_ERR_NOT_FOUND: Requested resource not found + * - ESP_ERR_WIFI_MODE: WiFi mode is wrong + * - ESP_ERR_WIFI_CONN: WiFi internal error, the station/soft-AP control block is invalid + */ +esp_err_t esp_wifi_ap_get_sta_aid(const uint8_t mac[6], uint16_t *aid); + +/** + * @brief Set the WiFi API configuration storage type + * + * @attention 1. The default value is WIFI_STORAGE_FLASH + * + * @param storage : storage type + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_set_storage(wifi_storage_t storage); + +/** + * @brief Function signature for received Vendor-Specific Information Element callback. + * @param ctx Context argument, as passed to esp_wifi_set_vendor_ie_cb() when registering callback. + * @param type Information element type, based on frame type received. + * @param sa Source 802.11 address. + * @param vnd_ie Pointer to the vendor specific element data received. + * @param rssi Received signal strength indication. + */ +typedef void (*esp_vendor_ie_cb_t) (void *ctx, wifi_vendor_ie_type_t type, const uint8_t sa[6], const vendor_ie_data_t *vnd_ie, int rssi); + +/** + * @brief Set 802.11 Vendor-Specific Information Element + * + * @param enable If true, specified IE is enabled. If false, specified IE is removed. + * @param type Information Element type. Determines the frame type to associate with the IE. + * @param idx Index to set or clear. Each IE type can be associated with up to two elements (indices 0 & 1). + * @param vnd_ie Pointer to vendor specific element data. First 6 bytes should be a header with fields matching vendor_ie_data_t. + * If enable is false, this argument is ignored and can be NULL. Data does not need to remain valid after the function returns. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init() + * - ESP_ERR_INVALID_ARG: Invalid argument, including if first byte of vnd_ie is not WIFI_VENDOR_IE_ELEMENT_ID (0xDD) + * or second byte is an invalid length. + * - ESP_ERR_NO_MEM: Out of memory + */ +esp_err_t esp_wifi_set_vendor_ie(bool enable, wifi_vendor_ie_type_t type, wifi_vendor_ie_id_t idx, const void *vnd_ie); + +/** + * @brief Register Vendor-Specific Information Element monitoring callback. + * + * @param cb Callback function + * @param ctx Context argument, passed to callback function. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_vendor_ie_cb(esp_vendor_ie_cb_t cb, void *ctx); + +/** + * @brief Set maximum transmitting power after WiFi start. + * + * @attention 1. Maximum power before wifi startup is limited by PHY init data bin. + * @attention 2. The value set by this API will be mapped to the max_tx_power of the structure wifi_country_t variable. + * @attention 3. Mapping Table {Power, max_tx_power} = {{8, 2}, {20, 5}, {28, 7}, {34, 8}, {44, 11}, + * {52, 13}, {56, 14}, {60, 15}, {66, 16}, {72, 18}, {80, 20}}. + * @attention 4. Param power unit is 0.25dBm, range is [8, 84] corresponding to 2dBm - 20dBm. + * @attention 5. Relationship between set value and actual value. As follows: {set value range, actual value} = {{[8, 19],8}, {[20, 27],20}, {[28, 33],28}, {[34, 43],34}, {[44, 51],44}, {[52, 55],52}, {[56, 59],56}, {[60, 65],60}, {[66, 71],66}, {[72, 79],72}, {[80, 84],80}}. + * + * @param power Maximum WiFi transmitting power. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start + * - ESP_ERR_WIFI_ARG: invalid argument, e.g. parameter is out of range + */ +esp_err_t esp_wifi_set_max_tx_power(int8_t power); + +/** + * @brief Get maximum transmiting power after WiFi start + * + * @param power Maximum WiFi transmitting power, unit is 0.25dBm. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_get_max_tx_power(int8_t *power); + +/** + * @brief Set mask to enable or disable some WiFi events + * + * @attention 1. Mask can be created by logical OR of various WIFI_EVENT_MASK_ constants. + * Events which have corresponding bit set in the mask will not be delivered to the system event handler. + * @attention 2. Default WiFi event mask is WIFI_EVENT_MASK_AP_PROBEREQRECVED. + * @attention 3. There may be lots of stations sending probe request data around. + * Don't unmask this event unless you need to receive probe request data. + * + * @param mask WiFi event mask. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ +esp_err_t esp_wifi_set_event_mask(uint32_t mask); + +/** + * @brief Get mask of WiFi events + * + * @param mask WiFi event mask. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_get_event_mask(uint32_t *mask); + +/** + * @brief Send raw ieee80211 data + * + * @attention Currently only support for sending beacon/probe request/probe response/action and non-QoS + * data frame + * + * @param ifx interface if the Wi-Fi mode is Station, the ifx should be WIFI_IF_STA. If the Wi-Fi + * mode is SoftAP, the ifx should be WIFI_IF_AP. If the Wi-Fi mode is Station+SoftAP, the + * ifx should be WIFI_IF_STA or WIFI_IF_AP. If the ifx is wrong, the API returns ESP_ERR_WIFI_IF. + * @param buffer raw ieee80211 buffer + * @param len the length of raw buffer, the len must be <= 1500 Bytes and >= 24 Bytes + * @param en_sys_seq indicate whether use the internal sequence number. If en_sys_seq is false, the + * sequence in raw buffer is unchanged, otherwise it will be overwritten by WiFi driver with + * the system sequence number. + * Generally, if esp_wifi_80211_tx is called before the Wi-Fi connection has been set up, both + * en_sys_seq==true and en_sys_seq==false are fine. However, if the API is called after the Wi-Fi + * connection has been set up, en_sys_seq must be true, otherwise ESP_ERR_WIFI_ARG is returned. + * + * @return + * - ESP_OK: success + * - ESP_ERR_WIFI_IF: Invalid interface + * - ESP_ERR_INVALID_ARG: Invalid parameter + * - ESP_ERR_WIFI_NO_MEM: out of memory + */ + +esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq); + +/** + * @brief The RX callback function of Channel State Information(CSI) data. + * + * Each time a CSI data is received, the callback function will be called. + * + * @param ctx context argument, passed to esp_wifi_set_csi_rx_cb() when registering callback function. + * @param data CSI data received. The memory that it points to will be deallocated after callback function returns. + * + */ +typedef void (* wifi_csi_cb_t)(void *ctx, wifi_csi_info_t *data); + + +/** + * @brief Register the RX callback function of CSI data. + * + * Each time a CSI data is received, the callback function will be called. + * + * @param cb callback + * @param ctx context argument, passed to callback function + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + */ + +esp_err_t esp_wifi_set_csi_rx_cb(wifi_csi_cb_t cb, void *ctx); + +/** + * @brief Set CSI data configuration + * + * @param config configuration + * + * return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_set_csi_config(const wifi_csi_config_t *config); + +/** + * @brief Enable or disable CSI + * + * @param en true - enable, false - disable + * + * return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_START: WiFi is not started by esp_wifi_start or promiscuous mode is not enabled + * - ESP_ERR_INVALID_ARG: invalid argument + */ +esp_err_t esp_wifi_set_csi(bool en); + +/** + * @brief Set antenna GPIO configuration + * + * @param config Antenna GPIO configuration. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: Invalid argument, e.g. parameter is NULL, invalid GPIO number etc + */ +esp_err_t esp_wifi_set_ant_gpio(const wifi_ant_gpio_config_t *config); + +/** + * @brief Get current antenna GPIO configuration + * + * @param config Antenna GPIO configuration. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument, e.g. parameter is NULL + */ +esp_err_t esp_wifi_get_ant_gpio(wifi_ant_gpio_config_t *config); + + +/** + * @brief Set antenna configuration + * + * @param config Antenna configuration. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: Invalid argument, e.g. parameter is NULL, invalid antenna mode or invalid GPIO number + */ +esp_err_t esp_wifi_set_ant(const wifi_ant_config_t *config); + +/** + * @brief Get current antenna configuration + * + * @param config Antenna configuration. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument, e.g. parameter is NULL + */ +esp_err_t esp_wifi_get_ant(wifi_ant_config_t *config); + +/** + * @brief Get the TSF time + * In Station mode or SoftAP+Station mode if station is not connected or station doesn't receive at least + * one beacon after connected, will return 0 + * + * @attention Enabling power save may cause the return value inaccurate, except WiFi modem sleep + * + * @param interface The interface whose tsf_time is to be retrieved. + * + * @return 0 or the TSF time + */ +int64_t esp_wifi_get_tsf_time(wifi_interface_t interface); + +/** + * @brief Set the inactive time of the ESP32 STA or AP + * + * @attention 1. For Station, If the station does not receive a beacon frame from the connected SoftAP during the inactive time, + * disconnect from SoftAP. Default 6s. + * @attention 2. For SoftAP, If the softAP doesn't receive any data from the connected STA during inactive time, + * the softAP will force deauth the STA. Default is 300s. + * @attention 3. The inactive time configuration is not stored into flash + * + * @param ifx interface to be configured. + * @param sec Inactive time. Unit seconds. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_NOT_STARTED: WiFi is not started by esp_wifi_start + * - ESP_ERR_WIFI_ARG: invalid argument, For Station, if sec is less than 3. For SoftAP, if sec is less than 10. + */ +esp_err_t esp_wifi_set_inactive_time(wifi_interface_t ifx, uint16_t sec); + +/** + * @brief Get inactive time of specified interface + * + * @param ifx Interface to be configured. + * @param sec Inactive time. Unit seconds. + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_get_inactive_time(wifi_interface_t ifx, uint16_t *sec); + +/** + * @brief Dump WiFi statistics + * + * @param modules statistic modules to be dumped + * + * @return + * - ESP_OK: succeed + * - others: failed + */ +esp_err_t esp_wifi_statis_dump(uint32_t modules); + +/** + * @brief Set RSSI threshold below which APP will get an event + * + * @attention This API needs to be called every time after WIFI_EVENT_STA_BSS_RSSI_LOW event is received. + * + * @param rssi threshold value in dbm between -100 to 0 + * + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by esp_wifi_init + * - ESP_ERR_WIFI_ARG: invalid argument + */ +esp_err_t esp_wifi_set_rssi_threshold(int32_t rssi); + +/** + * @brief Start an FTM Initiator session by sending FTM request + * If successful, event WIFI_EVENT_FTM_REPORT is generated with the result of the FTM procedure + * + * @attention Use this API only in Station mode + * + * @param cfg FTM Initiator session configuration + * + * @return + * - ESP_OK: succeed + * - others: failed + */ +esp_err_t esp_wifi_ftm_initiate_session(wifi_ftm_initiator_cfg_t *cfg); + +/** + * @brief Enable or disable 11b rate of specified interface + * + * @attention 1. This API should be called after esp_wifi_init() and before esp_wifi_start(). + * @attention 2. Only when really need to disable 11b rate call this API otherwise don't call this. + * + * @param ifx Interface to be configured. + * @param disable true means disable 11b rate while false means enable 11b rate. + * + * @return + * - ESP_OK: succeed + * - others: failed + */ +esp_err_t esp_wifi_config_11b_rate(wifi_interface_t ifx, bool disable); + +/** + * @brief Config ESPNOW rate of specified interface + * + * @attention 1. This API should be called after esp_wifi_init() and before esp_wifi_start(). + * + * @param ifx Interface to be configured. + * @param rate Only support 1M, 6M and MCS0_LGI + * + * @return + * - ESP_OK: succeed + * - others: failed + */ +esp_err_t esp_wifi_config_espnow_rate(wifi_interface_t ifx, wifi_phy_rate_t rate); + +/** + * @brief Set interval for station to wake up periodically at disconnected. + * + * @attention 1. Only when ESP_WIFI_STA_DISCONNECTED_PM_ENABLE is enabled, this configuration could work + * @attention 2. This configuration only work for station mode and disconnected status + * @attention 3. This configuration would influence nothing until some module configure wake_window + * @attention 4. A sensible interval which is not too small is recommended (e.g. 100ms) + * + * @param interval how much micriosecond would the chip wake up, from 1 to 65535. + */ +esp_err_t esp_wifi_set_connectionless_wake_interval(uint16_t interval); + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_WIFI_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_crypto_types.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_crypto_types.h new file mode 100644 index 00000000..f55d1484 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_crypto_types.h @@ -0,0 +1,408 @@ +// Hardware crypto support Copyright 2017 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. + + +#ifndef __ESP_WIFI_CRYPTO_TYPES_H__ +#define __ESP_WIFI_CRYPTO_TYPES_H__ + +/* This is an internal API header for configuring the implementation used for WiFi cryptographic + operations. + + During normal operation, you don't need to use any of these types or functions in this header. + See esp_wifi.h & esp_wifi_types.h instead. +*/ + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_WIFI_CRYPTO_VERSION 0x00000001 + +/* + * Enumeration for hash operations. + * When WPA2 is connecting, this enum is used to + * request a hash algorithm via crypto_hash_xxx functions. + */ +typedef enum { + ESP_CRYPTO_HASH_ALG_MD5, ESP_CRYPTO_HASH_ALG_SHA1, + ESP_CRYPTO_HASH_ALG_HMAC_MD5, ESP_CRYPTO_HASH_ALG_HMAC_SHA1, + ESP_CRYPTO_HASH_ALG_SHA256, ESP_CRYPTO_HASH_ALG_HMAC_SHA256 +}esp_crypto_hash_alg_t; + +/* + * Enumeration for block cipher operations. + * When WPA2 is connecting, this enum is used to request a block + * cipher algorithm via crypto_cipher_xxx functions. + */ +typedef enum { + ESP_CRYPTO_CIPHER_NULL, ESP_CRYPTO_CIPHER_ALG_AES, ESP_CRYPTO_CIPHER_ALG_3DES, + ESP_CRYPTO_CIPHER_ALG_DES, ESP_CRYPTO_CIPHER_ALG_RC2, ESP_CRYPTO_CIPHER_ALG_RC4 +} esp_crypto_cipher_alg_t; + +/* + * This structure is about the algorithm when do crypto_hash operation, for detail, + * please reference to the structure crypto_hash. + */ +typedef struct crypto_hash esp_crypto_hash_t; + +/* + * This structure is about the algorithm when do crypto_cipher operation, for detail, + * please reference to the structure crypto_cipher. + */ +typedef struct crypto_cipher esp_crypto_cipher_t; + +/** + * @brief The AES callback function when do WPS connect. + * + * @param key Encryption key. + * @param iv Encryption IV for CBC mode (16 bytes). + * @param data Data to encrypt in-place. + * @param data_len Length of data in bytes (must be divisible by 16) + */ +typedef int (*esp_aes_128_encrypt_t)(const unsigned char *key, const unsigned char *iv, unsigned char *data, int data_len); + +/** + * @brief The AES callback function when do WPS connect. + * + * @param key Decryption key. + * @param iv Decryption IV for CBC mode (16 bytes). + * @param data Data to decrypt in-place. + * @param data_len Length of data in bytes (must be divisible by 16) + * + */ +typedef int (*esp_aes_128_decrypt_t)(const unsigned char *key, const unsigned char *iv, unsigned char *data, int data_len); + +/** + * @brief The AES callback function when do STA connect. + * + * @param kek 16-octet Key encryption key (KEK). + * @param n Length of the plaintext key in 64-bit units; + * @param plain Plaintext key to be wrapped, n * 64 bits + * @param cipher Wrapped key, (n + 1) * 64 bits + * + */ +typedef int (*esp_aes_wrap_t)(const unsigned char *kek, int n, const unsigned char *plain, unsigned char *cipher); + +/** + * @brief The AES callback function when do STA connect. + * + * @param kek 16-octet Key decryption key (KEK). + * @param n Length of the plaintext key in 64-bit units; + * @param cipher Wrapped key to be unwrapped, (n + 1) * 64 bits + * @param plain Plaintext key, n * 64 bits + * + */ +typedef int (*esp_aes_unwrap_t)(const unsigned char *kek, int n, const unsigned char *cipher, unsigned char *plain); + +/** + * @brief The SHA256 callback function when do WPS connect. + * + * @param key Key for HMAC operations. + * @param key_len Length of the key in bytes. + * @param num_elem Number of elements in the data vector. + * @param addr Pointers to the data areas. + * @param len Lengths of the data blocks. + * @param mac Buffer for the hash (32 bytes). + * + */ +typedef int (*esp_hmac_sha256_vector_t)(const unsigned char *key, int key_len, int num_elem, + const unsigned char *addr[], const int *len, unsigned char *mac); + +/** + * @brief The AES callback function when do STA connect. + * + * @param key Key for PRF. + * @param key_len Length of the key in bytes. + * @param label A unique label for each purpose of the PRF. + * @param data Extra data to bind into the key. + * @param data_len Length of the data. + * @param buf Buffer for the generated pseudo-random key. + * @param buf_len Number of bytes of key to generate. + * + */ +typedef int (*esp_sha256_prf_t)(const unsigned char *key, int key_len, const char *label, + const unsigned char *data, int data_len, unsigned char *buf, int buf_len); + +/** + * @brief HMAC-MD5 over data buffer (RFC 2104)' + * + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @data: Pointers to the data area + * @data_len: Length of the data area + * @mac: Buffer for the hash (16 bytes) + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_hmac_md5_t)(const unsigned char *key, unsigned int key_len, const unsigned char *data, + unsigned int data_len, unsigned char *mac); + +/** + * @brief HMAC-MD5 over data vector (RFC 2104) + * + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @num_elem: Number of elements in the data vector + * @addr: Pointers to the data areas + * @len: Lengths of the data blocks + * @mac: Buffer for the hash (16 bytes) + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_hmac_md5_vector_t)(const unsigned char *key, unsigned int key_len, unsigned int num_elem, + const unsigned char *addr[], const unsigned int *len, unsigned char *mac); + +/** + * @brief HMAC-SHA1 over data buffer (RFC 2104) + * + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @data: Pointers to the data area + * @data_len: Length of the data area + * @mac: Buffer for the hash (20 bytes) + * Returns: 0 on success, -1 of failure + */ +typedef int (*esp_hmac_sha1_t)(const unsigned char *key, unsigned int key_len, const unsigned char *data, + unsigned int data_len, unsigned char *mac); + +/** + * @brief HMAC-SHA1 over data vector (RFC 2104) + * + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @num_elem: Number of elements in the data vector + * @addr: Pointers to the data areas + * @len: Lengths of the data blocks + * @mac: Buffer for the hash (20 bytes) + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_hmac_sha1_vector_t)(const unsigned char *key, unsigned int key_len, unsigned int num_elem, + const unsigned char *addr[], const unsigned int *len, unsigned char *mac); + +/** + * @brief SHA1-based Pseudo-Random Function (PRF) (IEEE 802.11i, 8.5.1.1) + * + * @key: Key for PRF + * @key_len: Length of the key in bytes + * @label: A unique label for each purpose of the PRF + * @data: Extra data to bind into the key + * @data_len: Length of the data + * @buf: Buffer for the generated pseudo-random key + * @buf_len: Number of bytes of key to generate + * Returns: 0 on success, -1 of failure + * + * This function is used to derive new, cryptographically separate keys from a + * given key (e.g., PMK in IEEE 802.11i). + */ +typedef int (*esp_sha1_prf_t)(const unsigned char *key, unsigned int key_len, const char *label, + const unsigned char *data, unsigned int data_len, unsigned char *buf, unsigned int buf_len); + +/** + * @brief SHA-1 hash for data vector + * + * @num_elem: Number of elements in the data vector + * @addr: Pointers to the data areas + * @len: Lengths of the data blocks + * @mac: Buffer for the hash + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_sha1_vector_t)(unsigned int num_elem, const unsigned char *addr[], const unsigned int *len, + unsigned char *mac); + +/** + * @brief SHA1-based key derivation function (PBKDF2) for IEEE 802.11i + * + * @passphrase: ASCII passphrase + * @ssid: SSID + * @ssid_len: SSID length in bytes + * @iterations: Number of iterations to run + * @buf: Buffer for the generated key + * @buflen: Length of the buffer in bytes + * Returns: 0 on success, -1 of failure + * + * This function is used to derive PSK for WPA-PSK. For this protocol, + * iterations is set to 4096 and buflen to 32. This function is described in + * IEEE Std 802.11-2004, Clause H.4. The main construction is from PKCS#5 v2.0. + */ +typedef int (*esp_pbkdf2_sha1_t)(const char *passphrase, const char *ssid, unsigned int ssid_len, + int iterations, unsigned char *buf, unsigned int buflen); + +/** + * @brief XOR RC4 stream to given data with skip-stream-start + * + * @key: RC4 key + * @keylen: RC4 key length + * @skip: number of bytes to skip from the beginning of the RC4 stream + * @data: data to be XOR'ed with RC4 stream + * @data_len: buf length + * Returns: 0 on success, -1 on failure + * + * Generate RC4 pseudo random stream for the given key, skip beginning of the + * stream, and XOR the end result with the data buffer to perform RC4 + * encryption/decryption. + */ +typedef int (*esp_rc4_skip_t)(const unsigned char *key, unsigned int keylen, unsigned int skip, + unsigned char *data, unsigned int data_len); + +/** + * @brief MD5 hash for data vector + * + * @num_elem: Number of elements in the data vector + * @addr: Pointers to the data areas + * @len: Lengths of the data blocks + * @mac: Buffer for the hash + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_md5_vector_t)(unsigned int num_elem, const unsigned char *addr[], const unsigned int *len, + unsigned char *mac); + +/** + * @brief Encrypt one AES block + * + * @ctx: Context pointer from aes_encrypt_init() + * @plain: Plaintext data to be encrypted (16 bytes) + * @crypt: Buffer for the encrypted data (16 bytes) + */ +typedef void (*esp_aes_encrypt_t)(void *ctx, const unsigned char *plain, unsigned char *crypt); + +/** + * @brief Initialize AES for encryption + * + * @key: Encryption key + * @len: Key length in bytes (usually 16, i.e., 128 bits) + * Returns: Pointer to context data or %NULL on failure + */ +typedef void * (*esp_aes_encrypt_init_t)(const unsigned char *key, unsigned int len); + +/** + * @brief Deinitialize AES encryption + * + * @ctx: Context pointer from aes_encrypt_init() + */ +typedef void (*esp_aes_encrypt_deinit_t)(void *ctx); + +/** + * @brief Decrypt one AES block + * + * @ctx: Context pointer from aes_encrypt_init() + * @crypt: Encrypted data (16 bytes) + * @plain: Buffer for the decrypted data (16 bytes) + */ +typedef void (*esp_aes_decrypt_t)(void *ctx, const unsigned char *crypt, unsigned char *plain); + +/** + * @brief Initialize AES for decryption + * + * @key: Decryption key + * @len: Key length in bytes (usually 16, i.e., 128 bits) + * Returns: Pointer to context data or %NULL on failure + */ +typedef void * (*esp_aes_decrypt_init_t)(const unsigned char *key, unsigned int len); + +/** + * @brief Deinitialize AES decryption + * + * @ctx: Context pointer from aes_encrypt_init() + */ +typedef void (*esp_aes_decrypt_deinit_t)(void *ctx); + +/** + * @brief One-Key CBC MAC (OMAC1) hash with AES-128 for MIC computation + * + * @key: 128-bit key for the hash operation + * @data: Data buffer for which a MIC is computed + * @data_len: Length of data buffer in bytes + * @mic: Buffer for MIC (128 bits, i.e., 16 bytes) + * Returns: 0 on success, -1 on failure + */ +typedef int (*esp_omac1_aes_128_t)(const uint8_t *key, const uint8_t *data, size_t data_len, + uint8_t *mic); + +/** + * @brief Decrypt data using CCMP (Counter Mode CBC-MAC Protocol OR + * Counter Mode Cipher Block Chaining Message Authentication + * Code Protocol) which is used in IEEE 802.11i RSN standard. + * @tk: 128-bit Temporal Key for obtained during 4-way handshake + * @hdr: Pointer to IEEE802.11 frame headeri needed for AAD + * @data: Pointer to encrypted data buffer + * @data_len: Encrypted data length in bytes + * @decrypted_len: Length of decrypted data + * @espnow_pkt: Indicates if it's an ESPNOW packet + * Returns: Pointer to decrypted data on success, NULL on failure + */ +typedef uint8_t * (*esp_ccmp_decrypt_t)(const uint8_t *tk, const uint8_t *ieee80211_hdr, + const uint8_t *data, size_t data_len, + size_t *decrypted_len, bool espnow_pkt); + +/** + * @brief Encrypt data using CCMP (Counter Mode CBC-MAC Protocol OR + * Counter Mode Cipher Block Chaining Message Authentication + * Code Protocol) which is used in IEEE 802.11i RSN standard. + * @tk: 128-bit Temporal Key for obtained during 4-way handshake + * @frame: Pointer to IEEE802.11 frame including header + * @len: Length of the frame including header + * @hdrlen: Length of the header + * @pn: Packet Number counter + * @keyid: Key ID to be mentioned in CCMP Vector + * @encrypted_len: Length of the encrypted frame including header + */ +typedef uint8_t * (*esp_ccmp_encrypt_t)(const uint8_t *tk, uint8_t *frame, size_t len, size_t hdrlen, + uint8_t *pn, int keyid, size_t *encrypted_len); + +/** + * @brief The crypto callback function structure used when do station security connect. + * The structure can be set as software crypto or the crypto optimized by ESP32 + * hardware. + */ +typedef struct { + uint32_t size; + uint32_t version; + esp_aes_wrap_t aes_wrap; /**< station connect function used when send EAPOL frame */ + esp_aes_unwrap_t aes_unwrap; /**< station connect function used when decrypt key data */ + esp_hmac_sha256_vector_t hmac_sha256_vector; /**< station connect function used when check MIC */ + esp_sha256_prf_t sha256_prf; /**< station connect function used when check MIC */ + esp_hmac_md5_t hmac_md5; + esp_hmac_md5_vector_t hamc_md5_vector; + esp_hmac_sha1_t hmac_sha1; + esp_hmac_sha1_vector_t hmac_sha1_vector; + esp_sha1_prf_t sha1_prf; + esp_sha1_vector_t sha1_vector; + esp_pbkdf2_sha1_t pbkdf2_sha1; + esp_rc4_skip_t rc4_skip; + esp_md5_vector_t md5_vector; + esp_aes_encrypt_t aes_encrypt; + esp_aes_encrypt_init_t aes_encrypt_init; + esp_aes_encrypt_deinit_t aes_encrypt_deinit; + esp_aes_decrypt_t aes_decrypt; + esp_aes_decrypt_init_t aes_decrypt_init; + esp_aes_decrypt_deinit_t aes_decrypt_deinit; + esp_aes_128_encrypt_t aes_128_encrypt; + esp_aes_128_decrypt_t aes_128_decrypt; + esp_omac1_aes_128_t omac1_aes_128; + esp_ccmp_decrypt_t ccmp_decrypt; + esp_ccmp_encrypt_t ccmp_encrypt; +}wpa_crypto_funcs_t; + +/** + * @brief The crypto callback function structure used in mesh vendor IE encryption. The + * structure can be set as software crypto or the crypto optimized by ESP32 + * hardware. + */ +typedef struct{ + esp_aes_128_encrypt_t aes_128_encrypt; /**< function used in mesh vendor IE encryption */ + esp_aes_128_decrypt_t aes_128_decrypt; /**< function used in mesh vendor IE decryption */ +} mesh_crypto_funcs_t; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_default.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_default.h new file mode 100644 index 00000000..4ce7f8b2 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_default.h @@ -0,0 +1,118 @@ +// Copyright 2019 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. + +#ifndef _ESP_WIFI_DEFAULT_H +#define _ESP_WIFI_DEFAULT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Attaches wifi station interface to supplied netif + * + * @param esp_netif instance to attach the wifi station to + * + * @return + * - ESP_OK on success + * - ESP_FAIL if attach failed + */ +esp_err_t esp_netif_attach_wifi_station(esp_netif_t *esp_netif); + +/** + * @brief Attaches wifi soft AP interface to supplied netif + * + * @param esp_netif instance to attach the wifi AP to + * + * @return + * - ESP_OK on success + * - ESP_FAIL if attach failed + */ +esp_err_t esp_netif_attach_wifi_ap(esp_netif_t *esp_netif); + +/** + * @brief Sets default wifi event handlers for STA interface + * + * @return + * - ESP_OK on success, error returned from esp_event_handler_register if failed + */ +esp_err_t esp_wifi_set_default_wifi_sta_handlers(void); + +/** + * @brief Sets default wifi event handlers for STA interface + * + * @return + * - ESP_OK on success, error returned from esp_event_handler_register if failed + */ +esp_err_t esp_wifi_set_default_wifi_ap_handlers(void); + +/** + * @brief Clears default wifi event handlers for supplied network interface + * + * @param esp_netif instance of corresponding if object + * + * @return + * - ESP_OK on success, error returned from esp_event_handler_register if failed + */ +esp_err_t esp_wifi_clear_default_wifi_driver_and_handlers(void *esp_netif); + +/** + * @brief Creates default WIFI AP. In case of any init error this API aborts. + * + * @return pointer to esp-netif instance + */ +esp_netif_t* esp_netif_create_default_wifi_ap(void); + +/** + * @brief Creates default WIFI STA. In case of any init error this API aborts. + * + * @return pointer to esp-netif instance + */ +esp_netif_t* esp_netif_create_default_wifi_sta(void); + +/** + * @brief Creates esp_netif WiFi object based on the custom configuration. + * + * @attention This API DOES NOT register default handlers! + * + * @param[in] wifi_if type of wifi interface + * @param[in] esp_netif_config inherent esp-netif configuration pointer + * + * @return pointer to esp-netif instance + */ +esp_netif_t* esp_netif_create_wifi(wifi_interface_t wifi_if, esp_netif_inherent_config_t *esp_netif_config); + +/** + * @brief Creates default STA and AP network interfaces for esp-mesh. + * + * Both netifs are almost identical to the default station and softAP, but with + * DHCP client and server disabled. Please note that the DHCP client is typically + * enabled only if the device is promoted to a root node. + * + * Returns created interfaces which could be ignored setting parameters to NULL + * if an application code does not need to save the interface instances + * for further processing. + * + * @param[out] p_netif_sta pointer where the resultant STA interface is saved (if non NULL) + * @param[out] p_netif_ap pointer where the resultant AP interface is saved (if non NULL) + * + * @return ESP_OK on success + */ +esp_err_t esp_netif_create_default_wifi_mesh_netifs(esp_netif_t **p_netif_sta, esp_netif_t **p_netif_ap); + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_WIFI_DEFAULT_H diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_netif.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_netif.h new file mode 100644 index 00000000..2c2243b4 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_netif.h @@ -0,0 +1,91 @@ +// Copyright 2019 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. + +#ifndef _ESP_WIFI_NETIF_H +#define _ESP_WIFI_NETIF_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Number of WiFi interfaces used by wifi-netif abstraction + */ +#define MAX_WIFI_IFS (2) + +/** + * @brief Forward declaration of WiFi interface handle + */ +typedef struct wifi_netif_driver* wifi_netif_driver_t; + +/** + * @brief Creates wifi driver instance to be used with esp-netif + * + * @param wifi_if wifi interface type (station, softAP) + * + * @return + * - pointer to wifi interface handle on success + * - NULL otherwise + */ +wifi_netif_driver_t esp_wifi_create_if_driver(wifi_interface_t wifi_if); + +/** + * @brief Destroys wifi driver instance + * + * @param h pointer to wifi interface handle + * + */ +void esp_wifi_destroy_if_driver(wifi_netif_driver_t h); + +/** + * @brief Return mac of specified wifi driver instance + * + * @param[in] ifx pointer to wifi interface handle + * @param[out] mac output mac address + * + * @return ESP_OK on success + * + */ +esp_err_t esp_wifi_get_if_mac(wifi_netif_driver_t ifx, uint8_t mac[6]); + +/** + * @brief Return true if the supplied interface instance is ready after start. + * Typically used when registering on receive callback, which ought to be + * installed as soon as AP started, but once STA gets connected. + * + * @param[in] ifx pointer to wifi interface handle + * + * @return + * - true if ready after intertace started (typically Access Point type) + * - false if ready once intertace connected (typically for Station type) + */ +bool esp_wifi_is_if_ready_when_started(wifi_netif_driver_t ifx); + +/** + * @brief Register interface receive callback function with argument + * + * @param[in] ifx pointer to wifi interface handle + * @param[in] fn funtion to be registered (typically esp_netif_receive) + * @param[in] arg argument to be supplied to registered function (typically esp_netif ptr) + * + * @return ESP_OK on success + * + */ +esp_err_t esp_wifi_register_if_rxcb(wifi_netif_driver_t ifx, esp_netif_receive_t fn, void * arg); + +#ifdef __cplusplus +} +#endif + +#endif //_ESP_WIFI_NETIF_H diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_types.h b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_types.h new file mode 100644 index 00000000..f159857c --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/esp_wifi_types.h @@ -0,0 +1,748 @@ +// Copyright 2015-2016 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. + + +#ifndef __ESP_WIFI_TYPES_H__ +#define __ESP_WIFI_TYPES_H__ + +#include "esp_private/esp_wifi_types_private.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + WIFI_MODE_NULL = 0, /**< null mode */ + WIFI_MODE_STA, /**< WiFi station mode */ + WIFI_MODE_AP, /**< WiFi soft-AP mode */ + WIFI_MODE_APSTA, /**< WiFi station + soft-AP mode */ + WIFI_MODE_MAX +} wifi_mode_t; + +typedef enum { + WIFI_IF_STA = ESP_IF_WIFI_STA, + WIFI_IF_AP = ESP_IF_WIFI_AP, +} wifi_interface_t; + +#define WIFI_OFFCHAN_TX_REQ 1 +#define WIFI_OFFCHAN_TX_CANCEL 0 + +#define WIFI_ROC_REQ 1 +#define WIFI_ROC_CANCEL 0 + +typedef enum { + WIFI_COUNTRY_POLICY_AUTO, /**< Country policy is auto, use the country info of AP to which the station is connected */ + WIFI_COUNTRY_POLICY_MANUAL, /**< Country policy is manual, always use the configured country info */ +} wifi_country_policy_t; + +/** @brief Structure describing WiFi country-based regional restrictions. */ +typedef struct { + char cc[3]; /**< country code string */ + uint8_t schan; /**< start channel */ + uint8_t nchan; /**< total channel number */ + int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ + wifi_country_policy_t policy; /**< country policy */ +} wifi_country_t; + +typedef enum { + WIFI_AUTH_OPEN = 0, /**< authenticate mode : open */ + WIFI_AUTH_WEP, /**< authenticate mode : WEP */ + WIFI_AUTH_WPA_PSK, /**< authenticate mode : WPA_PSK */ + WIFI_AUTH_WPA2_PSK, /**< authenticate mode : WPA2_PSK */ + WIFI_AUTH_WPA_WPA2_PSK, /**< authenticate mode : WPA_WPA2_PSK */ + WIFI_AUTH_WPA2_ENTERPRISE, /**< authenticate mode : WPA2_ENTERPRISE */ + WIFI_AUTH_WPA3_PSK, /**< authenticate mode : WPA3_PSK */ + WIFI_AUTH_WPA2_WPA3_PSK, /**< authenticate mode : WPA2_WPA3_PSK */ + WIFI_AUTH_WAPI_PSK, /**< authenticate mode : WAPI_PSK */ + WIFI_AUTH_MAX +} wifi_auth_mode_t; + +typedef enum { + WIFI_REASON_UNSPECIFIED = 1, + WIFI_REASON_AUTH_EXPIRE = 2, + WIFI_REASON_AUTH_LEAVE = 3, + WIFI_REASON_ASSOC_EXPIRE = 4, + WIFI_REASON_ASSOC_TOOMANY = 5, + WIFI_REASON_NOT_AUTHED = 6, + WIFI_REASON_NOT_ASSOCED = 7, + WIFI_REASON_ASSOC_LEAVE = 8, + WIFI_REASON_ASSOC_NOT_AUTHED = 9, + WIFI_REASON_DISASSOC_PWRCAP_BAD = 10, + WIFI_REASON_DISASSOC_SUPCHAN_BAD = 11, + WIFI_REASON_IE_INVALID = 13, + WIFI_REASON_MIC_FAILURE = 14, + WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT = 15, + WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT = 16, + WIFI_REASON_IE_IN_4WAY_DIFFERS = 17, + WIFI_REASON_GROUP_CIPHER_INVALID = 18, + WIFI_REASON_PAIRWISE_CIPHER_INVALID = 19, + WIFI_REASON_AKMP_INVALID = 20, + WIFI_REASON_UNSUPP_RSN_IE_VERSION = 21, + WIFI_REASON_INVALID_RSN_IE_CAP = 22, + WIFI_REASON_802_1X_AUTH_FAILED = 23, + WIFI_REASON_CIPHER_SUITE_REJECTED = 24, + + WIFI_REASON_INVALID_PMKID = 53, + + WIFI_REASON_BEACON_TIMEOUT = 200, + WIFI_REASON_NO_AP_FOUND = 201, + WIFI_REASON_AUTH_FAIL = 202, + WIFI_REASON_ASSOC_FAIL = 203, + WIFI_REASON_HANDSHAKE_TIMEOUT = 204, + WIFI_REASON_CONNECTION_FAIL = 205, + WIFI_REASON_AP_TSF_RESET = 206, + WIFI_REASON_ROAMING = 207, +} wifi_err_reason_t; + +typedef enum { + WIFI_SECOND_CHAN_NONE = 0, /**< the channel width is HT20 */ + WIFI_SECOND_CHAN_ABOVE, /**< the channel width is HT40 and the secondary channel is above the primary channel */ + WIFI_SECOND_CHAN_BELOW, /**< the channel width is HT40 and the secondary channel is below the primary channel */ +} wifi_second_chan_t; + +typedef enum { + WIFI_SCAN_TYPE_ACTIVE = 0, /**< active scan */ + WIFI_SCAN_TYPE_PASSIVE, /**< passive scan */ +} wifi_scan_type_t; + +/** @brief Range of active scan times per channel */ +typedef struct { + uint32_t min; /**< minimum active scan time per channel, units: millisecond */ + uint32_t max; /**< maximum active scan time per channel, units: millisecond, values above 1500ms may + cause station to disconnect from AP and are not recommended. */ +} wifi_active_scan_time_t; + +/** @brief Aggregate of active & passive scan time per channel */ +typedef struct { + wifi_active_scan_time_t active; /**< active scan time per channel, units: millisecond. */ + uint32_t passive; /**< passive scan time per channel, units: millisecond, values above 1500ms may + cause station to disconnect from AP and are not recommended. */ +} wifi_scan_time_t; + +/** @brief Parameters for an SSID scan. */ +typedef struct { + uint8_t *ssid; /**< SSID of AP */ + uint8_t *bssid; /**< MAC address of AP */ + uint8_t channel; /**< channel, scan the specific channel */ + bool show_hidden; /**< enable to scan AP whose SSID is hidden */ + wifi_scan_type_t scan_type; /**< scan type, active or passive */ + wifi_scan_time_t scan_time; /**< scan time per channel */ +} wifi_scan_config_t; + +typedef enum { + WIFI_CIPHER_TYPE_NONE = 0, /**< the cipher type is none */ + WIFI_CIPHER_TYPE_WEP40, /**< the cipher type is WEP40 */ + WIFI_CIPHER_TYPE_WEP104, /**< the cipher type is WEP104 */ + WIFI_CIPHER_TYPE_TKIP, /**< the cipher type is TKIP */ + WIFI_CIPHER_TYPE_CCMP, /**< the cipher type is CCMP */ + WIFI_CIPHER_TYPE_TKIP_CCMP, /**< the cipher type is TKIP and CCMP */ + WIFI_CIPHER_TYPE_AES_CMAC128,/**< the cipher type is AES-CMAC-128 */ + WIFI_CIPHER_TYPE_SMS4, /**< the cipher type is SMS4 */ + WIFI_CIPHER_TYPE_UNKNOWN, /**< the cipher type is unknown */ +} wifi_cipher_type_t; + +/** + * @brief WiFi antenna + * + */ +typedef enum { + WIFI_ANT_ANT0, /**< WiFi antenna 0 */ + WIFI_ANT_ANT1, /**< WiFi antenna 1 */ + WIFI_ANT_MAX, /**< Invalid WiFi antenna */ +} wifi_ant_t; + +/** @brief Description of a WiFi AP */ +typedef struct { + uint8_t bssid[6]; /**< MAC address of AP */ + uint8_t ssid[33]; /**< SSID of AP */ + uint8_t primary; /**< channel of AP */ + wifi_second_chan_t second; /**< secondary channel of AP */ + int8_t rssi; /**< signal strength of AP */ + wifi_auth_mode_t authmode; /**< authmode of AP */ + wifi_cipher_type_t pairwise_cipher; /**< pairwise cipher of AP */ + wifi_cipher_type_t group_cipher; /**< group cipher of AP */ + wifi_ant_t ant; /**< antenna used to receive beacon from AP */ + uint32_t phy_11b:1; /**< bit: 0 flag to identify if 11b mode is enabled or not */ + uint32_t phy_11g:1; /**< bit: 1 flag to identify if 11g mode is enabled or not */ + uint32_t phy_11n:1; /**< bit: 2 flag to identify if 11n mode is enabled or not */ + uint32_t phy_lr:1; /**< bit: 3 flag to identify if low rate is enabled or not */ + uint32_t wps:1; /**< bit: 4 flag to identify if WPS is supported or not */ + uint32_t ftm_responder:1; /**< bit: 5 flag to identify if FTM is supported in responder mode */ + uint32_t ftm_initiator:1; /**< bit: 6 flag to identify if FTM is supported in initiator mode */ + uint32_t reserved:25; /**< bit: 7..31 reserved */ + wifi_country_t country; /**< country information of AP */ +} wifi_ap_record_t; + +typedef enum { + WIFI_FAST_SCAN = 0, /**< Do fast scan, scan will end after find SSID match AP */ + WIFI_ALL_CHANNEL_SCAN, /**< All channel scan, scan will end after scan all the channel */ +}wifi_scan_method_t; + +typedef enum { + WIFI_CONNECT_AP_BY_SIGNAL = 0, /**< Sort match AP in scan list by RSSI */ + WIFI_CONNECT_AP_BY_SECURITY, /**< Sort match AP in scan list by security mode */ +}wifi_sort_method_t; + +/** @brief Structure describing parameters for a WiFi fast scan */ +typedef struct { + int8_t rssi; /**< The minimum rssi to accept in the fast scan mode */ + wifi_auth_mode_t authmode; /**< The weakest authmode to accept in the fast scan mode */ +}wifi_scan_threshold_t; + +typedef enum { + WIFI_PS_NONE, /**< No power save */ + WIFI_PS_MIN_MODEM, /**< Minimum modem power saving. In this mode, station wakes up to receive beacon every DTIM period */ + WIFI_PS_MAX_MODEM, /**< Maximum modem power saving. In this mode, interval to receive beacons is determined by the listen_interval parameter in wifi_sta_config_t */ +} wifi_ps_type_t; + +#define WIFI_PROTOCOL_11B 1 +#define WIFI_PROTOCOL_11G 2 +#define WIFI_PROTOCOL_11N 4 +#define WIFI_PROTOCOL_LR 8 + +typedef enum { + WIFI_BW_HT20 = 1, /* Bandwidth is HT20 */ + WIFI_BW_HT40, /* Bandwidth is HT40 */ +} wifi_bandwidth_t; + +/** Configuration structure for Protected Management Frame */ +typedef struct { + bool capable; /**< Advertizes support for Protected Management Frame. Device will prefer to connect in PMF mode if other device also advertizes PMF capability. */ + bool required; /**< Advertizes that Protected Management Frame is required. Device will not associate to non-PMF capable devices. */ +} wifi_pmf_config_t; + +/** @brief Soft-AP configuration settings for the ESP32 */ +typedef struct { + uint8_t ssid[32]; /**< SSID of ESP32 soft-AP. If ssid_len field is 0, this must be a Null terminated string. Otherwise, length is set according to ssid_len. */ + uint8_t password[64]; /**< Password of ESP32 soft-AP. */ + uint8_t ssid_len; /**< Optional length of SSID field. */ + uint8_t channel; /**< Channel of ESP32 soft-AP */ + wifi_auth_mode_t authmode; /**< Auth mode of ESP32 soft-AP. Do not support AUTH_WEP in soft-AP mode */ + uint8_t ssid_hidden; /**< Broadcast SSID or not, default 0, broadcast the SSID */ + uint8_t max_connection; /**< Max number of stations allowed to connect in, default 4, max 10 */ + uint16_t beacon_interval; /**< Beacon interval which should be multiples of 100. Unit: TU(time unit, 1 TU = 1024 us). Range: 100 ~ 60000. Default value: 100 */ + wifi_cipher_type_t pairwise_cipher; /**< pairwise cipher of SoftAP, group cipher will be derived using this. cipher values are valid starting from WIFI_CIPHER_TYPE_TKIP, enum values before that will be considered as invalid and default cipher suites(TKIP+CCMP) will be used. Valid cipher suites in softAP mode are WIFI_CIPHER_TYPE_TKIP, WIFI_CIPHER_TYPE_CCMP and WIFI_CIPHER_TYPE_TKIP_CCMP. */ +} wifi_ap_config_t; + +/** @brief STA configuration settings for the ESP32 */ +typedef struct { + uint8_t ssid[32]; /**< SSID of target AP. */ + uint8_t password[64]; /**< Password of target AP. */ + wifi_scan_method_t scan_method; /**< do all channel scan or fast scan */ + bool bssid_set; /**< whether set MAC address of target AP or not. Generally, station_config.bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP.*/ + uint8_t bssid[6]; /**< MAC address of target AP*/ + uint8_t channel; /**< channel of target AP. Set to 1~13 to scan starting from the specified channel before connecting to AP. If the channel of AP is unknown, set it to 0.*/ + uint16_t listen_interval; /**< Listen interval for ESP32 station to receive beacon when WIFI_PS_MAX_MODEM is set. Units: AP beacon intervals. Defaults to 3 if set to 0. */ + wifi_sort_method_t sort_method; /**< sort the connect AP in the list by rssi or security mode */ + wifi_scan_threshold_t threshold; /**< When sort_method is set, only APs which have an auth mode that is more secure than the selected auth mode and a signal stronger than the minimum RSSI will be used. */ + wifi_pmf_config_t pmf_cfg; /**< Configuration for Protected Management Frame. Will be advertized in RSN Capabilities in RSN IE. */ + uint32_t rm_enabled:1; /**< Whether Radio Measurements are enabled for the connection */ + uint32_t btm_enabled:1; /**< Whether BSS Transition Management is enabled for the connection */ + uint32_t reserved:30; /**< Reserved for future feature set */ +} wifi_sta_config_t; + +/** @brief Configuration data for ESP32 AP or STA. + * + * The usage of this union (for ap or sta configuration) is determined by the accompanying + * interface argument passed to esp_wifi_set_config() or esp_wifi_get_config() + * + */ +typedef union { + wifi_ap_config_t ap; /**< configuration of AP */ + wifi_sta_config_t sta; /**< configuration of STA */ +} wifi_config_t; + +/** @brief Description of STA associated with AP */ +typedef struct { + uint8_t mac[6]; /**< mac address */ + int8_t rssi; /**< current average rssi of sta connected */ + uint32_t phy_11b:1; /**< bit: 0 flag to identify if 11b mode is enabled or not */ + uint32_t phy_11g:1; /**< bit: 1 flag to identify if 11g mode is enabled or not */ + uint32_t phy_11n:1; /**< bit: 2 flag to identify if 11n mode is enabled or not */ + uint32_t phy_lr:1; /**< bit: 3 flag to identify if low rate is enabled or not */ + uint32_t reserved:28; /**< bit: 4..31 reserved */ +} wifi_sta_info_t; + +#define ESP_WIFI_MAX_CONN_NUM (10) /**< max number of stations which can connect to ESP32 soft-AP */ + +/** @brief List of stations associated with the ESP32 Soft-AP */ +typedef struct { + wifi_sta_info_t sta[ESP_WIFI_MAX_CONN_NUM]; /**< station list */ + int num; /**< number of stations in the list (other entries are invalid) */ +} wifi_sta_list_t; + +typedef enum { + WIFI_STORAGE_FLASH, /**< all configuration will store in both memory and flash */ + WIFI_STORAGE_RAM, /**< all configuration will only store in the memory */ +} wifi_storage_t; + +/** + * @brief Vendor Information Element type + * + * Determines the frame type that the IE will be associated with. + */ +typedef enum { + WIFI_VND_IE_TYPE_BEACON, + WIFI_VND_IE_TYPE_PROBE_REQ, + WIFI_VND_IE_TYPE_PROBE_RESP, + WIFI_VND_IE_TYPE_ASSOC_REQ, + WIFI_VND_IE_TYPE_ASSOC_RESP, +} wifi_vendor_ie_type_t; + +/** + * @brief Vendor Information Element index + * + * Each IE type can have up to two associated vendor ID elements. + */ +typedef enum { + WIFI_VND_IE_ID_0, + WIFI_VND_IE_ID_1, +} wifi_vendor_ie_id_t; + +#define WIFI_VENDOR_IE_ELEMENT_ID 0xDD + +/** + * @brief Vendor Information Element header + * + * The first bytes of the Information Element will match this header. Payload follows. + */ +typedef struct { + uint8_t element_id; /**< Should be set to WIFI_VENDOR_IE_ELEMENT_ID (0xDD) */ + uint8_t length; /**< Length of all bytes in the element data following this field. Minimum 4. */ + uint8_t vendor_oui[3]; /**< Vendor identifier (OUI). */ + uint8_t vendor_oui_type; /**< Vendor-specific OUI type. */ + uint8_t payload[0]; /**< Payload. Length is equal to value in 'length' field, minus 4. */ +} vendor_ie_data_t; + +/** @brief Received packet radio metadata header, this is the common header at the beginning of all promiscuous mode RX callback buffers */ +typedef struct { + signed rssi:8; /**< Received Signal Strength Indicator(RSSI) of packet. unit: dBm */ + unsigned rate:5; /**< PHY rate encoding of the packet. Only valid for non HT(11bg) packet */ + unsigned :1; /**< reserved */ + unsigned sig_mode:2; /**< 0: non HT(11bg) packet; 1: HT(11n) packet; 3: VHT(11ac) packet */ + unsigned :16; /**< reserved */ + unsigned mcs:7; /**< Modulation Coding Scheme. If is HT(11n) packet, shows the modulation, range from 0 to 76(MSC0 ~ MCS76) */ + unsigned cwb:1; /**< Channel Bandwidth of the packet. 0: 20MHz; 1: 40MHz */ + unsigned :16; /**< reserved */ + unsigned smoothing:1; /**< reserved */ + unsigned not_sounding:1; /**< reserved */ + unsigned :1; /**< reserved */ + unsigned aggregation:1; /**< Aggregation. 0: MPDU packet; 1: AMPDU packet */ + unsigned stbc:2; /**< Space Time Block Code(STBC). 0: non STBC packet; 1: STBC packet */ + unsigned fec_coding:1; /**< Flag is set for 11n packets which are LDPC */ + unsigned sgi:1; /**< Short Guide Interval(SGI). 0: Long GI; 1: Short GI */ +#if CONFIG_IDF_TARGET_ESP32 + signed noise_floor:8; /**< noise floor of Radio Frequency Module(RF). unit: 0.25dBm*/ +#elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3 + unsigned :8; /**< reserved */ +#endif + unsigned ampdu_cnt:8; /**< ampdu cnt */ + unsigned channel:4; /**< primary channel on which this packet is received */ + unsigned secondary_channel:4; /**< secondary channel on which this packet is received. 0: none; 1: above; 2: below */ + unsigned :8; /**< reserved */ + unsigned timestamp:32; /**< timestamp. The local time when this packet is received. It is precise only if modem sleep or light sleep is not enabled. unit: microsecond */ + unsigned :32; /**< reserved */ +#if CONFIG_IDF_TARGET_ESP32S2 + unsigned :32; /**< reserved */ +#elif CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3 + signed noise_floor:8; /**< noise floor of Radio Frequency Module(RF). unit: 0.25dBm*/ + unsigned :24; /**< reserved */ + unsigned :32; /**< reserved */ +#endif + unsigned :31; /**< reserved */ + unsigned ant:1; /**< antenna number from which this packet is received. 0: WiFi antenna 0; 1: WiFi antenna 1 */ +#if CONFIG_IDF_TARGET_ESP32S2 + signed noise_floor:8; /**< noise floor of Radio Frequency Module(RF). unit: 0.25dBm*/ + unsigned :24; /**< reserved */ +#elif CONFIG_IDF_TARGET_ESP32S3 || CONFIG_IDF_TARGET_ESP32C3 + unsigned :32; /**< reserved */ + unsigned :32; /**< reserved */ + unsigned :32; /**< reserved */ +#endif + unsigned sig_len:12; /**< length of packet including Frame Check Sequence(FCS) */ + unsigned :12; /**< reserved */ + unsigned rx_state:8; /**< state of the packet. 0: no error; others: error numbers which are not public */ +} wifi_pkt_rx_ctrl_t; + +/** @brief Payload passed to 'buf' parameter of promiscuous mode RX callback. + */ +typedef struct { + wifi_pkt_rx_ctrl_t rx_ctrl; /**< metadata header */ + uint8_t payload[0]; /**< Data or management payload. Length of payload is described by rx_ctrl.sig_len. Type of content determined by packet type argument of callback. */ +} wifi_promiscuous_pkt_t; + +/** + * @brief Promiscuous frame type + * + * Passed to promiscuous mode RX callback to indicate the type of parameter in the buffer. + * + */ +typedef enum { + WIFI_PKT_MGMT, /**< Management frame, indicates 'buf' argument is wifi_promiscuous_pkt_t */ + WIFI_PKT_CTRL, /**< Control frame, indicates 'buf' argument is wifi_promiscuous_pkt_t */ + WIFI_PKT_DATA, /**< Data frame, indiciates 'buf' argument is wifi_promiscuous_pkt_t */ + WIFI_PKT_MISC, /**< Other type, such as MIMO etc. 'buf' argument is wifi_promiscuous_pkt_t but the payload is zero length. */ +} wifi_promiscuous_pkt_type_t; + + +#define WIFI_PROMIS_FILTER_MASK_ALL (0xFFFFFFFF) /**< filter all packets */ +#define WIFI_PROMIS_FILTER_MASK_MGMT (1) /**< filter the packets with type of WIFI_PKT_MGMT */ +#define WIFI_PROMIS_FILTER_MASK_CTRL (1<<1) /**< filter the packets with type of WIFI_PKT_CTRL */ +#define WIFI_PROMIS_FILTER_MASK_DATA (1<<2) /**< filter the packets with type of WIFI_PKT_DATA */ +#define WIFI_PROMIS_FILTER_MASK_MISC (1<<3) /**< filter the packets with type of WIFI_PKT_MISC */ +#define WIFI_PROMIS_FILTER_MASK_DATA_MPDU (1<<4) /**< filter the MPDU which is a kind of WIFI_PKT_DATA */ +#define WIFI_PROMIS_FILTER_MASK_DATA_AMPDU (1<<5) /**< filter the AMPDU which is a kind of WIFI_PKT_DATA */ +#define WIFI_PROMIS_FILTER_MASK_FCSFAIL (1<<6) /**< filter the FCS failed packets, do not open it in general */ + +#define WIFI_PROMIS_CTRL_FILTER_MASK_ALL (0xFF800000) /**< filter all control packets */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_WRAPPER (1<<23) /**< filter the control packets with subtype of Control Wrapper */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_BAR (1<<24) /**< filter the control packets with subtype of Block Ack Request */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_BA (1<<25) /**< filter the control packets with subtype of Block Ack */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_PSPOLL (1<<26) /**< filter the control packets with subtype of PS-Poll */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_RTS (1<<27) /**< filter the control packets with subtype of RTS */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_CTS (1<<28) /**< filter the control packets with subtype of CTS */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_ACK (1<<29) /**< filter the control packets with subtype of ACK */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_CFEND (1<<30) /**< filter the control packets with subtype of CF-END */ +#define WIFI_PROMIS_CTRL_FILTER_MASK_CFENDACK (1<<31) /**< filter the control packets with subtype of CF-END+CF-ACK */ + +/** @brief Mask for filtering different packet types in promiscuous mode. */ +typedef struct { + uint32_t filter_mask; /**< OR of one or more filter values WIFI_PROMIS_FILTER_* */ +} wifi_promiscuous_filter_t; + +#define WIFI_EVENT_MASK_ALL (0xFFFFFFFF) /**< mask all WiFi events */ +#define WIFI_EVENT_MASK_NONE (0) /**< mask none of the WiFi events */ +#define WIFI_EVENT_MASK_AP_PROBEREQRECVED (BIT(0)) /**< mask SYSTEM_EVENT_AP_PROBEREQRECVED event */ + +/** + * @brief Channel state information(CSI) configuration type + * + */ +typedef struct { + bool lltf_en; /**< enable to receive legacy long training field(lltf) data. Default enabled */ + bool htltf_en; /**< enable to receive HT long training field(htltf) data. Default enabled */ + bool stbc_htltf2_en; /**< enable to receive space time block code HT long training field(stbc-htltf2) data. Default enabled */ + bool ltf_merge_en; /**< enable to generate htlft data by averaging lltf and ht_ltf data when receiving HT packet. Otherwise, use ht_ltf data directly. Default enabled */ + bool channel_filter_en; /**< enable to turn on channel filter to smooth adjacent sub-carrier. Disable it to keep independence of adjacent sub-carrier. Default enabled */ + bool manu_scale; /**< manually scale the CSI data by left shifting or automatically scale the CSI data. If set true, please set the shift bits. false: automatically. true: manually. Default false */ + uint8_t shift; /**< manually left shift bits of the scale of the CSI data. The range of the left shift bits is 0~15 */ +} wifi_csi_config_t; + +/** + * @brief CSI data type + * + */ +typedef struct { + wifi_pkt_rx_ctrl_t rx_ctrl;/**< received packet radio metadata header of the CSI data */ + uint8_t mac[6]; /**< source MAC address of the CSI data */ + bool first_word_invalid; /**< first four bytes of the CSI data is invalid or not */ + int8_t *buf; /**< buffer of CSI data */ + uint16_t len; /**< length of CSI data */ +} wifi_csi_info_t; + +/** + * @brief WiFi GPIO configuration for antenna selection + * + */ +typedef struct { + uint8_t gpio_select: 1, /**< Whether this GPIO is connected to external antenna switch */ + gpio_num: 7; /**< The GPIO number that connects to external antenna switch */ +} wifi_ant_gpio_t; + +/** + * @brief WiFi GPIOs configuration for antenna selection + * + */ +typedef struct { + wifi_ant_gpio_t gpio_cfg[4]; /**< The configurations of GPIOs that connect to external antenna switch */ +} wifi_ant_gpio_config_t; + +/** + * @brief WiFi antenna mode + * + */ +typedef enum { + WIFI_ANT_MODE_ANT0, /**< Enable WiFi antenna 0 only */ + WIFI_ANT_MODE_ANT1, /**< Enable WiFi antenna 1 only */ + WIFI_ANT_MODE_AUTO, /**< Enable WiFi antenna 0 and 1, automatically select an antenna */ + WIFI_ANT_MODE_MAX, /**< Invalid WiFi enabled antenna */ +} wifi_ant_mode_t; + +/** + * @brief WiFi antenna configuration + * + */ +typedef struct { + wifi_ant_mode_t rx_ant_mode; /**< WiFi antenna mode for receiving */ + wifi_ant_t rx_ant_default; /**< Default antenna mode for receiving, it's ignored if rx_ant_mode is not WIFI_ANT_MODE_AUTO */ + wifi_ant_mode_t tx_ant_mode; /**< WiFi antenna mode for transmission, it can be set to WIFI_ANT_MODE_AUTO only if rx_ant_mode is set to WIFI_ANT_MODE_AUTO */ + uint8_t enabled_ant0: 4, /**< Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT0 */ + enabled_ant1: 4; /**< Index (in antenna GPIO configuration) of enabled WIFI_ANT_MODE_ANT1 */ +} wifi_ant_config_t; + +/** + * @brief The Rx callback function of Action Tx operations + * + * @param hdr pointer to the IEEE 802.11 Header structure + * @param payload pointer to the Payload following 802.11 Header + * @param len length of the Payload + * @param channel channel number the frame is received on + * + */ +typedef int (* wifi_action_rx_cb_t)(uint8_t *hdr, uint8_t *payload, + size_t len, uint8_t channel); + +/** + * @brief Action Frame Tx Request + * + * + */ +typedef struct { + wifi_interface_t ifx; /**< WiFi interface to send request to */ + uint8_t dest_mac[6]; /**< Destination MAC address */ + bool no_ack; /**< Indicates no ack required */ + wifi_action_rx_cb_t rx_cb; /**< Rx Callback to receive any response */ + uint32_t data_len; /**< Length of the appended Data */ + uint8_t data[0]; /**< Appended Data payload */ +} wifi_action_tx_req_t; + +/** + * @brief FTM Initiator configuration + * + */ +typedef struct { + uint8_t resp_mac[6]; /**< MAC address of the FTM Responder */ + uint8_t channel; /**< Primary channel of the FTM Responder */ + uint8_t frm_count; /**< No. of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0(No pref), 16, 24, 32, 64) */ + uint16_t burst_period; /**< Requested time period between consecutive FTM bursts in 100's of milliseconds (0 - No pref) */ +} wifi_ftm_initiator_cfg_t; + +/** + * @brief WiFi PHY rate encodings + * + */ +typedef enum { + WIFI_PHY_RATE_1M_L = 0x00, /**< 1 Mbps with long preamble */ + WIFI_PHY_RATE_2M_L = 0x01, /**< 2 Mbps with long preamble */ + WIFI_PHY_RATE_5M_L = 0x02, /**< 5.5 Mbps with long preamble */ + WIFI_PHY_RATE_11M_L = 0x03, /**< 11 Mbps with long preamble */ + WIFI_PHY_RATE_2M_S = 0x05, /**< 2 Mbps with short preamble */ + WIFI_PHY_RATE_5M_S = 0x06, /**< 5.5 Mbps with short preamble */ + WIFI_PHY_RATE_11M_S = 0x07, /**< 11 Mbps with short preamble */ + WIFI_PHY_RATE_48M = 0x08, /**< 48 Mbps */ + WIFI_PHY_RATE_24M = 0x09, /**< 24 Mbps */ + WIFI_PHY_RATE_12M = 0x0A, /**< 12 Mbps */ + WIFI_PHY_RATE_6M = 0x0B, /**< 6 Mbps */ + WIFI_PHY_RATE_54M = 0x0C, /**< 54 Mbps */ + WIFI_PHY_RATE_36M = 0x0D, /**< 36 Mbps */ + WIFI_PHY_RATE_18M = 0x0E, /**< 18 Mbps */ + WIFI_PHY_RATE_9M = 0x0F, /**< 9 Mbps */ + WIFI_PHY_RATE_MCS0_LGI = 0x10, /**< MCS0 with long GI, 6.5 Mbps for 20MHz, 13.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS1_LGI = 0x11, /**< MCS1 with long GI, 13 Mbps for 20MHz, 27 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS2_LGI = 0x12, /**< MCS2 with long GI, 19.5 Mbps for 20MHz, 40.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS3_LGI = 0x13, /**< MCS3 with long GI, 26 Mbps for 20MHz, 54 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS4_LGI = 0x14, /**< MCS4 with long GI, 39 Mbps for 20MHz, 81 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS5_LGI = 0x15, /**< MCS5 with long GI, 52 Mbps for 20MHz, 108 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS6_LGI = 0x16, /**< MCS6 with long GI, 58.5 Mbps for 20MHz, 121.5 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS7_LGI = 0x17, /**< MCS7 with long GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS0_SGI = 0x18, /**< MCS0 with short GI, 7.2 Mbps for 20MHz, 15 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS1_SGI = 0x19, /**< MCS1 with short GI, 14.4 Mbps for 20MHz, 30 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS2_SGI = 0x1A, /**< MCS2 with short GI, 21.7 Mbps for 20MHz, 45 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS3_SGI = 0x1B, /**< MCS3 with short GI, 28.9 Mbps for 20MHz, 60 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS4_SGI = 0x1C, /**< MCS4 with short GI, 43.3 Mbps for 20MHz, 90 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS5_SGI = 0x1D, /**< MCS5 with short GI, 57.8 Mbps for 20MHz, 120 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS6_SGI = 0x1E, /**< MCS6 with short GI, 65 Mbps for 20MHz, 135 Mbps for 40MHz */ + WIFI_PHY_RATE_MCS7_SGI = 0x1F, /**< MCS7 with short GI, 72.2 Mbps for 20MHz, 150 Mbps for 40MHz */ + WIFI_PHY_RATE_LORA_250K = 0x29, /**< 250 Kbps */ + WIFI_PHY_RATE_LORA_500K = 0x2A, /**< 500 Kbps */ + WIFI_PHY_RATE_MAX, +} wifi_phy_rate_t; + + +/** WiFi event declarations */ +typedef enum { + WIFI_EVENT_WIFI_READY = 0, /**< ESP32 WiFi ready */ + WIFI_EVENT_SCAN_DONE, /**< ESP32 finish scanning AP */ + WIFI_EVENT_STA_START, /**< ESP32 station start */ + WIFI_EVENT_STA_STOP, /**< ESP32 station stop */ + WIFI_EVENT_STA_CONNECTED, /**< ESP32 station connected to AP */ + WIFI_EVENT_STA_DISCONNECTED, /**< ESP32 station disconnected from AP */ + WIFI_EVENT_STA_AUTHMODE_CHANGE, /**< the auth mode of AP connected by ESP32 station changed */ + + WIFI_EVENT_STA_WPS_ER_SUCCESS, /**< ESP32 station wps succeeds in enrollee mode */ + WIFI_EVENT_STA_WPS_ER_FAILED, /**< ESP32 station wps fails in enrollee mode */ + WIFI_EVENT_STA_WPS_ER_TIMEOUT, /**< ESP32 station wps timeout in enrollee mode */ + WIFI_EVENT_STA_WPS_ER_PIN, /**< ESP32 station wps pin code in enrollee mode */ + WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP, /**< ESP32 station wps overlap in enrollee mode */ + + WIFI_EVENT_AP_START, /**< ESP32 soft-AP start */ + WIFI_EVENT_AP_STOP, /**< ESP32 soft-AP stop */ + WIFI_EVENT_AP_STACONNECTED, /**< a station connected to ESP32 soft-AP */ + WIFI_EVENT_AP_STADISCONNECTED, /**< a station disconnected from ESP32 soft-AP */ + WIFI_EVENT_AP_PROBEREQRECVED, /**< Receive probe request packet in soft-AP interface */ + + WIFI_EVENT_FTM_REPORT, /**< Receive report of FTM procedure */ + + /* Add next events after this only */ + WIFI_EVENT_STA_BSS_RSSI_LOW, /**< AP's RSSI crossed configured threshold */ + WIFI_EVENT_ACTION_TX_STATUS, /**< Status indication of Action Tx operation */ + WIFI_EVENT_ROC_DONE, /**< Remain-on-Channel operation complete */ + + WIFI_EVENT_STA_BEACON_TIMEOUT, /**< ESP32 station beacon timeout */ + + WIFI_EVENT_MAX, /**< Invalid WiFi event ID */ +} wifi_event_t; + +/** @cond **/ +/** @brief WiFi event base declaration */ +ESP_EVENT_DECLARE_BASE(WIFI_EVENT); +/** @endcond **/ + +/** Argument structure for WIFI_EVENT_SCAN_DONE event */ +typedef struct { + uint32_t status; /**< status of scanning APs: 0 — success, 1 - failure */ + uint8_t number; /**< number of scan results */ + uint8_t scan_id; /**< scan sequence number, used for block scan */ +} wifi_event_sta_scan_done_t; + +/** Argument structure for WIFI_EVENT_STA_CONNECTED event */ +typedef struct { + uint8_t ssid[32]; /**< SSID of connected AP */ + uint8_t ssid_len; /**< SSID length of connected AP */ + uint8_t bssid[6]; /**< BSSID of connected AP*/ + uint8_t channel; /**< channel of connected AP*/ + wifi_auth_mode_t authmode;/**< authentication mode used by AP*/ +} wifi_event_sta_connected_t; + +/** Argument structure for WIFI_EVENT_STA_DISCONNECTED event */ +typedef struct { + uint8_t ssid[32]; /**< SSID of disconnected AP */ + uint8_t ssid_len; /**< SSID length of disconnected AP */ + uint8_t bssid[6]; /**< BSSID of disconnected AP */ + uint8_t reason; /**< reason of disconnection */ +} wifi_event_sta_disconnected_t; + +/** Argument structure for WIFI_EVENT_STA_AUTHMODE_CHANGE event */ +typedef struct { + wifi_auth_mode_t old_mode; /**< the old auth mode of AP */ + wifi_auth_mode_t new_mode; /**< the new auth mode of AP */ +} wifi_event_sta_authmode_change_t; + +/** Argument structure for WIFI_EVENT_STA_WPS_ER_PIN event */ +typedef struct { + uint8_t pin_code[8]; /**< PIN code of station in enrollee mode */ +} wifi_event_sta_wps_er_pin_t; + +/** Argument structure for WIFI_EVENT_STA_WPS_ER_FAILED event */ +typedef enum { + WPS_FAIL_REASON_NORMAL = 0, /**< ESP32 WPS normal fail reason */ + WPS_FAIL_REASON_RECV_M2D, /**< ESP32 WPS receive M2D frame */ + WPS_FAIL_REASON_MAX +} wifi_event_sta_wps_fail_reason_t; + +#define MAX_SSID_LEN 32 +#define MAX_PASSPHRASE_LEN 64 +#define MAX_WPS_AP_CRED 3 + +/** Argument structure for WIFI_EVENT_STA_WPS_ER_SUCCESS event */ +typedef struct { + uint8_t ap_cred_cnt; /**< Number of AP credentials received */ + struct { + uint8_t ssid[MAX_SSID_LEN]; /**< SSID of AP */ + uint8_t passphrase[MAX_PASSPHRASE_LEN]; /**< Passphrase for the AP */ + } ap_cred[MAX_WPS_AP_CRED]; /**< All AP credentials received from WPS handshake */ +} wifi_event_sta_wps_er_success_t; + +/** Argument structure for WIFI_EVENT_AP_STACONNECTED event */ +typedef struct { + uint8_t mac[6]; /**< MAC address of the station connected to ESP32 soft-AP */ + uint8_t aid; /**< the aid that ESP32 soft-AP gives to the station connected to */ +} wifi_event_ap_staconnected_t; + +/** Argument structure for WIFI_EVENT_AP_STADISCONNECTED event */ +typedef struct { + uint8_t mac[6]; /**< MAC address of the station disconnects to ESP32 soft-AP */ + uint8_t aid; /**< the aid that ESP32 soft-AP gave to the station disconnects to */ +} wifi_event_ap_stadisconnected_t; + +/** Argument structure for WIFI_EVENT_AP_PROBEREQRECVED event */ +typedef struct { + int rssi; /**< Received probe request signal strength */ + uint8_t mac[6]; /**< MAC address of the station which send probe request */ +} wifi_event_ap_probe_req_rx_t; + +/** Argument structure for WIFI_EVENT_STA_BSS_RSSI_LOW event */ +typedef struct { + int32_t rssi; /**< RSSI value of bss */ +} wifi_event_bss_rssi_low_t; + +/** + * @brief FTM operation status types + * + */ +typedef enum { + FTM_STATUS_SUCCESS = 0, /**< FTM exchange is successful */ + FTM_STATUS_UNSUPPORTED, /**< Peer does not support FTM */ + FTM_STATUS_CONF_REJECTED, /**< Peer rejected FTM configuration in FTM Request */ + FTM_STATUS_NO_RESPONSE, /**< Peer did not respond to FTM Requests */ + FTM_STATUS_FAIL, /**< Unknown error during FTM exchange */ +} wifi_ftm_status_t; + +/** Argument structure for */ +typedef struct { + uint8_t dlog_token; /**< Dialog Token of the FTM frame */ + int8_t rssi; /**< RSSI of the FTM frame received */ + uint32_t rtt; /**< Round Trip Time in pSec with a peer */ + uint64_t t1; /**< Time of departure of FTM frame from FTM Responder in pSec */ + uint64_t t2; /**< Time of arrival of FTM frame at FTM Initiator in pSec */ + uint64_t t3; /**< Time of departure of ACK from FTM Initiator in pSec */ + uint64_t t4; /**< Time of arrival of ACK at FTM Responder in pSec */ +} wifi_ftm_report_entry_t; + +/** Argument structure for WIFI_EVENT_FTM_REPORT event */ +typedef struct { + uint8_t peer_mac[6]; /**< MAC address of the FTM Peer */ + wifi_ftm_status_t status; /**< Status of the FTM operation */ + uint32_t rtt_raw; /**< Raw average Round-Trip-Time with peer in Nano-Seconds */ + uint32_t rtt_est; /**< Estimated Round-Trip-Time with peer in Nano-Seconds */ + uint32_t dist_est; /**< Estimated one-way distance in Centi-Meters */ + wifi_ftm_report_entry_t *ftm_report_data; /**< Pointer to FTM Report with multiple entries, should be freed after use */ + uint8_t ftm_report_num_entries; /**< Number of entries in the FTM Report data */ +} wifi_event_ftm_report_t; + +#define WIFI_STATIS_BUFFER (1<<0) +#define WIFI_STATIS_RXTX (1<<1) +#define WIFI_STATIS_HW (1<<2) +#define WIFI_STATIS_DIAG (1<<3) +#define WIFI_STATIS_PS (1<<4) +#define WIFI_STATIS_ALL (-1) + +/** Argument structure for WIFI_EVENT_ACTION_TX_STATUS event */ +typedef struct { + wifi_interface_t ifx; /**< WiFi interface to send request to */ + uint32_t context; /**< Context to identify the request */ + uint8_t da[6]; /**< Destination MAC address */ + uint8_t status; /**< Status of the operation */ +} wifi_event_action_tx_status_t; + +/** Argument structure for WIFI_EVENT_ROC_DONE event */ +typedef struct { + uint32_t context; /**< Context to identify the request */ +} wifi_event_roc_done_t; + +#ifdef __cplusplus +} +#endif + +#endif /* __ESP_WIFI_TYPES_H__ */ diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/phy.h b/tools/sdk/esp32c3/include/esp_wifi/include/phy.h new file mode 100644 index 00000000..c0eadbf2 --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/phy.h @@ -0,0 +1,98 @@ +// Copyright 2015-2016 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. + +#pragma once +#include "esp_phy_init.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ESP_CAL_DATA_CHECK_FAIL 1 + +/** + * @file phy.h + * @brief Declarations for functions provided by libphy.a + */ + +/** + * @brief Return ROM function pointer table from PHY library. + */ +void phy_get_romfunc_addr(void); + +/** + * @brief Initialize PHY module and do RF calibration + * @param[in] init_data Initialization parameters to be used by the PHY + * @param[inout] cal_data As input, calibration data previously obtained. As output, will contain new calibration data. + * @param[in] cal_mode RF calibration mode + * @return ESP_CAL_DATA_CHECK_FAIL if calibration data checksum fails, other values are reserved for future use + */ +int register_chipv7_phy(const esp_phy_init_data_t* init_data, esp_phy_calibration_data_t *cal_data, esp_phy_calibration_mode_t cal_mode); + +/** + * @brief Get the format version of calibration data used by PHY library. + * @return Format version number, OR'ed with BIT(16) if PHY is in WIFI only mode. + */ +uint32_t phy_get_rf_cal_version(void); + +/** + * @brief Set RF/BB for only WIFI mode or coexist(WIFI & BT) mode + * @param[in] true is for only WIFI mode, false is for coexist mode. default is 0. + * @return NULL + */ +void phy_set_wifi_mode_only(bool wifi_only); + +/** + * @brief Set BT the highest priority in coexist mode. + * @return NULL + */ +void coex_bt_high_prio(void); + +/** + * @brief Open PHY and RF. + */ +void phy_wakeup_init(void); + +/** + * @brief Shutdown PHY and RF. + */ +void phy_close_rf(void); + +#if CONFIG_IDF_TARGET_ESP32C3 || CONFIG_IDF_TARGET_ESP32S2 +/** + * @brief Disable PHY temperature sensor. + */ +void phy_xpd_tsens(void); +#endif + +/** + * @brief Store and load PHY digital registers. + * + * @param backup_en if backup_en is true, store PHY digital registers to memory. Otherwise load PHY digital registers from memory + * @param mem_addr Memory address to store and load PHY digital registers + * + * @return memory size + */ +uint8_t phy_dig_reg_backup(bool backup_en, uint32_t *mem_addr); + +#if CONFIG_MAC_BB_PD +/** + * @brief Store and load baseband registers. + */ +void phy_freq_mem_backup(bool backup_en, uint32_t *mem); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/esp_wifi/include/smartconfig_ack.h b/tools/sdk/esp32c3/include/esp_wifi/include/smartconfig_ack.h new file mode 100644 index 00000000..abfada3f --- /dev/null +++ b/tools/sdk/esp32c3/include/esp_wifi/include/smartconfig_ack.h @@ -0,0 +1,44 @@ +// Copyright 2010-2017 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. + +#ifndef SMARTCONFIG_ACK_H +#define SMARTCONFIG_ACK_H + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Send smartconfig ACK to cellphone. + * + * @attention The API can only be used when receiving SC_EVENT_GOT_SSID_PSWD event. + * + * @param type: smartconfig type(ESPTouch or AirKiss); + * token: token from the cellphone; + * cellphone_ip: IP address of the cellphone; + * + * @return ESP_OK: succeed + * others: fail + */ +esp_err_t sc_send_ack_start(smartconfig_type_t type, uint8_t token, uint8_t *cellphone_ip); + +/** + * @brief Stop sending smartconfig ACK to cellphone. + */ +void sc_send_ack_stop(void); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/tools/sdk/esp32c3/include/espcoredump/include/esp_core_dump.h b/tools/sdk/esp32c3/include/espcoredump/include/esp_core_dump.h new file mode 100644 index 00000000..fb0d44d2 --- /dev/null +++ b/tools/sdk/esp32c3/include/espcoredump/include/esp_core_dump.h @@ -0,0 +1,96 @@ +// Copyright 2015-2019 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. +#ifndef ESP_CORE_DUMP_H_ +#define ESP_CORE_DUMP_H_ + +#include +#include "esp_err.h" +#include "esp_private/panic_internal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/**************************************************************************************/ +/******************************** EXCEPTION MODE API **********************************/ +/**************************************************************************************/ + +/** + * @brief Initializes core dump module internal data. + * + * @note Should be called at system startup. + */ +void esp_core_dump_init(void); + +/** + * @brief Saves core dump to flash. + * + * The structure of data stored in flash is as follows: + * + * | TOTAL_LEN | VERSION | TASKS_NUM | TCB_SIZE | + * | TCB_ADDR_1 | STACK_TOP_1 | STACK_END_1 | TCB_1 | STACK_1 | + * . . . . + * . . . . + * | TCB_ADDR_N | STACK_TOP_N | STACK_END_N | TCB_N | STACK_N | + * | CHECKSUM | + * + * Core dump in flash consists of header and data for every task in the system at the moment of crash. + * For flash data integrity, a checksum is used at the end of core the dump data. + * The structure of core dump data is described below in details. + * 1) Core dump starts with header: + * 1.1) TOTAL_LEN is total length of core dump data in flash including the checksum. Size is 4 bytes. + * 1.2) VERSION field keeps 4 byte version of core dump. + * 1.2) TASKS_NUM is the number of tasks for which data are stored. Size is 4 bytes. + * 1.3) TCB_SIZE is the size of task's TCB structure. Size is 4 bytes. + * 2) Core dump header is followed by the data for every task in the system. + * Task data are started with task header: + * 2.1) TCB_ADDR is the address of TCB in memory. Size is 4 bytes. + * 2.2) STACK_TOP is the top of task's stack (address of the topmost stack item). Size is 4 bytes. + * 2.2) STACK_END is the end of task's stack (address from which task's stack starts). Size is 4 bytes. + * 3) Task header is followed by TCB data. Size is TCB_SIZE bytes. + * 4) Task's stack is placed after TCB data. Size is (STACK_END - STACK_TOP) bytes. + * 5) The checksum is placed at the end of the data. + */ +void esp_core_dump_to_flash(panic_info_t *info); + +/** + * @brief Print base64-encoded core dump to UART. + * + * The structure of core dump data is the same as for data stored in flash (@see esp_core_dump_to_flash) with some notes: + * 1) The checksum is not present in core dump printed to UART. + * 2) Since checksum is omitted TOTAL_LEN does not include its size. + * 3) Printed base64 data are surrounded with special messages to help user recognize the start and end of actual data. + */ +void esp_core_dump_to_uart(panic_info_t *info); + +/**************************************************************************************/ +/*********************************** USER MODE API ************************************/ +/**************************************************************************************/ + +/** + * @brief Retrieves address and size of coredump data in flash. + * This function is always available, even when core dump is disabled in menuconfig. + * + * @param out_addr pointer to store image address in flash. + * @param out_size pointer to store image size in flash (including checksum). In bytes. + * + * @return ESP_OK on success, otherwise \see esp_err_t + */ +esp_err_t esp_core_dump_image_get(size_t* out_addr, size_t *out_size); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/ascii.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/ascii.h new file mode 100644 index 00000000..c3587e57 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/ascii.h @@ -0,0 +1,120 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#define ASCII_A 0x41 +#define ASCII_B 0x42 +#define ASCII_C 0x43 +#define ASCII_D 0x44 +#define ASCII_E 0x45 +#define ASCII_F 0x46 +#define ASCII_G 0x47 +#define ASCII_H 0x48 +#define ASCII_I 0x49 +#define ASCII_J 0x4A +#define ASCII_K 0x4B +#define ASCII_L 0x4C +#define ASCII_M 0x4D +#define ASCII_N 0x4E +#define ASCII_O 0x4F +#define ASCII_P 0x50 +#define ASCII_Q 0x51 +#define ASCII_R 0x52 +#define ASCII_S 0x53 +#define ASCII_T 0x54 +#define ASCII_U 0x55 +#define ASCII_V 0x56 +#define ASCII_W 0x57 +#define ASCII_X 0x58 +#define ASCII_Y 0x59 +#define ASCII_Z 0x5A + +#define ASCII_a 0x61 +#define ASCII_b 0x62 +#define ASCII_c 0x63 +#define ASCII_d 0x64 +#define ASCII_e 0x65 +#define ASCII_f 0x66 +#define ASCII_g 0x67 +#define ASCII_h 0x68 +#define ASCII_i 0x69 +#define ASCII_j 0x6A +#define ASCII_k 0x6B +#define ASCII_l 0x6C +#define ASCII_m 0x6D +#define ASCII_n 0x6E +#define ASCII_o 0x6F +#define ASCII_p 0x70 +#define ASCII_q 0x71 +#define ASCII_r 0x72 +#define ASCII_s 0x73 +#define ASCII_t 0x74 +#define ASCII_u 0x75 +#define ASCII_v 0x76 +#define ASCII_w 0x77 +#define ASCII_x 0x78 +#define ASCII_y 0x79 +#define ASCII_z 0x7A + +#define ASCII_0 0x30 +#define ASCII_1 0x31 +#define ASCII_2 0x32 +#define ASCII_3 0x33 +#define ASCII_4 0x34 +#define ASCII_5 0x35 +#define ASCII_6 0x36 +#define ASCII_7 0x37 +#define ASCII_8 0x38 +#define ASCII_9 0x39 + +#define ASCII_TAB 0x09 +#define ASCII_SPACE 0x20 +#define ASCII_EXCL 0x21 +#define ASCII_QUOT 0x22 +#define ASCII_AMP 0x26 +#define ASCII_APOS 0x27 +#define ASCII_MINUS 0x2D +#define ASCII_PERIOD 0x2E +#define ASCII_COLON 0x3A +#define ASCII_SEMI 0x3B +#define ASCII_LT 0x3C +#define ASCII_EQUALS 0x3D +#define ASCII_GT 0x3E +#define ASCII_LSQB 0x5B +#define ASCII_RSQB 0x5D +#define ASCII_UNDERSCORE 0x5F +#define ASCII_LPAREN 0x28 +#define ASCII_RPAREN 0x29 +#define ASCII_FF 0x0C +#define ASCII_SLASH 0x2F +#define ASCII_HASH 0x23 +#define ASCII_PIPE 0x7C +#define ASCII_COMMA 0x2C diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/asciitab.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/asciitab.h new file mode 100644 index 00000000..2f59fd92 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/asciitab.h @@ -0,0 +1,64 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, +/* 0x0C */ BT_NONXML, BT_CR, BT_NONXML, BT_NONXML, +/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, +/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, +/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, +/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, +/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, +/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, +/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, +/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, +/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat.h new file mode 100644 index 00000000..1f608c02 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat.h @@ -0,0 +1,1085 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef Expat_INCLUDED +#define Expat_INCLUDED 1 + +#ifdef __VMS +/* 0 1 2 3 0 1 2 3 + 1234567890123456789012345678901 1234567890123456789012345678901 */ +#define XML_SetProcessingInstructionHandler XML_SetProcessingInstrHandler +#define XML_SetUnparsedEntityDeclHandler XML_SetUnparsedEntDeclHandler +#define XML_SetStartNamespaceDeclHandler XML_SetStartNamespcDeclHandler +#define XML_SetExternalEntityRefHandlerArg XML_SetExternalEntRefHandlerArg +#endif + +#include +#include "expat_external.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct XML_ParserStruct; +typedef struct XML_ParserStruct *XML_Parser; + +typedef unsigned char XML_Bool; +#define XML_TRUE ((XML_Bool) 1) +#define XML_FALSE ((XML_Bool) 0) + +/* The XML_Status enum gives the possible return values for several + API functions. The preprocessor #defines are included so this + stanza can be added to code that still needs to support older + versions of Expat 1.95.x: + + #ifndef XML_STATUS_OK + #define XML_STATUS_OK 1 + #define XML_STATUS_ERROR 0 + #endif + + Otherwise, the #define hackery is quite ugly and would have been + dropped. +*/ +enum XML_Status { + XML_STATUS_ERROR = 0, +#define XML_STATUS_ERROR XML_STATUS_ERROR + XML_STATUS_OK = 1, +#define XML_STATUS_OK XML_STATUS_OK + XML_STATUS_SUSPENDED = 2 +#define XML_STATUS_SUSPENDED XML_STATUS_SUSPENDED +}; + +enum XML_Error { + XML_ERROR_NONE, + XML_ERROR_NO_MEMORY, + XML_ERROR_SYNTAX, + XML_ERROR_NO_ELEMENTS, + XML_ERROR_INVALID_TOKEN, + XML_ERROR_UNCLOSED_TOKEN, + XML_ERROR_PARTIAL_CHAR, + XML_ERROR_TAG_MISMATCH, + XML_ERROR_DUPLICATE_ATTRIBUTE, + XML_ERROR_JUNK_AFTER_DOC_ELEMENT, + XML_ERROR_PARAM_ENTITY_REF, + XML_ERROR_UNDEFINED_ENTITY, + XML_ERROR_RECURSIVE_ENTITY_REF, + XML_ERROR_ASYNC_ENTITY, + XML_ERROR_BAD_CHAR_REF, + XML_ERROR_BINARY_ENTITY_REF, + XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF, + XML_ERROR_MISPLACED_XML_PI, + XML_ERROR_UNKNOWN_ENCODING, + XML_ERROR_INCORRECT_ENCODING, + XML_ERROR_UNCLOSED_CDATA_SECTION, + XML_ERROR_EXTERNAL_ENTITY_HANDLING, + XML_ERROR_NOT_STANDALONE, + XML_ERROR_UNEXPECTED_STATE, + XML_ERROR_ENTITY_DECLARED_IN_PE, + XML_ERROR_FEATURE_REQUIRES_XML_DTD, + XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING, + /* Added in 1.95.7. */ + XML_ERROR_UNBOUND_PREFIX, + /* Added in 1.95.8. */ + XML_ERROR_UNDECLARING_PREFIX, + XML_ERROR_INCOMPLETE_PE, + XML_ERROR_XML_DECL, + XML_ERROR_TEXT_DECL, + XML_ERROR_PUBLICID, + XML_ERROR_SUSPENDED, + XML_ERROR_NOT_SUSPENDED, + XML_ERROR_ABORTED, + XML_ERROR_FINISHED, + XML_ERROR_SUSPEND_PE, + /* Added in 2.0. */ + XML_ERROR_RESERVED_PREFIX_XML, + XML_ERROR_RESERVED_PREFIX_XMLNS, + XML_ERROR_RESERVED_NAMESPACE_URI, + /* Added in 2.2.1. */ + XML_ERROR_INVALID_ARGUMENT +}; + +enum XML_Content_Type { + XML_CTYPE_EMPTY = 1, + XML_CTYPE_ANY, + XML_CTYPE_MIXED, + XML_CTYPE_NAME, + XML_CTYPE_CHOICE, + XML_CTYPE_SEQ +}; + +enum XML_Content_Quant { + XML_CQUANT_NONE, + XML_CQUANT_OPT, + XML_CQUANT_REP, + XML_CQUANT_PLUS +}; + +/* If type == XML_CTYPE_EMPTY or XML_CTYPE_ANY, then quant will be + XML_CQUANT_NONE, and the other fields will be zero or NULL. + If type == XML_CTYPE_MIXED, then quant will be NONE or REP and + numchildren will contain number of elements that may be mixed in + and children point to an array of XML_Content cells that will be + all of XML_CTYPE_NAME type with no quantification. + + If type == XML_CTYPE_NAME, then the name points to the name, and + the numchildren field will be zero and children will be NULL. The + quant fields indicates any quantifiers placed on the name. + + CHOICE and SEQ will have name NULL, the number of children in + numchildren and children will point, recursively, to an array + of XML_Content cells. + + The EMPTY, ANY, and MIXED types will only occur at top level. +*/ + +typedef struct XML_cp XML_Content; + +struct XML_cp { + enum XML_Content_Type type; + enum XML_Content_Quant quant; + XML_Char * name; + unsigned int numchildren; + XML_Content * children; +}; + + +/* This is called for an element declaration. See above for + description of the model argument. It's the caller's responsibility + to free model when finished with it. +*/ +typedef void (XMLCALL *XML_ElementDeclHandler) (void *userData, + const XML_Char *name, + XML_Content *model); + +XMLPARSEAPI(void) +XML_SetElementDeclHandler(XML_Parser parser, + XML_ElementDeclHandler eldecl); + +/* The Attlist declaration handler is called for *each* attribute. So + a single Attlist declaration with multiple attributes declared will + generate multiple calls to this handler. The "default" parameter + may be NULL in the case of the "#IMPLIED" or "#REQUIRED" + keyword. The "isrequired" parameter will be true and the default + value will be NULL in the case of "#REQUIRED". If "isrequired" is + true and default is non-NULL, then this is a "#FIXED" default. +*/ +typedef void (XMLCALL *XML_AttlistDeclHandler) ( + void *userData, + const XML_Char *elname, + const XML_Char *attname, + const XML_Char *att_type, + const XML_Char *dflt, + int isrequired); + +XMLPARSEAPI(void) +XML_SetAttlistDeclHandler(XML_Parser parser, + XML_AttlistDeclHandler attdecl); + +/* The XML declaration handler is called for *both* XML declarations + and text declarations. The way to distinguish is that the version + parameter will be NULL for text declarations. The encoding + parameter may be NULL for XML declarations. The standalone + parameter will be -1, 0, or 1 indicating respectively that there + was no standalone parameter in the declaration, that it was given + as no, or that it was given as yes. +*/ +typedef void (XMLCALL *XML_XmlDeclHandler) (void *userData, + const XML_Char *version, + const XML_Char *encoding, + int standalone); + +XMLPARSEAPI(void) +XML_SetXmlDeclHandler(XML_Parser parser, + XML_XmlDeclHandler xmldecl); + + +typedef struct { + void *(*malloc_fcn)(size_t size); + void *(*realloc_fcn)(void *ptr, size_t size); + void (*free_fcn)(void *ptr); +} XML_Memory_Handling_Suite; + +/* Constructs a new parser; encoding is the encoding specified by the + external protocol or NULL if there is none specified. +*/ +XMLPARSEAPI(XML_Parser) +XML_ParserCreate(const XML_Char *encoding); + +/* Constructs a new parser and namespace processor. Element type + names and attribute names that belong to a namespace will be + expanded; unprefixed attribute names are never expanded; unprefixed + element type names are expanded only if there is a default + namespace. The expanded name is the concatenation of the namespace + URI, the namespace separator character, and the local part of the + name. If the namespace separator is '\0' then the namespace URI + and the local part will be concatenated without any separator. + It is a programming error to use the separator '\0' with namespace + triplets (see XML_SetReturnNSTriplet). +*/ +XMLPARSEAPI(XML_Parser) +XML_ParserCreateNS(const XML_Char *encoding, XML_Char namespaceSeparator); + + +/* Constructs a new parser using the memory management suite referred to + by memsuite. If memsuite is NULL, then use the standard library memory + suite. If namespaceSeparator is non-NULL it creates a parser with + namespace processing as described above. The character pointed at + will serve as the namespace separator. + + All further memory operations used for the created parser will come from + the given suite. +*/ +XMLPARSEAPI(XML_Parser) +XML_ParserCreate_MM(const XML_Char *encoding, + const XML_Memory_Handling_Suite *memsuite, + const XML_Char *namespaceSeparator); + +/* Prepare a parser object to be re-used. This is particularly + valuable when memory allocation overhead is disproportionatly high, + such as when a large number of small documnents need to be parsed. + All handlers are cleared from the parser, except for the + unknownEncodingHandler. The parser's external state is re-initialized + except for the values of ns and ns_triplets. + + Added in Expat 1.95.3. +*/ +XMLPARSEAPI(XML_Bool) +XML_ParserReset(XML_Parser parser, const XML_Char *encoding); + +/* atts is array of name/value pairs, terminated by 0; + names and values are 0 terminated. +*/ +typedef void (XMLCALL *XML_StartElementHandler) (void *userData, + const XML_Char *name, + const XML_Char **atts); + +typedef void (XMLCALL *XML_EndElementHandler) (void *userData, + const XML_Char *name); + + +/* s is not 0 terminated. */ +typedef void (XMLCALL *XML_CharacterDataHandler) (void *userData, + const XML_Char *s, + int len); + +/* target and data are 0 terminated */ +typedef void (XMLCALL *XML_ProcessingInstructionHandler) ( + void *userData, + const XML_Char *target, + const XML_Char *data); + +/* data is 0 terminated */ +typedef void (XMLCALL *XML_CommentHandler) (void *userData, + const XML_Char *data); + +typedef void (XMLCALL *XML_StartCdataSectionHandler) (void *userData); +typedef void (XMLCALL *XML_EndCdataSectionHandler) (void *userData); + +/* This is called for any characters in the XML document for which + there is no applicable handler. This includes both characters that + are part of markup which is of a kind that is not reported + (comments, markup declarations), or characters that are part of a + construct which could be reported but for which no handler has been + supplied. The characters are passed exactly as they were in the XML + document except that they will be encoded in UTF-8 or UTF-16. + Line boundaries are not normalized. Note that a byte order mark + character is not passed to the default handler. There are no + guarantees about how characters are divided between calls to the + default handler: for example, a comment might be split between + multiple calls. +*/ +typedef void (XMLCALL *XML_DefaultHandler) (void *userData, + const XML_Char *s, + int len); + +/* This is called for the start of the DOCTYPE declaration, before + any DTD or internal subset is parsed. +*/ +typedef void (XMLCALL *XML_StartDoctypeDeclHandler) ( + void *userData, + const XML_Char *doctypeName, + const XML_Char *sysid, + const XML_Char *pubid, + int has_internal_subset); + +/* This is called for the start of the DOCTYPE declaration when the + closing > is encountered, but after processing any external + subset. +*/ +typedef void (XMLCALL *XML_EndDoctypeDeclHandler)(void *userData); + +/* This is called for entity declarations. The is_parameter_entity + argument will be non-zero if the entity is a parameter entity, zero + otherwise. + + For internal entities (), value will + be non-NULL and systemId, publicID, and notationName will be NULL. + The value string is NOT nul-terminated; the length is provided in + the value_length argument. Since it is legal to have zero-length + values, do not use this argument to test for internal entities. + + For external entities, value will be NULL and systemId will be + non-NULL. The publicId argument will be NULL unless a public + identifier was provided. The notationName argument will have a + non-NULL value only for unparsed entity declarations. + + Note that is_parameter_entity can't be changed to XML_Bool, since + that would break binary compatibility. +*/ +typedef void (XMLCALL *XML_EntityDeclHandler) ( + void *userData, + const XML_Char *entityName, + int is_parameter_entity, + const XML_Char *value, + int value_length, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName); + +XMLPARSEAPI(void) +XML_SetEntityDeclHandler(XML_Parser parser, + XML_EntityDeclHandler handler); + +/* OBSOLETE -- OBSOLETE -- OBSOLETE + This handler has been superseded by the EntityDeclHandler above. + It is provided here for backward compatibility. + + This is called for a declaration of an unparsed (NDATA) entity. + The base argument is whatever was set by XML_SetBase. The + entityName, systemId and notationName arguments will never be + NULL. The other arguments may be. +*/ +typedef void (XMLCALL *XML_UnparsedEntityDeclHandler) ( + void *userData, + const XML_Char *entityName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId, + const XML_Char *notationName); + +/* This is called for a declaration of notation. The base argument is + whatever was set by XML_SetBase. The notationName will never be + NULL. The other arguments can be. +*/ +typedef void (XMLCALL *XML_NotationDeclHandler) ( + void *userData, + const XML_Char *notationName, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + +/* When namespace processing is enabled, these are called once for + each namespace declaration. The call to the start and end element + handlers occur between the calls to the start and end namespace + declaration handlers. For an xmlns attribute, prefix will be + NULL. For an xmlns="" attribute, uri will be NULL. +*/ +typedef void (XMLCALL *XML_StartNamespaceDeclHandler) ( + void *userData, + const XML_Char *prefix, + const XML_Char *uri); + +typedef void (XMLCALL *XML_EndNamespaceDeclHandler) ( + void *userData, + const XML_Char *prefix); + +/* This is called if the document is not standalone, that is, it has an + external subset or a reference to a parameter entity, but does not + have standalone="yes". If this handler returns XML_STATUS_ERROR, + then processing will not continue, and the parser will return a + XML_ERROR_NOT_STANDALONE error. + If parameter entity parsing is enabled, then in addition to the + conditions above this handler will only be called if the referenced + entity was actually read. +*/ +typedef int (XMLCALL *XML_NotStandaloneHandler) (void *userData); + +/* This is called for a reference to an external parsed general + entity. The referenced entity is not automatically parsed. The + application can parse it immediately or later using + XML_ExternalEntityParserCreate. + + The parser argument is the parser parsing the entity containing the + reference; it can be passed as the parser argument to + XML_ExternalEntityParserCreate. The systemId argument is the + system identifier as specified in the entity declaration; it will + not be NULL. + + The base argument is the system identifier that should be used as + the base for resolving systemId if systemId was relative; this is + set by XML_SetBase; it may be NULL. + + The publicId argument is the public identifier as specified in the + entity declaration, or NULL if none was specified; the whitespace + in the public identifier will have been normalized as required by + the XML spec. + + The context argument specifies the parsing context in the format + expected by the context argument to XML_ExternalEntityParserCreate; + context is valid only until the handler returns, so if the + referenced entity is to be parsed later, it must be copied. + context is NULL only when the entity is a parameter entity. + + The handler should return XML_STATUS_ERROR if processing should not + continue because of a fatal error in the handling of the external + entity. In this case the calling parser will return an + XML_ERROR_EXTERNAL_ENTITY_HANDLING error. + + Note that unlike other handlers the first argument is the parser, + not userData. +*/ +typedef int (XMLCALL *XML_ExternalEntityRefHandler) ( + XML_Parser parser, + const XML_Char *context, + const XML_Char *base, + const XML_Char *systemId, + const XML_Char *publicId); + +/* This is called in two situations: + 1) An entity reference is encountered for which no declaration + has been read *and* this is not an error. + 2) An internal entity reference is read, but not expanded, because + XML_SetDefaultHandler has been called. + Note: skipped parameter entities in declarations and skipped general + entities in attribute values cannot be reported, because + the event would be out of sync with the reporting of the + declarations or attribute values +*/ +typedef void (XMLCALL *XML_SkippedEntityHandler) ( + void *userData, + const XML_Char *entityName, + int is_parameter_entity); + +/* This structure is filled in by the XML_UnknownEncodingHandler to + provide information to the parser about encodings that are unknown + to the parser. + + The map[b] member gives information about byte sequences whose + first byte is b. + + If map[b] is c where c is >= 0, then b by itself encodes the + Unicode scalar value c. + + If map[b] is -1, then the byte sequence is malformed. + + If map[b] is -n, where n >= 2, then b is the first byte of an + n-byte sequence that encodes a single Unicode scalar value. + + The data member will be passed as the first argument to the convert + function. + + The convert function is used to convert multibyte sequences; s will + point to a n-byte sequence where map[(unsigned char)*s] == -n. The + convert function must return the Unicode scalar value represented + by this byte sequence or -1 if the byte sequence is malformed. + + The convert function may be NULL if the encoding is a single-byte + encoding, that is if map[b] >= -1 for all bytes b. + + When the parser is finished with the encoding, then if release is + not NULL, it will call release passing it the data member; once + release has been called, the convert function will not be called + again. + + Expat places certain restrictions on the encodings that are supported + using this mechanism. + + 1. Every ASCII character that can appear in a well-formed XML document, + other than the characters + + $@\^`{}~ + + must be represented by a single byte, and that byte must be the + same byte that represents that character in ASCII. + + 2. No character may require more than 4 bytes to encode. + + 3. All characters encoded must have Unicode scalar values <= + 0xFFFF, (i.e., characters that would be encoded by surrogates in + UTF-16 are not allowed). Note that this restriction doesn't + apply to the built-in support for UTF-8 and UTF-16. + + 4. No Unicode character may be encoded by more than one distinct + sequence of bytes. +*/ +typedef struct { + int map[256]; + void *data; + int (XMLCALL *convert)(void *data, const char *s); + void (XMLCALL *release)(void *data); +} XML_Encoding; + +/* This is called for an encoding that is unknown to the parser. + + The encodingHandlerData argument is that which was passed as the + second argument to XML_SetUnknownEncodingHandler. + + The name argument gives the name of the encoding as specified in + the encoding declaration. + + If the callback can provide information about the encoding, it must + fill in the XML_Encoding structure, and return XML_STATUS_OK. + Otherwise it must return XML_STATUS_ERROR. + + If info does not describe a suitable encoding, then the parser will + return an XML_UNKNOWN_ENCODING error. +*/ +typedef int (XMLCALL *XML_UnknownEncodingHandler) ( + void *encodingHandlerData, + const XML_Char *name, + XML_Encoding *info); + +XMLPARSEAPI(void) +XML_SetElementHandler(XML_Parser parser, + XML_StartElementHandler start, + XML_EndElementHandler end); + +XMLPARSEAPI(void) +XML_SetStartElementHandler(XML_Parser parser, + XML_StartElementHandler handler); + +XMLPARSEAPI(void) +XML_SetEndElementHandler(XML_Parser parser, + XML_EndElementHandler handler); + +XMLPARSEAPI(void) +XML_SetCharacterDataHandler(XML_Parser parser, + XML_CharacterDataHandler handler); + +XMLPARSEAPI(void) +XML_SetProcessingInstructionHandler(XML_Parser parser, + XML_ProcessingInstructionHandler handler); +XMLPARSEAPI(void) +XML_SetCommentHandler(XML_Parser parser, + XML_CommentHandler handler); + +XMLPARSEAPI(void) +XML_SetCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start, + XML_EndCdataSectionHandler end); + +XMLPARSEAPI(void) +XML_SetStartCdataSectionHandler(XML_Parser parser, + XML_StartCdataSectionHandler start); + +XMLPARSEAPI(void) +XML_SetEndCdataSectionHandler(XML_Parser parser, + XML_EndCdataSectionHandler end); + +/* This sets the default handler and also inhibits expansion of + internal entities. These entity references will be passed to the + default handler, or to the skipped entity handler, if one is set. +*/ +XMLPARSEAPI(void) +XML_SetDefaultHandler(XML_Parser parser, + XML_DefaultHandler handler); + +/* This sets the default handler but does not inhibit expansion of + internal entities. The entity reference will not be passed to the + default handler. +*/ +XMLPARSEAPI(void) +XML_SetDefaultHandlerExpand(XML_Parser parser, + XML_DefaultHandler handler); + +XMLPARSEAPI(void) +XML_SetDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start, + XML_EndDoctypeDeclHandler end); + +XMLPARSEAPI(void) +XML_SetStartDoctypeDeclHandler(XML_Parser parser, + XML_StartDoctypeDeclHandler start); + +XMLPARSEAPI(void) +XML_SetEndDoctypeDeclHandler(XML_Parser parser, + XML_EndDoctypeDeclHandler end); + +XMLPARSEAPI(void) +XML_SetUnparsedEntityDeclHandler(XML_Parser parser, + XML_UnparsedEntityDeclHandler handler); + +XMLPARSEAPI(void) +XML_SetNotationDeclHandler(XML_Parser parser, + XML_NotationDeclHandler handler); + +XMLPARSEAPI(void) +XML_SetNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start, + XML_EndNamespaceDeclHandler end); + +XMLPARSEAPI(void) +XML_SetStartNamespaceDeclHandler(XML_Parser parser, + XML_StartNamespaceDeclHandler start); + +XMLPARSEAPI(void) +XML_SetEndNamespaceDeclHandler(XML_Parser parser, + XML_EndNamespaceDeclHandler end); + +XMLPARSEAPI(void) +XML_SetNotStandaloneHandler(XML_Parser parser, + XML_NotStandaloneHandler handler); + +XMLPARSEAPI(void) +XML_SetExternalEntityRefHandler(XML_Parser parser, + XML_ExternalEntityRefHandler handler); + +/* If a non-NULL value for arg is specified here, then it will be + passed as the first argument to the external entity ref handler + instead of the parser object. +*/ +XMLPARSEAPI(void) +XML_SetExternalEntityRefHandlerArg(XML_Parser parser, + void *arg); + +XMLPARSEAPI(void) +XML_SetSkippedEntityHandler(XML_Parser parser, + XML_SkippedEntityHandler handler); + +XMLPARSEAPI(void) +XML_SetUnknownEncodingHandler(XML_Parser parser, + XML_UnknownEncodingHandler handler, + void *encodingHandlerData); + +/* This can be called within a handler for a start element, end + element, processing instruction or character data. It causes the + corresponding markup to be passed to the default handler. +*/ +XMLPARSEAPI(void) +XML_DefaultCurrent(XML_Parser parser); + +/* If do_nst is non-zero, and namespace processing is in effect, and + a name has a prefix (i.e. an explicit namespace qualifier) then + that name is returned as a triplet in a single string separated by + the separator character specified when the parser was created: URI + + sep + local_name + sep + prefix. + + If do_nst is zero, then namespace information is returned in the + default manner (URI + sep + local_name) whether or not the name + has a prefix. + + Note: Calling XML_SetReturnNSTriplet after XML_Parse or + XML_ParseBuffer has no effect. +*/ + +XMLPARSEAPI(void) +XML_SetReturnNSTriplet(XML_Parser parser, int do_nst); + +/* This value is passed as the userData argument to callbacks. */ +XMLPARSEAPI(void) +XML_SetUserData(XML_Parser parser, void *userData); + +/* Returns the last value set by XML_SetUserData or NULL. */ +#define XML_GetUserData(parser) (*(void **)(parser)) + +/* This is equivalent to supplying an encoding argument to + XML_ParserCreate. On success XML_SetEncoding returns non-zero, + zero otherwise. + Note: Calling XML_SetEncoding after XML_Parse or XML_ParseBuffer + has no effect and returns XML_STATUS_ERROR. +*/ +XMLPARSEAPI(enum XML_Status) +XML_SetEncoding(XML_Parser parser, const XML_Char *encoding); + +/* If this function is called, then the parser will be passed as the + first argument to callbacks instead of userData. The userData will + still be accessible using XML_GetUserData. +*/ +XMLPARSEAPI(void) +XML_UseParserAsHandlerArg(XML_Parser parser); + +/* If useDTD == XML_TRUE is passed to this function, then the parser + will assume that there is an external subset, even if none is + specified in the document. In such a case the parser will call the + externalEntityRefHandler with a value of NULL for the systemId + argument (the publicId and context arguments will be NULL as well). + Note: For the purpose of checking WFC: Entity Declared, passing + useDTD == XML_TRUE will make the parser behave as if the document + had a DTD with an external subset. + Note: If this function is called, then this must be done before + the first call to XML_Parse or XML_ParseBuffer, since it will + have no effect after that. Returns + XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING. + Note: If the document does not have a DOCTYPE declaration at all, + then startDoctypeDeclHandler and endDoctypeDeclHandler will not + be called, despite an external subset being parsed. + Note: If XML_DTD is not defined when Expat is compiled, returns + XML_ERROR_FEATURE_REQUIRES_XML_DTD. + Note: If parser == NULL, returns XML_ERROR_INVALID_ARGUMENT. +*/ +XMLPARSEAPI(enum XML_Error) +XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD); + + +/* Sets the base to be used for resolving relative URIs in system + identifiers in declarations. Resolving relative identifiers is + left to the application: this value will be passed through as the + base argument to the XML_ExternalEntityRefHandler, + XML_NotationDeclHandler and XML_UnparsedEntityDeclHandler. The base + argument will be copied. Returns XML_STATUS_ERROR if out of memory, + XML_STATUS_OK otherwise. +*/ +XMLPARSEAPI(enum XML_Status) +XML_SetBase(XML_Parser parser, const XML_Char *base); + +XMLPARSEAPI(const XML_Char *) +XML_GetBase(XML_Parser parser); + +/* Returns the number of the attribute/value pairs passed in last call + to the XML_StartElementHandler that were specified in the start-tag + rather than defaulted. Each attribute/value pair counts as 2; thus + this correspondds to an index into the atts array passed to the + XML_StartElementHandler. Returns -1 if parser == NULL. +*/ +XMLPARSEAPI(int) +XML_GetSpecifiedAttributeCount(XML_Parser parser); + +/* Returns the index of the ID attribute passed in the last call to + XML_StartElementHandler, or -1 if there is no ID attribute or + parser == NULL. Each attribute/value pair counts as 2; thus this + correspondds to an index into the atts array passed to the + XML_StartElementHandler. +*/ +XMLPARSEAPI(int) +XML_GetIdAttributeIndex(XML_Parser parser); + +#ifdef XML_ATTR_INFO +/* Source file byte offsets for the start and end of attribute names and values. + The value indices are exclusive of surrounding quotes; thus in a UTF-8 source + file an attribute value of "blah" will yield: + info->valueEnd - info->valueStart = 4 bytes. +*/ +typedef struct { + XML_Index nameStart; /* Offset to beginning of the attribute name. */ + XML_Index nameEnd; /* Offset after the attribute name's last byte. */ + XML_Index valueStart; /* Offset to beginning of the attribute value. */ + XML_Index valueEnd; /* Offset after the attribute value's last byte. */ +} XML_AttrInfo; + +/* Returns an array of XML_AttrInfo structures for the attribute/value pairs + passed in last call to the XML_StartElementHandler that were specified + in the start-tag rather than defaulted. Each attribute/value pair counts + as 1; thus the number of entries in the array is + XML_GetSpecifiedAttributeCount(parser) / 2. +*/ +XMLPARSEAPI(const XML_AttrInfo *) +XML_GetAttributeInfo(XML_Parser parser); +#endif + +/* Parses some input. Returns XML_STATUS_ERROR if a fatal error is + detected. The last call to XML_Parse must have isFinal true; len + may be zero for this call (or any other). + + Though the return values for these functions has always been + described as a Boolean value, the implementation, at least for the + 1.95.x series, has always returned exactly one of the XML_Status + values. +*/ +XMLPARSEAPI(enum XML_Status) +XML_Parse(XML_Parser parser, const char *s, int len, int isFinal); + +XMLPARSEAPI(void *) +XML_GetBuffer(XML_Parser parser, int len); + +XMLPARSEAPI(enum XML_Status) +XML_ParseBuffer(XML_Parser parser, int len, int isFinal); + +/* Stops parsing, causing XML_Parse() or XML_ParseBuffer() to return. + Must be called from within a call-back handler, except when aborting + (resumable = 0) an already suspended parser. Some call-backs may + still follow because they would otherwise get lost. Examples: + - endElementHandler() for empty elements when stopped in + startElementHandler(), + - endNameSpaceDeclHandler() when stopped in endElementHandler(), + and possibly others. + + Can be called from most handlers, including DTD related call-backs, + except when parsing an external parameter entity and resumable != 0. + Returns XML_STATUS_OK when successful, XML_STATUS_ERROR otherwise. + Possible error codes: + - XML_ERROR_SUSPENDED: when suspending an already suspended parser. + - XML_ERROR_FINISHED: when the parser has already finished. + - XML_ERROR_SUSPEND_PE: when suspending while parsing an external PE. + + When resumable != 0 (true) then parsing is suspended, that is, + XML_Parse() and XML_ParseBuffer() return XML_STATUS_SUSPENDED. + Otherwise, parsing is aborted, that is, XML_Parse() and XML_ParseBuffer() + return XML_STATUS_ERROR with error code XML_ERROR_ABORTED. + + *Note*: + This will be applied to the current parser instance only, that is, if + there is a parent parser then it will continue parsing when the + externalEntityRefHandler() returns. It is up to the implementation of + the externalEntityRefHandler() to call XML_StopParser() on the parent + parser (recursively), if one wants to stop parsing altogether. + + When suspended, parsing can be resumed by calling XML_ResumeParser(). +*/ +XMLPARSEAPI(enum XML_Status) +XML_StopParser(XML_Parser parser, XML_Bool resumable); + +/* Resumes parsing after it has been suspended with XML_StopParser(). + Must not be called from within a handler call-back. Returns same + status codes as XML_Parse() or XML_ParseBuffer(). + Additional error code XML_ERROR_NOT_SUSPENDED possible. + + *Note*: + This must be called on the most deeply nested child parser instance + first, and on its parent parser only after the child parser has finished, + to be applied recursively until the document entity's parser is restarted. + That is, the parent parser will not resume by itself and it is up to the + application to call XML_ResumeParser() on it at the appropriate moment. +*/ +XMLPARSEAPI(enum XML_Status) +XML_ResumeParser(XML_Parser parser); + +enum XML_Parsing { + XML_INITIALIZED, + XML_PARSING, + XML_FINISHED, + XML_SUSPENDED +}; + +typedef struct { + enum XML_Parsing parsing; + XML_Bool finalBuffer; +} XML_ParsingStatus; + +/* Returns status of parser with respect to being initialized, parsing, + finished, or suspended and processing the final buffer. + XXX XML_Parse() and XML_ParseBuffer() should return XML_ParsingStatus, + XXX with XML_FINISHED_OK or XML_FINISHED_ERROR replacing XML_FINISHED +*/ +XMLPARSEAPI(void) +XML_GetParsingStatus(XML_Parser parser, XML_ParsingStatus *status); + +/* Creates an XML_Parser object that can parse an external general + entity; context is a '\0'-terminated string specifying the parse + context; encoding is a '\0'-terminated string giving the name of + the externally specified encoding, or NULL if there is no + externally specified encoding. The context string consists of a + sequence of tokens separated by formfeeds (\f); a token consisting + of a name specifies that the general entity of the name is open; a + token of the form prefix=uri specifies the namespace for a + particular prefix; a token of the form =uri specifies the default + namespace. This can be called at any point after the first call to + an ExternalEntityRefHandler so longer as the parser has not yet + been freed. The new parser is completely independent and may + safely be used in a separate thread. The handlers and userData are + initialized from the parser argument. Returns NULL if out of memory. + Otherwise returns a new XML_Parser object. +*/ +XMLPARSEAPI(XML_Parser) +XML_ExternalEntityParserCreate(XML_Parser parser, + const XML_Char *context, + const XML_Char *encoding); + +enum XML_ParamEntityParsing { + XML_PARAM_ENTITY_PARSING_NEVER, + XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE, + XML_PARAM_ENTITY_PARSING_ALWAYS +}; + +/* Controls parsing of parameter entities (including the external DTD + subset). If parsing of parameter entities is enabled, then + references to external parameter entities (including the external + DTD subset) will be passed to the handler set with + XML_SetExternalEntityRefHandler. The context passed will be 0. + + Unlike external general entities, external parameter entities can + only be parsed synchronously. If the external parameter entity is + to be parsed, it must be parsed during the call to the external + entity ref handler: the complete sequence of + XML_ExternalEntityParserCreate, XML_Parse/XML_ParseBuffer and + XML_ParserFree calls must be made during this call. After + XML_ExternalEntityParserCreate has been called to create the parser + for the external parameter entity (context must be 0 for this + call), it is illegal to make any calls on the old parser until + XML_ParserFree has been called on the newly created parser. + If the library has been compiled without support for parameter + entity parsing (ie without XML_DTD being defined), then + XML_SetParamEntityParsing will return 0 if parsing of parameter + entities is requested; otherwise it will return non-zero. + Note: If XML_SetParamEntityParsing is called after XML_Parse or + XML_ParseBuffer, then it has no effect and will always return 0. + Note: If parser == NULL, the function will do nothing and return 0. +*/ +XMLPARSEAPI(int) +XML_SetParamEntityParsing(XML_Parser parser, + enum XML_ParamEntityParsing parsing); + +/* Sets the hash salt to use for internal hash calculations. + Helps in preventing DoS attacks based on predicting hash + function behavior. This must be called before parsing is started. + Returns 1 if successful, 0 when called after parsing has started. + Note: If parser == NULL, the function will do nothing and return 0. +*/ +XMLPARSEAPI(int) +XML_SetHashSalt(XML_Parser parser, + unsigned long hash_salt); + +/* If XML_Parse or XML_ParseBuffer have returned XML_STATUS_ERROR, then + XML_GetErrorCode returns information about the error. +*/ +XMLPARSEAPI(enum XML_Error) +XML_GetErrorCode(XML_Parser parser); + +/* These functions return information about the current parse + location. They may be called from any callback called to report + some parse event; in this case the location is the location of the + first of the sequence of characters that generated the event. When + called from callbacks generated by declarations in the document + prologue, the location identified isn't as neatly defined, but will + be within the relevant markup. When called outside of the callback + functions, the position indicated will be just past the last parse + event (regardless of whether there was an associated callback). + + They may also be called after returning from a call to XML_Parse + or XML_ParseBuffer. If the return value is XML_STATUS_ERROR then + the location is the location of the character at which the error + was detected; otherwise the location is the location of the last + parse event, as described above. + + Note: XML_GetCurrentLineNumber and XML_GetCurrentColumnNumber + return 0 to indicate an error. + Note: XML_GetCurrentByteIndex returns -1 to indicate an error. +*/ +XMLPARSEAPI(XML_Size) XML_GetCurrentLineNumber(XML_Parser parser); +XMLPARSEAPI(XML_Size) XML_GetCurrentColumnNumber(XML_Parser parser); +XMLPARSEAPI(XML_Index) XML_GetCurrentByteIndex(XML_Parser parser); + +/* Return the number of bytes in the current event. + Returns 0 if the event is in an internal entity. +*/ +XMLPARSEAPI(int) +XML_GetCurrentByteCount(XML_Parser parser); + +/* If XML_CONTEXT_BYTES is defined, returns the input buffer, sets + the integer pointed to by offset to the offset within this buffer + of the current parse position, and sets the integer pointed to by size + to the size of this buffer (the number of input bytes). Otherwise + returns a NULL pointer. Also returns a NULL pointer if a parse isn't + active. + + NOTE: The character pointer returned should not be used outside + the handler that makes the call. +*/ +XMLPARSEAPI(const char *) +XML_GetInputContext(XML_Parser parser, + int *offset, + int *size); + +/* For backwards compatibility with previous versions. */ +#define XML_GetErrorLineNumber XML_GetCurrentLineNumber +#define XML_GetErrorColumnNumber XML_GetCurrentColumnNumber +#define XML_GetErrorByteIndex XML_GetCurrentByteIndex + +/* Frees the content model passed to the element declaration handler */ +XMLPARSEAPI(void) +XML_FreeContentModel(XML_Parser parser, XML_Content *model); + +/* Exposing the memory handling functions used in Expat */ +XMLPARSEAPI(void *) +XML_ATTR_MALLOC +XML_ATTR_ALLOC_SIZE(2) +XML_MemMalloc(XML_Parser parser, size_t size); + +XMLPARSEAPI(void *) +XML_ATTR_ALLOC_SIZE(3) +XML_MemRealloc(XML_Parser parser, void *ptr, size_t size); + +XMLPARSEAPI(void) +XML_MemFree(XML_Parser parser, void *ptr); + +/* Frees memory used by the parser. */ +XMLPARSEAPI(void) +XML_ParserFree(XML_Parser parser); + +/* Returns a string describing the error. */ +XMLPARSEAPI(const XML_LChar *) +XML_ErrorString(enum XML_Error code); + +/* Return a string containing the version number of this expat */ +XMLPARSEAPI(const XML_LChar *) +XML_ExpatVersion(void); + +typedef struct { + int major; + int minor; + int micro; +} XML_Expat_Version; + +/* Return an XML_Expat_Version structure containing numeric version + number information for this version of expat. +*/ +XMLPARSEAPI(XML_Expat_Version) +XML_ExpatVersionInfo(void); + +/* Added in Expat 1.95.5. */ +enum XML_FeatureEnum { + XML_FEATURE_END = 0, + XML_FEATURE_UNICODE, + XML_FEATURE_UNICODE_WCHAR_T, + XML_FEATURE_DTD, + XML_FEATURE_CONTEXT_BYTES, + XML_FEATURE_MIN_SIZE, + XML_FEATURE_SIZEOF_XML_CHAR, + XML_FEATURE_SIZEOF_XML_LCHAR, + XML_FEATURE_NS, + XML_FEATURE_LARGE_SIZE, + XML_FEATURE_ATTR_INFO + /* Additional features must be added to the end of this enum. */ +}; + +typedef struct { + enum XML_FeatureEnum feature; + const XML_LChar *name; + long int value; +} XML_Feature; + +XMLPARSEAPI(const XML_Feature *) +XML_GetFeatureList(void); + + +/* Expat follows the semantic versioning convention. + See http://semver.org. +*/ +#define XML_MAJOR_VERSION 2 +#define XML_MINOR_VERSION 2 +#define XML_MICRO_VERSION 5 + +#ifdef __cplusplus +} +#endif + +#endif /* not Expat_INCLUDED */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat_external.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat_external.h new file mode 100644 index 00000000..629483a9 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/expat_external.h @@ -0,0 +1,162 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef Expat_External_INCLUDED +#define Expat_External_INCLUDED 1 + +/* External API definitions */ + +#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__) +# define XML_USE_MSC_EXTENSIONS 1 +#endif + +/* Expat tries very hard to make the API boundary very specifically + defined. There are two macros defined to control this boundary; + each of these can be defined before including this header to + achieve some different behavior, but doing so it not recommended or + tested frequently. + + XMLCALL - The calling convention to use for all calls across the + "library boundary." This will default to cdecl, and + try really hard to tell the compiler that's what we + want. + + XMLIMPORT - Whatever magic is needed to note that a function is + to be imported from a dynamically loaded library + (.dll, .so, or .sl, depending on your platform). + + The XMLCALL macro was added in Expat 1.95.7. The only one which is + expected to be directly useful in client code is XMLCALL. + + Note that on at least some Unix versions, the Expat library must be + compiled with the cdecl calling convention as the default since + system headers may assume the cdecl convention. +*/ +#ifndef XMLCALL +# if defined(_MSC_VER) +# define XMLCALL __cdecl +# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER) +# define XMLCALL __attribute__((cdecl)) +# else +/* For any platform which uses this definition and supports more than + one calling convention, we need to extend this definition to + declare the convention used on that platform, if it's possible to + do so. + + If this is the case for your platform, please file a bug report + with information on how to identify your platform via the C + pre-processor and how to specify the same calling convention as the + platform's malloc() implementation. +*/ +# define XMLCALL +# endif +#endif /* not defined XMLCALL */ + + +#if !defined(XML_STATIC) && !defined(XMLIMPORT) +# ifndef XML_BUILDING_EXPAT +/* using Expat from an application */ + +# ifdef XML_USE_MSC_EXTENSIONS +# define XMLIMPORT __declspec(dllimport) +# endif + +# endif +#endif /* not defined XML_STATIC */ + +#if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4) +# define XMLIMPORT __attribute__ ((visibility ("default"))) +#endif + +/* If we didn't define it above, define it away: */ +#ifndef XMLIMPORT +# define XMLIMPORT +#endif + +#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)) +# define XML_ATTR_MALLOC __attribute__((__malloc__)) +#else +# define XML_ATTR_MALLOC +#endif + +#if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) +# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x))) +#else +# define XML_ATTR_ALLOC_SIZE(x) +#endif + +#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef XML_UNICODE_WCHAR_T +# ifndef XML_UNICODE +# define XML_UNICODE +# endif +# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2) +# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc" +# endif +#endif + +#ifdef XML_UNICODE /* Information is UTF-16 encoded. */ +# ifdef XML_UNICODE_WCHAR_T +typedef wchar_t XML_Char; +typedef wchar_t XML_LChar; +# else +typedef unsigned short XML_Char; +typedef char XML_LChar; +# endif /* XML_UNICODE_WCHAR_T */ +#else /* Information is UTF-8 encoded. */ +typedef char XML_Char; +typedef char XML_LChar; +#endif /* XML_UNICODE */ + +#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */ +# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400 +typedef __int64 XML_Index; +typedef unsigned __int64 XML_Size; +# else +typedef long long XML_Index; +typedef unsigned long long XML_Size; +# endif +#else +typedef long XML_Index; +typedef unsigned long XML_Size; +#endif /* XML_LARGE_SIZE */ + +#ifdef __cplusplus +} +#endif + +#endif /* not Expat_External_INCLUDED */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/iasciitab.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/iasciitab.h new file mode 100644 index 00000000..ce4a4bf7 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/iasciitab.h @@ -0,0 +1,65 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */ +/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x04 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x08 */ BT_NONXML, BT_S, BT_LF, BT_NONXML, +/* 0x0C */ BT_NONXML, BT_S, BT_NONXML, BT_NONXML, +/* 0x10 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x14 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x18 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x1C */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0x20 */ BT_S, BT_EXCL, BT_QUOT, BT_NUM, +/* 0x24 */ BT_OTHER, BT_PERCNT, BT_AMP, BT_APOS, +/* 0x28 */ BT_LPAR, BT_RPAR, BT_AST, BT_PLUS, +/* 0x2C */ BT_COMMA, BT_MINUS, BT_NAME, BT_SOL, +/* 0x30 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x34 */ BT_DIGIT, BT_DIGIT, BT_DIGIT, BT_DIGIT, +/* 0x38 */ BT_DIGIT, BT_DIGIT, BT_COLON, BT_SEMI, +/* 0x3C */ BT_LT, BT_EQUALS, BT_GT, BT_QUEST, +/* 0x40 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x44 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x48 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x4C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x50 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x54 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x58 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_LSQB, +/* 0x5C */ BT_OTHER, BT_RSQB, BT_OTHER, BT_NMSTRT, +/* 0x60 */ BT_OTHER, BT_HEX, BT_HEX, BT_HEX, +/* 0x64 */ BT_HEX, BT_HEX, BT_HEX, BT_NMSTRT, +/* 0x68 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x6C */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x70 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x74 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0x78 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0x7C */ BT_VERBAR, BT_OTHER, BT_OTHER, BT_OTHER, diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/internal.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/internal.h new file mode 100644 index 00000000..e33fdcb0 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/internal.h @@ -0,0 +1,124 @@ +/* internal.h + + Internal definitions used by Expat. This is not needed to compile + client code. + + The following calling convention macros are defined for frequently + called functions: + + FASTCALL - Used for those internal functions that have a simple + body and a low number of arguments and local variables. + + PTRCALL - Used for functions called though function pointers. + + PTRFASTCALL - Like PTRCALL, but for low number of arguments. + + inline - Used for selected internal functions for which inlining + may improve performance on some platforms. + + Note: Use of these macros is based on judgement, not hard rules, + and therefore subject to change. + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__) +/* We'll use this version by default only where we know it helps. + + regparm() generates warnings on Solaris boxes. See SF bug #692878. + + Instability reported with egcs on a RedHat Linux 7.3. + Let's comment out: + #define FASTCALL __attribute__((stdcall, regparm(3))) + and let's try this: +*/ +#define FASTCALL __attribute__((regparm(3))) +#define PTRFASTCALL __attribute__((regparm(3))) +#endif + +/* Using __fastcall seems to have an unexpected negative effect under + MS VC++, especially for function pointers, so we won't use it for + now on that platform. It may be reconsidered for a future release + if it can be made more effective. + Likely reason: __fastcall on Windows is like stdcall, therefore + the compiler cannot perform stack optimizations for call clusters. +*/ + +/* Make sure all of these are defined if they aren't already. */ + +#ifndef FASTCALL +#define FASTCALL +#endif + +#ifndef PTRCALL +#define PTRCALL +#endif + +#ifndef PTRFASTCALL +#define PTRFASTCALL +#endif + +#ifndef XML_MIN_SIZE +#if !defined(__cplusplus) && !defined(inline) +#ifdef __GNUC__ +#define inline __inline +#endif /* __GNUC__ */ +#endif +#endif /* XML_MIN_SIZE */ + +#ifdef __cplusplus +#define inline inline +#else +#ifndef inline +#define inline +#endif +#endif + +#ifndef UNUSED_P +# ifdef __GNUC__ +# define UNUSED_P(p) UNUSED_ ## p __attribute__((__unused__)) +# else +# define UNUSED_P(p) UNUSED_ ## p +# endif +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + +void +_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/latin1tab.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/latin1tab.h new file mode 100644 index 00000000..95dfa52b --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/latin1tab.h @@ -0,0 +1,64 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x84 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x88 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x8C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x90 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x94 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x98 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0x9C */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA4 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xA8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, +/* 0xAC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xB0 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xB4 */ BT_OTHER, BT_NMSTRT, BT_OTHER, BT_NAME, +/* 0xB8 */ BT_OTHER, BT_OTHER, BT_NMSTRT, BT_OTHER, +/* 0xBC */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER, +/* 0xC0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xC4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xC8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xCC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xD0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xD4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0xD8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xDC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xE8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xEC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xF0 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xF4 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_OTHER, +/* 0xF8 */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, +/* 0xFC */ BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, BT_NMSTRT, diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/nametab.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/nametab.h new file mode 100644 index 00000000..bfa2bd38 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/nametab.h @@ -0,0 +1,182 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +static const unsigned namingBitmap[] = { +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0x00000000, 0x04000000, 0x87FFFFFE, 0x07FFFFFE, +0x00000000, 0x00000000, 0xFF7FFFFF, 0xFF7FFFFF, +0xFFFFFFFF, 0x7FF3FFFF, 0xFFFFFDFE, 0x7FFFFFFF, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFE00F, 0xFC31FFFF, +0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, +0xFFFFFFFF, 0xF80001FF, 0x00000003, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFD740, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, +0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, +0xFFFF0003, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, +0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, +0x0000007F, 0x00000000, 0xFFFF0000, 0x000707FF, +0x00000000, 0x07FFFFFE, 0x000007FE, 0xFFFE0000, +0xFFFFFFFF, 0x7CFFFFFF, 0x002F7FFF, 0x00000060, +0xFFFFFFE0, 0x23FFFFFF, 0xFF000000, 0x00000003, +0xFFF99FE0, 0x03C5FDFF, 0xB0000000, 0x00030003, +0xFFF987E0, 0x036DFDFF, 0x5E000000, 0x001C0000, +0xFFFBAFE0, 0x23EDFDFF, 0x00000000, 0x00000001, +0xFFF99FE0, 0x23CDFDFF, 0xB0000000, 0x00000003, +0xD63DC7E0, 0x03BFC718, 0x00000000, 0x00000000, +0xFFFDDFE0, 0x03EFFDFF, 0x00000000, 0x00000003, +0xFFFDDFE0, 0x03EFFDFF, 0x40000000, 0x00000003, +0xFFFDDFE0, 0x03FFFDFF, 0x00000000, 0x00000003, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFE, 0x000D7FFF, 0x0000003F, 0x00000000, +0xFEF02596, 0x200D6CAE, 0x0000001F, 0x00000000, +0x00000000, 0x00000000, 0xFFFFFEFF, 0x000003FF, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0xFFFFFFFF, 0xFFFF003F, 0x007FFFFF, +0x0007DAED, 0x50000000, 0x82315001, 0x002C62AB, +0x40000000, 0xF580C900, 0x00000007, 0x02010800, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0x0FFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x03FFFFFF, +0x3F3FFFFF, 0xFFFFFFFF, 0xAAFF3F3F, 0x3FFFFFFF, +0xFFFFFFFF, 0x5FDFFFFF, 0x0FCF1FDC, 0x1FDC1FFF, +0x00000000, 0x00004C40, 0x00000000, 0x00000000, +0x00000007, 0x00000000, 0x00000000, 0x00000000, +0x00000080, 0x000003FE, 0xFFFFFFFE, 0xFFFFFFFF, +0x001FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x07FFFFFF, +0xFFFFFFE0, 0x00001FFF, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0x0000003F, 0x00000000, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, +0xFFFFFFFF, 0x0000000F, 0x00000000, 0x00000000, +0x00000000, 0x07FF6000, 0x87FFFFFE, 0x07FFFFFE, +0x00000000, 0x00800000, 0xFF7FFFFF, 0xFF7FFFFF, +0x00FFFFFF, 0x00000000, 0xFFFF0000, 0xFFFFFFFF, +0xFFFFFFFF, 0xF80001FF, 0x00030003, 0x00000000, +0xFFFFFFFF, 0xFFFFFFFF, 0x0000003F, 0x00000003, +0xFFFFD7C0, 0xFFFFFFFB, 0x547F7FFF, 0x000FFFFD, +0xFFFFDFFE, 0xFFFFFFFF, 0xDFFEFFFF, 0xFFFFFFFF, +0xFFFF007B, 0xFFFFFFFF, 0xFFFF199F, 0x033FCFFF, +0x00000000, 0xFFFE0000, 0x027FFFFF, 0xFFFFFFFE, +0xFFFE007F, 0xBBFFFFFB, 0xFFFF0016, 0x000707FF, +0x00000000, 0x07FFFFFE, 0x0007FFFF, 0xFFFF03FF, +0xFFFFFFFF, 0x7CFFFFFF, 0xFFEF7FFF, 0x03FF3DFF, +0xFFFFFFEE, 0xF3FFFFFF, 0xFF1E3FFF, 0x0000FFCF, +0xFFF99FEE, 0xD3C5FDFF, 0xB080399F, 0x0003FFCF, +0xFFF987E4, 0xD36DFDFF, 0x5E003987, 0x001FFFC0, +0xFFFBAFEE, 0xF3EDFDFF, 0x00003BBF, 0x0000FFC1, +0xFFF99FEE, 0xF3CDFDFF, 0xB0C0398F, 0x0000FFC3, +0xD63DC7EC, 0xC3BFC718, 0x00803DC7, 0x0000FF80, +0xFFFDDFEE, 0xC3EFFDFF, 0x00603DDF, 0x0000FFC3, +0xFFFDDFEC, 0xC3EFFDFF, 0x40603DDF, 0x0000FFC3, +0xFFFDDFEC, 0xC3FFFDFF, 0x00803DCF, 0x0000FFC3, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0xFFFFFFFE, 0x07FF7FFF, 0x03FF7FFF, 0x00000000, +0xFEF02596, 0x3BFF6CAE, 0x03FF3F5F, 0x00000000, +0x03000000, 0xC2A003FF, 0xFFFFFEFF, 0xFFFE03FF, +0xFEBF0FDF, 0x02FE3FFF, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x00000000, 0x00000000, +0x00000000, 0x00000000, 0x1FFF0000, 0x00000002, +0x000000A0, 0x003EFFFE, 0xFFFFFFFE, 0xFFFFFFFF, +0x661FFFFF, 0xFFFFFFFE, 0xFFFFFFFF, 0x77FFFFFF, +}; +static const unsigned char nmstrtPages[] = { +0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x00, +0x00, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, +0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, +0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x15, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; +static const unsigned char namePages[] = { +0x19, 0x03, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x00, +0x00, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, +0x10, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x13, +0x26, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x27, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x17, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, +0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x18, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/siphash.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/siphash.h new file mode 100644 index 00000000..581872df --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/siphash.h @@ -0,0 +1,374 @@ +/* ========================================================================== + * siphash.h - SipHash-2-4 in a single header file + * -------------------------------------------------------------------------- + * Derived by William Ahern from the reference implementation[1] published[2] + * by Jean-Philippe Aumasson and Daniel J. Berstein. + * Minimal changes by Sebastian Pipping and Victor Stinner on top, see below. + * Licensed under the CC0 Public Domain Dedication license. + * + * 1. https://www.131002.net/siphash/siphash24.c + * 2. https://www.131002.net/siphash/ + * -------------------------------------------------------------------------- + * HISTORY: + * + * 2017-07-25 (Vadim Zeitlin) + * - Fix use of SIPHASH_MAIN macro + * + * 2017-07-05 (Sebastian Pipping) + * - Use _SIP_ULL macro to not require a C++11 compiler if compiled as C++ + * - Add const qualifiers at two places + * - Ensure <=80 characters line length (assuming tab width 4) + * + * 2017-06-23 (Victor Stinner) + * - Address Win64 compile warnings + * + * 2017-06-18 (Sebastian Pipping) + * - Clarify license note in the header + * - Address C89 issues: + * - Stop using inline keyword (and let compiler decide) + * - Replace _Bool by int + * - Turn macro siphash24 into a function + * - Address invalid conversion (void pointer) by explicit cast + * - Address lack of stdint.h for Visual Studio 2003 to 2008 + * - Always expose sip24_valid (for self-tests) + * + * 2012-11-04 - Born. (William Ahern) + * -------------------------------------------------------------------------- + * USAGE: + * + * SipHash-2-4 takes as input two 64-bit words as the key, some number of + * message bytes, and outputs a 64-bit word as the message digest. This + * implementation employs two data structures: a struct sipkey for + * representing the key, and a struct siphash for representing the hash + * state. + * + * For converting a 16-byte unsigned char array to a key, use either the + * macro sip_keyof or the routine sip_tokey. The former instantiates a + * compound literal key, while the latter requires a key object as a + * parameter. + * + * unsigned char secret[16]; + * arc4random_buf(secret, sizeof secret); + * struct sipkey *key = sip_keyof(secret); + * + * For hashing a message, use either the convenience macro siphash24 or the + * routines sip24_init, sip24_update, and sip24_final. + * + * struct siphash state; + * void *msg; + * size_t len; + * uint64_t hash; + * + * sip24_init(&state, key); + * sip24_update(&state, msg, len); + * hash = sip24_final(&state); + * + * or + * + * hash = siphash24(msg, len, key); + * + * To convert the 64-bit hash value to a canonical 8-byte little-endian + * binary representation, use either the macro sip_binof or the routine + * sip_tobin. The former instantiates and returns a compound literal array, + * while the latter requires an array object as a parameter. + * -------------------------------------------------------------------------- + * NOTES: + * + * o Neither sip_keyof, sip_binof, nor siphash24 will work with compilers + * lacking compound literal support. Instead, you must use the lower-level + * interfaces which take as parameters the temporary state objects. + * + * o Uppercase macros may evaluate parameters more than once. Lowercase + * macros should not exhibit any such side effects. + * ========================================================================== + */ +#ifndef SIPHASH_H +#define SIPHASH_H + +#include /* size_t */ + +#if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600) + /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */ + typedef unsigned __int8 uint8_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; +#else + #include /* uint64_t uint32_t uint8_t */ +#endif + + +/* + * Workaround to not require a C++11 compiler for using ULL suffix + * if this code is included and compiled as C++; related GCC warning is: + * warning: use of C++11 long long integer constant [-Wlong-long] + */ +#define _SIP_ULL(high, low) (((uint64_t)high << 32) | low) + + +#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ( (x) >> (64 - (b)))) + +#define SIP_U32TO8_LE(p, v) \ + (p)[0] = (uint8_t)((v) >> 0); (p)[1] = (uint8_t)((v) >> 8); \ + (p)[2] = (uint8_t)((v) >> 16); (p)[3] = (uint8_t)((v) >> 24); + +#define SIP_U64TO8_LE(p, v) \ + SIP_U32TO8_LE((p) + 0, (uint32_t)((v) >> 0)); \ + SIP_U32TO8_LE((p) + 4, (uint32_t)((v) >> 32)); + +#define SIP_U8TO64_LE(p) \ + (((uint64_t)((p)[0]) << 0) | \ + ((uint64_t)((p)[1]) << 8) | \ + ((uint64_t)((p)[2]) << 16) | \ + ((uint64_t)((p)[3]) << 24) | \ + ((uint64_t)((p)[4]) << 32) | \ + ((uint64_t)((p)[5]) << 40) | \ + ((uint64_t)((p)[6]) << 48) | \ + ((uint64_t)((p)[7]) << 56)) + + +#define SIPHASH_INITIALIZER { 0, 0, 0, 0, { 0 }, 0, 0 } + +struct siphash { + uint64_t v0, v1, v2, v3; + + unsigned char buf[8], *p; + uint64_t c; +}; /* struct siphash */ + + +#define SIP_KEYLEN 16 + +struct sipkey { + uint64_t k[2]; +}; /* struct sipkey */ + +#define sip_keyof(k) sip_tokey(&(struct sipkey){ { 0 } }, (k)) + +static struct sipkey *sip_tokey(struct sipkey *key, const void *src) { + key->k[0] = SIP_U8TO64_LE((const unsigned char *)src); + key->k[1] = SIP_U8TO64_LE((const unsigned char *)src + 8); + return key; +} /* sip_tokey() */ + + +#define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v)) + +static void *sip_tobin(void *dst, uint64_t u64) { + SIP_U64TO8_LE((unsigned char *)dst, u64); + return dst; +} /* sip_tobin() */ + + +static void sip_round(struct siphash *H, const int rounds) { + int i; + + for (i = 0; i < rounds; i++) { + H->v0 += H->v1; + H->v1 = SIP_ROTL(H->v1, 13); + H->v1 ^= H->v0; + H->v0 = SIP_ROTL(H->v0, 32); + + H->v2 += H->v3; + H->v3 = SIP_ROTL(H->v3, 16); + H->v3 ^= H->v2; + + H->v0 += H->v3; + H->v3 = SIP_ROTL(H->v3, 21); + H->v3 ^= H->v0; + + H->v2 += H->v1; + H->v1 = SIP_ROTL(H->v1, 17); + H->v1 ^= H->v2; + H->v2 = SIP_ROTL(H->v2, 32); + } +} /* sip_round() */ + + +static struct siphash *sip24_init(struct siphash *H, + const struct sipkey *key) { + H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0]; + H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1]; + H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0]; + H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1]; + + H->p = H->buf; + H->c = 0; + + return H; +} /* sip24_init() */ + + +#define sip_endof(a) (&(a)[sizeof (a) / sizeof *(a)]) + +static struct siphash *sip24_update(struct siphash *H, const void *src, + size_t len) { + const unsigned char *p = (const unsigned char *)src, *pe = p + len; + uint64_t m; + + do { + while (p < pe && H->p < sip_endof(H->buf)) + *H->p++ = *p++; + + if (H->p < sip_endof(H->buf)) + break; + + m = SIP_U8TO64_LE(H->buf); + H->v3 ^= m; + sip_round(H, 2); + H->v0 ^= m; + + H->p = H->buf; + H->c += 8; + } while (p < pe); + + return H; +} /* sip24_update() */ + + +static uint64_t sip24_final(struct siphash *H) { + const char left = (char)(H->p - H->buf); + uint64_t b = (H->c + left) << 56; + + switch (left) { + case 7: b |= (uint64_t)H->buf[6] << 48; + case 6: b |= (uint64_t)H->buf[5] << 40; + case 5: b |= (uint64_t)H->buf[4] << 32; + case 4: b |= (uint64_t)H->buf[3] << 24; + case 3: b |= (uint64_t)H->buf[2] << 16; + case 2: b |= (uint64_t)H->buf[1] << 8; + case 1: b |= (uint64_t)H->buf[0] << 0; + case 0: break; + } + + H->v3 ^= b; + sip_round(H, 2); + H->v0 ^= b; + H->v2 ^= 0xff; + sip_round(H, 4); + + return H->v0 ^ H->v1 ^ H->v2 ^ H->v3; +} /* sip24_final() */ + + +static uint64_t siphash24(const void *src, size_t len, + const struct sipkey *key) { + struct siphash state = SIPHASH_INITIALIZER; + return sip24_final(sip24_update(sip24_init(&state, key), src, len)); +} /* siphash24() */ + + +/* + * SipHash-2-4 output with + * k = 00 01 02 ... + * and + * in = (empty string) + * in = 00 (1 byte) + * in = 00 01 (2 bytes) + * in = 00 01 02 (3 bytes) + * ... + * in = 00 01 02 ... 3e (63 bytes) + */ +static int sip24_valid(void) { + static const unsigned char vectors[64][8] = { + { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, + { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, + { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, }, + { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, }, + { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, }, + { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, }, + { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, }, + { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, }, + { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, }, + { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, }, + { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, }, + { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, }, + { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, }, + { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, }, + { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, }, + { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, }, + { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, }, + { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, }, + { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, }, + { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, }, + { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, }, + { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, }, + { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, }, + { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, }, + { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, }, + { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, }, + { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, }, + { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, }, + { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, }, + { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, }, + { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, }, + { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, }, + { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, }, + { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, }, + { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, }, + { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, }, + { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, }, + { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, }, + { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, }, + { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, }, + { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, }, + { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, }, + { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, }, + { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, }, + { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, }, + { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, }, + { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, }, + { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, }, + { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, }, + { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, }, + { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, }, + { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, }, + { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, }, + { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, }, + { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, }, + { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, }, + { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, }, + { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, }, + { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, }, + { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, }, + { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, }, + { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, }, + { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, + { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } + }; + unsigned char in[64]; + struct sipkey k; + size_t i; + + sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011" + "\012\013\014\015\016\017"); + + for (i = 0; i < sizeof in; ++i) { + in[i] = (unsigned char)i; + + if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i])) + return 0; + } + + return 1; +} /* sip24_valid() */ + + +#ifdef SIPHASH_MAIN + +#include + +int main(void) { + const int ok = sip24_valid(); + + if (ok) + puts("OK"); + else + puts("FAIL"); + + return !ok; +} /* main() */ + +#endif /* SIPHASH_MAIN */ + + +#endif /* SIPHASH_H */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/utf8tab.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/utf8tab.h new file mode 100644 index 00000000..fa0bed6f --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/utf8tab.h @@ -0,0 +1,64 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +/* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x88 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x8C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x90 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x94 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x98 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0x9C */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xA8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xAC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB0 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB4 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xB8 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xBC */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL, +/* 0xC0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xC4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xC8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xCC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD0 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD4 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xD8 */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xDC */ BT_LEAD2, BT_LEAD2, BT_LEAD2, BT_LEAD2, +/* 0xE0 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xE4 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xE8 */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xEC */ BT_LEAD3, BT_LEAD3, BT_LEAD3, BT_LEAD3, +/* 0xF0 */ BT_LEAD4, BT_LEAD4, BT_LEAD4, BT_LEAD4, +/* 0xF4 */ BT_LEAD4, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0xF8 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML, +/* 0xFC */ BT_NONXML, BT_NONXML, BT_MALFORM, BT_MALFORM, diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/winconfig.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/winconfig.h new file mode 100644 index 00000000..17fea468 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/winconfig.h @@ -0,0 +1,63 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef WINCONFIG_H +#define WINCONFIG_H + +#define WIN32_LEAN_AND_MEAN +#include +#undef WIN32_LEAN_AND_MEAN + +#include +#include + + +#if defined(HAVE_EXPAT_CONFIG_H) /* e.g. MinGW */ +# include +#else /* !defined(HAVE_EXPAT_CONFIG_H) */ + + +#define XML_NS 1 +#define XML_DTD 1 +#define XML_CONTEXT_BYTES 1024 + +/* we will assume all Windows platforms are little endian */ +#define BYTEORDER 1234 + +/* Windows has memmove() available. */ +#define HAVE_MEMMOVE + + +#endif /* !defined(HAVE_EXPAT_CONFIG_H) */ + + +#endif /* ndef WINCONFIG_H */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmlrole.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmlrole.h new file mode 100644 index 00000000..e5f048ea --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmlrole.h @@ -0,0 +1,142 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef XmlRole_INCLUDED +#define XmlRole_INCLUDED 1 + +#ifdef __VMS +/* 0 1 2 3 0 1 2 3 + 1234567890123456789012345678901 1234567890123456789012345678901 */ +#define XmlPrologStateInitExternalEntity XmlPrologStateInitExternalEnt +#endif + +#include "xmltok.h" + +#ifdef __cplusplus +extern "C" { +#endif + +enum { + XML_ROLE_ERROR = -1, + XML_ROLE_NONE = 0, + XML_ROLE_XML_DECL, + XML_ROLE_INSTANCE_START, + XML_ROLE_DOCTYPE_NONE, + XML_ROLE_DOCTYPE_NAME, + XML_ROLE_DOCTYPE_SYSTEM_ID, + XML_ROLE_DOCTYPE_PUBLIC_ID, + XML_ROLE_DOCTYPE_INTERNAL_SUBSET, + XML_ROLE_DOCTYPE_CLOSE, + XML_ROLE_GENERAL_ENTITY_NAME, + XML_ROLE_PARAM_ENTITY_NAME, + XML_ROLE_ENTITY_NONE, + XML_ROLE_ENTITY_VALUE, + XML_ROLE_ENTITY_SYSTEM_ID, + XML_ROLE_ENTITY_PUBLIC_ID, + XML_ROLE_ENTITY_COMPLETE, + XML_ROLE_ENTITY_NOTATION_NAME, + XML_ROLE_NOTATION_NONE, + XML_ROLE_NOTATION_NAME, + XML_ROLE_NOTATION_SYSTEM_ID, + XML_ROLE_NOTATION_NO_SYSTEM_ID, + XML_ROLE_NOTATION_PUBLIC_ID, + XML_ROLE_ATTRIBUTE_NAME, + XML_ROLE_ATTRIBUTE_TYPE_CDATA, + XML_ROLE_ATTRIBUTE_TYPE_ID, + XML_ROLE_ATTRIBUTE_TYPE_IDREF, + XML_ROLE_ATTRIBUTE_TYPE_IDREFS, + XML_ROLE_ATTRIBUTE_TYPE_ENTITY, + XML_ROLE_ATTRIBUTE_TYPE_ENTITIES, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN, + XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS, + XML_ROLE_ATTRIBUTE_ENUM_VALUE, + XML_ROLE_ATTRIBUTE_NOTATION_VALUE, + XML_ROLE_ATTLIST_NONE, + XML_ROLE_ATTLIST_ELEMENT_NAME, + XML_ROLE_IMPLIED_ATTRIBUTE_VALUE, + XML_ROLE_REQUIRED_ATTRIBUTE_VALUE, + XML_ROLE_DEFAULT_ATTRIBUTE_VALUE, + XML_ROLE_FIXED_ATTRIBUTE_VALUE, + XML_ROLE_ELEMENT_NONE, + XML_ROLE_ELEMENT_NAME, + XML_ROLE_CONTENT_ANY, + XML_ROLE_CONTENT_EMPTY, + XML_ROLE_CONTENT_PCDATA, + XML_ROLE_GROUP_OPEN, + XML_ROLE_GROUP_CLOSE, + XML_ROLE_GROUP_CLOSE_REP, + XML_ROLE_GROUP_CLOSE_OPT, + XML_ROLE_GROUP_CLOSE_PLUS, + XML_ROLE_GROUP_CHOICE, + XML_ROLE_GROUP_SEQUENCE, + XML_ROLE_CONTENT_ELEMENT, + XML_ROLE_CONTENT_ELEMENT_REP, + XML_ROLE_CONTENT_ELEMENT_OPT, + XML_ROLE_CONTENT_ELEMENT_PLUS, + XML_ROLE_PI, + XML_ROLE_COMMENT, +#ifdef XML_DTD + XML_ROLE_TEXT_DECL, + XML_ROLE_IGNORE_SECT, + XML_ROLE_INNER_PARAM_ENTITY_REF, +#endif /* XML_DTD */ + XML_ROLE_PARAM_ENTITY_REF +}; + +typedef struct prolog_state { + int (PTRCALL *handler) (struct prolog_state *state, + int tok, + const char *ptr, + const char *end, + const ENCODING *enc); + unsigned level; + int role_none; +#ifdef XML_DTD + unsigned includeLevel; + int documentEntity; + int inEntityValue; +#endif /* XML_DTD */ +} PROLOG_STATE; + +void XmlPrologStateInit(PROLOG_STATE *); +#ifdef XML_DTD +void XmlPrologStateInitExternalEntity(PROLOG_STATE *); +#endif /* XML_DTD */ + +#define XmlTokenRole(state, tok, ptr, end, enc) \ + (((state)->handler)(state, tok, ptr, end, enc)) + +#ifdef __cplusplus +} +#endif + +#endif /* not XmlRole_INCLUDED */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok.h new file mode 100644 index 00000000..50926f38 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok.h @@ -0,0 +1,345 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +#ifndef XmlTok_INCLUDED +#define XmlTok_INCLUDED 1 + +#ifdef __cplusplus +extern "C" { +#endif + +/* The following token may be returned by XmlContentTok */ +#define XML_TOK_TRAILING_RSQB -5 /* ] or ]] at the end of the scan; might be + start of illegal ]]> sequence */ +/* The following tokens may be returned by both XmlPrologTok and + XmlContentTok. +*/ +#define XML_TOK_NONE -4 /* The string to be scanned is empty */ +#define XML_TOK_TRAILING_CR -3 /* A CR at the end of the scan; + might be part of CRLF sequence */ +#define XML_TOK_PARTIAL_CHAR -2 /* only part of a multibyte sequence */ +#define XML_TOK_PARTIAL -1 /* only part of a token */ +#define XML_TOK_INVALID 0 + +/* The following tokens are returned by XmlContentTok; some are also + returned by XmlAttributeValueTok, XmlEntityTok, XmlCdataSectionTok. +*/ +#define XML_TOK_START_TAG_WITH_ATTS 1 +#define XML_TOK_START_TAG_NO_ATTS 2 +#define XML_TOK_EMPTY_ELEMENT_WITH_ATTS 3 /* empty element tag */ +#define XML_TOK_EMPTY_ELEMENT_NO_ATTS 4 +#define XML_TOK_END_TAG 5 +#define XML_TOK_DATA_CHARS 6 +#define XML_TOK_DATA_NEWLINE 7 +#define XML_TOK_CDATA_SECT_OPEN 8 +#define XML_TOK_ENTITY_REF 9 +#define XML_TOK_CHAR_REF 10 /* numeric character reference */ + +/* The following tokens may be returned by both XmlPrologTok and + XmlContentTok. +*/ +#define XML_TOK_PI 11 /* processing instruction */ +#define XML_TOK_XML_DECL 12 /* XML decl or text decl */ +#define XML_TOK_COMMENT 13 +#define XML_TOK_BOM 14 /* Byte order mark */ + +/* The following tokens are returned only by XmlPrologTok */ +#define XML_TOK_PROLOG_S 15 +#define XML_TOK_DECL_OPEN 16 /* */ +#define XML_TOK_NAME 18 +#define XML_TOK_NMTOKEN 19 +#define XML_TOK_POUND_NAME 20 /* #name */ +#define XML_TOK_OR 21 /* | */ +#define XML_TOK_PERCENT 22 +#define XML_TOK_OPEN_PAREN 23 +#define XML_TOK_CLOSE_PAREN 24 +#define XML_TOK_OPEN_BRACKET 25 +#define XML_TOK_CLOSE_BRACKET 26 +#define XML_TOK_LITERAL 27 +#define XML_TOK_PARAM_ENTITY_REF 28 +#define XML_TOK_INSTANCE_START 29 + +/* The following occur only in element type declarations */ +#define XML_TOK_NAME_QUESTION 30 /* name? */ +#define XML_TOK_NAME_ASTERISK 31 /* name* */ +#define XML_TOK_NAME_PLUS 32 /* name+ */ +#define XML_TOK_COND_SECT_OPEN 33 /* */ +#define XML_TOK_CLOSE_PAREN_QUESTION 35 /* )? */ +#define XML_TOK_CLOSE_PAREN_ASTERISK 36 /* )* */ +#define XML_TOK_CLOSE_PAREN_PLUS 37 /* )+ */ +#define XML_TOK_COMMA 38 + +/* The following token is returned only by XmlAttributeValueTok */ +#define XML_TOK_ATTRIBUTE_VALUE_S 39 + +/* The following token is returned only by XmlCdataSectionTok */ +#define XML_TOK_CDATA_SECT_CLOSE 40 + +/* With namespace processing this is returned by XmlPrologTok for a + name with a colon. +*/ +#define XML_TOK_PREFIXED_NAME 41 + +#ifdef XML_DTD +#define XML_TOK_IGNORE_SECT 42 +#endif /* XML_DTD */ + +#ifdef XML_DTD +#define XML_N_STATES 4 +#else /* not XML_DTD */ +#define XML_N_STATES 3 +#endif /* not XML_DTD */ + +#define XML_PROLOG_STATE 0 +#define XML_CONTENT_STATE 1 +#define XML_CDATA_SECTION_STATE 2 +#ifdef XML_DTD +#define XML_IGNORE_SECTION_STATE 3 +#endif /* XML_DTD */ + +#define XML_N_LITERAL_TYPES 2 +#define XML_ATTRIBUTE_VALUE_LITERAL 0 +#define XML_ENTITY_VALUE_LITERAL 1 + +/* The size of the buffer passed to XmlUtf8Encode must be at least this. */ +#define XML_UTF8_ENCODE_MAX 4 +/* The size of the buffer passed to XmlUtf16Encode must be at least this. */ +#define XML_UTF16_ENCODE_MAX 2 + +typedef struct position { + /* first line and first column are 0 not 1 */ + XML_Size lineNumber; + XML_Size columnNumber; +} POSITION; + +typedef struct { + const char *name; + const char *valuePtr; + const char *valueEnd; + char normalized; +} ATTRIBUTE; + +struct encoding; +typedef struct encoding ENCODING; + +typedef int (PTRCALL *SCANNER)(const ENCODING *, + const char *, + const char *, + const char **); + +enum XML_Convert_Result { + XML_CONVERT_COMPLETED = 0, + XML_CONVERT_INPUT_INCOMPLETE = 1, + XML_CONVERT_OUTPUT_EXHAUSTED = 2 /* and therefore potentially input remaining as well */ +}; + +struct encoding { + SCANNER scanners[XML_N_STATES]; + SCANNER literalScanners[XML_N_LITERAL_TYPES]; + int (PTRCALL *nameMatchesAscii)(const ENCODING *, + const char *, + const char *, + const char *); + int (PTRFASTCALL *nameLength)(const ENCODING *, const char *); + const char *(PTRFASTCALL *skipS)(const ENCODING *, const char *); + int (PTRCALL *getAtts)(const ENCODING *enc, + const char *ptr, + int attsMax, + ATTRIBUTE *atts); + int (PTRFASTCALL *charRefNumber)(const ENCODING *enc, const char *ptr); + int (PTRCALL *predefinedEntityName)(const ENCODING *, + const char *, + const char *); + void (PTRCALL *updatePosition)(const ENCODING *, + const char *ptr, + const char *end, + POSITION *); + int (PTRCALL *isPublicId)(const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr); + enum XML_Convert_Result (PTRCALL *utf8Convert)(const ENCODING *enc, + const char **fromP, + const char *fromLim, + char **toP, + const char *toLim); + enum XML_Convert_Result (PTRCALL *utf16Convert)(const ENCODING *enc, + const char **fromP, + const char *fromLim, + unsigned short **toP, + const unsigned short *toLim); + int minBytesPerChar; + char isUtf8; + char isUtf16; +}; + +/* Scan the string starting at ptr until the end of the next complete + token, but do not scan past eptr. Return an integer giving the + type of token. + + Return XML_TOK_NONE when ptr == eptr; nextTokPtr will not be set. + + Return XML_TOK_PARTIAL when the string does not contain a complete + token; nextTokPtr will not be set. + + Return XML_TOK_INVALID when the string does not start a valid + token; nextTokPtr will be set to point to the character which made + the token invalid. + + Otherwise the string starts with a valid token; nextTokPtr will be + set to point to the character following the end of that token. + + Each data character counts as a single token, but adjacent data + characters may be returned together. Similarly for characters in + the prolog outside literals, comments and processing instructions. +*/ + + +#define XmlTok(enc, state, ptr, end, nextTokPtr) \ + (((enc)->scanners[state])(enc, ptr, end, nextTokPtr)) + +#define XmlPrologTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_PROLOG_STATE, ptr, end, nextTokPtr) + +#define XmlContentTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_CONTENT_STATE, ptr, end, nextTokPtr) + +#define XmlCdataSectionTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_CDATA_SECTION_STATE, ptr, end, nextTokPtr) + +#ifdef XML_DTD + +#define XmlIgnoreSectionTok(enc, ptr, end, nextTokPtr) \ + XmlTok(enc, XML_IGNORE_SECTION_STATE, ptr, end, nextTokPtr) + +#endif /* XML_DTD */ + +/* This is used for performing a 2nd-level tokenization on the content + of a literal that has already been returned by XmlTok. +*/ +#define XmlLiteralTok(enc, literalType, ptr, end, nextTokPtr) \ + (((enc)->literalScanners[literalType])(enc, ptr, end, nextTokPtr)) + +#define XmlAttributeValueTok(enc, ptr, end, nextTokPtr) \ + XmlLiteralTok(enc, XML_ATTRIBUTE_VALUE_LITERAL, ptr, end, nextTokPtr) + +#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \ + XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr) + +#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \ + (((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2)) + +#define XmlNameLength(enc, ptr) \ + (((enc)->nameLength)(enc, ptr)) + +#define XmlSkipS(enc, ptr) \ + (((enc)->skipS)(enc, ptr)) + +#define XmlGetAttributes(enc, ptr, attsMax, atts) \ + (((enc)->getAtts)(enc, ptr, attsMax, atts)) + +#define XmlCharRefNumber(enc, ptr) \ + (((enc)->charRefNumber)(enc, ptr)) + +#define XmlPredefinedEntityName(enc, ptr, end) \ + (((enc)->predefinedEntityName)(enc, ptr, end)) + +#define XmlUpdatePosition(enc, ptr, end, pos) \ + (((enc)->updatePosition)(enc, ptr, end, pos)) + +#define XmlIsPublicId(enc, ptr, end, badPtr) \ + (((enc)->isPublicId)(enc, ptr, end, badPtr)) + +#define XmlUtf8Convert(enc, fromP, fromLim, toP, toLim) \ + (((enc)->utf8Convert)(enc, fromP, fromLim, toP, toLim)) + +#define XmlUtf16Convert(enc, fromP, fromLim, toP, toLim) \ + (((enc)->utf16Convert)(enc, fromP, fromLim, toP, toLim)) + +typedef struct { + ENCODING initEnc; + const ENCODING **encPtr; +} INIT_ENCODING; + +int XmlParseXmlDecl(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingNamePtr, + const ENCODING **namedEncodingPtr, + int *standalonePtr); + +int XmlInitEncoding(INIT_ENCODING *, const ENCODING **, const char *name); +const ENCODING *XmlGetUtf8InternalEncoding(void); +const ENCODING *XmlGetUtf16InternalEncoding(void); +int FASTCALL XmlUtf8Encode(int charNumber, char *buf); +int FASTCALL XmlUtf16Encode(int charNumber, unsigned short *buf); +int XmlSizeOfUnknownEncoding(void); + + +typedef int (XMLCALL *CONVERTER) (void *userData, const char *p); + +ENCODING * +XmlInitUnknownEncoding(void *mem, + int *table, + CONVERTER convert, + void *userData); + +int XmlParseXmlDeclNS(int isGeneralTextEntity, + const ENCODING *enc, + const char *ptr, + const char *end, + const char **badPtr, + const char **versionPtr, + const char **versionEndPtr, + const char **encodingNamePtr, + const ENCODING **namedEncodingPtr, + int *standalonePtr); + +int XmlInitEncodingNS(INIT_ENCODING *, const ENCODING **, const char *name); +const ENCODING *XmlGetUtf8InternalEncodingNS(void); +const ENCODING *XmlGetUtf16InternalEncodingNS(void); +ENCODING * +XmlInitUnknownEncodingNS(void *mem, + int *table, + CONVERTER convert, + void *userData); +#ifdef __cplusplus +} +#endif + +#endif /* not XmlTok_INCLUDED */ diff --git a/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok_impl.h b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok_impl.h new file mode 100644 index 00000000..a6420f48 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/expat/expat/lib/xmltok_impl.h @@ -0,0 +1,73 @@ +/* + __ __ _ + ___\ \/ /_ __ __ _| |_ + / _ \\ /| '_ \ / _` | __| + | __// \| |_) | (_| | |_ + \___/_/\_\ .__/ \__,_|\__| + |_| XML parser + + Copyright (c) 1997-2000 Thai Open Source Software Center Ltd + Copyright (c) 2000-2017 Expat development team + Licensed under the MIT license: + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the + following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +enum { + BT_NONXML, + BT_MALFORM, + BT_LT, + BT_AMP, + BT_RSQB, + BT_LEAD2, + BT_LEAD3, + BT_LEAD4, + BT_TRAIL, + BT_CR, + BT_LF, + BT_GT, + BT_QUOT, + BT_APOS, + BT_EQUALS, + BT_QUEST, + BT_EXCL, + BT_SOL, + BT_SEMI, + BT_NUM, + BT_LSQB, + BT_S, + BT_NMSTRT, + BT_COLON, + BT_HEX, + BT_DIGIT, + BT_NAME, + BT_MINUS, + BT_OTHER, /* known not to be a name or name start character */ + BT_NONASCII, /* might be a name or name start character */ + BT_PERCNT, + BT_LPAR, + BT_RPAR, + BT_AST, + BT_PLUS, + BT_COMMA, + BT_VERBAR +}; + +#include diff --git a/tools/sdk/esp32c3/include/expat/port/include/expat_config.h b/tools/sdk/esp32c3/include/expat/port/include/expat_config.h new file mode 100644 index 00000000..b6b927a1 --- /dev/null +++ b/tools/sdk/esp32c3/include/expat/port/include/expat_config.h @@ -0,0 +1,103 @@ +/* expat_config.h. Generated from expat_config.h.in by configure. */ +/* expat_config.h.in. Generated from configure.ac by autoheader. */ + +/* 1234 = LIL_ENDIAN, 4321 = BIGENDIAN */ +#define BYTEORDER 1234 +/* Define to 1 if you have the `bcopy' function. */ +#define HAVE_BCOPY 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_DLFCN_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `getpagesize' function. */ +#define HAVE_GETPAGESIZE 1 +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `memmove' function. */ +#define HAVE_MEMMOVE 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have a working `mmap' system call. */ +#define HAVE_MMAP 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_PARAM_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Name of package */ +#define PACKAGE "expat" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "expat-bugs@libexpat.org" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "expat" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "expat 2.2.5" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "expat" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "2.2.5" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Version number of package */ +#define VERSION "2.2.5" + +/* whether byteorder is bigendian */ +/* #undef WORDS_BIGENDIAN */ + +/* Define to specify how much context to retain around the current parse + point. */ +#define XML_CONTEXT_BYTES 1024 + +/* Define to make parameter entity parsing functionality available. */ +#define XML_DTD 1 + +/* Define to make XML Namespaces functionality available. */ +#define XML_NS 1 + +/* Define to empty if `const' does not conform to ANSI C. */ +/* #undef const */ + +/* Define to `long int' if does not define. */ +/* #undef off_t */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ diff --git a/tools/sdk/esp32c3/include/fatfs/diskio/diskio_impl.h b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_impl.h new file mode 100644 index 00000000..9d7e0124 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_impl.h @@ -0,0 +1,72 @@ +// Copyright 2017-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +typedef unsigned int UINT; +typedef unsigned char BYTE; +typedef uint32_t DWORD; + +#define FF_DRV_NOT_USED 0xFF + +#include "diskio.h" +#include "esp_err.h" + +/** + * Structure of pointers to disk IO driver functions. + * + * See FatFs documentation for details about these functions + */ +typedef struct { + DSTATUS (*init) (unsigned char pdrv); /*!< disk initialization function */ + DSTATUS (*status) (unsigned char pdrv); /*!< disk status check function */ + DRESULT (*read) (unsigned char pdrv, unsigned char* buff, uint32_t sector, unsigned count); /*!< sector read function */ + DRESULT (*write) (unsigned char pdrv, const unsigned char* buff, uint32_t sector, unsigned count); /*!< sector write function */ + DRESULT (*ioctl) (unsigned char pdrv, unsigned char cmd, void* buff); /*!< function to get info about disk and do some misc operations */ +} ff_diskio_impl_t; + +/** + * Register or unregister diskio driver for given drive number. + * + * When FATFS library calls one of disk_xxx functions for driver number pdrv, + * corresponding function in discio_impl for given pdrv will be called. + * + * @param pdrv drive number + * @param discio_impl pointer to ff_diskio_impl_t structure with diskio functions + * or NULL to unregister and free previously registered drive + */ +void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t* discio_impl); + +#define ff_diskio_unregister(pdrv_) ff_diskio_register(pdrv_, NULL) + + +/** + * Get next available drive number + * + * @param out_pdrv pointer to the byte to set if successful + * + * @return ESP_OK on success + * ESP_ERR_NOT_FOUND if all drives are attached + */ +esp_err_t ff_diskio_get_drive(BYTE* out_pdrv); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/fatfs/diskio/diskio_rawflash.h b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_rawflash.h new file mode 100644 index 00000000..73ff15f8 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_rawflash.h @@ -0,0 +1,37 @@ +// Copyright 2015-2018 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. + +#ifndef _DISKIO_RAWFLASH_DEFINED +#define _DISKIO_RAWFLASH_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "esp_partition.h" + +/** + * Register spi flash partition + * + * @param pdrv drive number + * @param part_handle pointer to raw flash partition. + */ +esp_err_t ff_diskio_register_raw_partition(unsigned char pdrv, const esp_partition_t* part_handle); +unsigned char ff_diskio_get_pdrv_raw(const esp_partition_t* part_handle); + +#ifdef __cplusplus +} +#endif + +#endif // _DISKIO_RAWFLASH_DEFINED diff --git a/tools/sdk/esp32c3/include/fatfs/diskio/diskio_sdmmc.h b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_sdmmc.h new file mode 100644 index 00000000..538a9c6d --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_sdmmc.h @@ -0,0 +1,42 @@ +// Copyright 2017-2019 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. + +#pragma once + +#include "sdmmc_cmd.h" +#include "driver/sdmmc_defs.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Register SD/MMC diskio driver + * + * @param pdrv drive number + * @param card pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount. + */ +void ff_diskio_register_sdmmc(unsigned char pdrv, sdmmc_card_t* card); + +/** + * @brief Get the driver number corresponding to a card + * + * @param card The card to get its driver + * @return Driver number to the card + */ +BYTE ff_diskio_get_pdrv_card(const sdmmc_card_t* card); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/fatfs/diskio/diskio_wl.h b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_wl.h new file mode 100644 index 00000000..619cb6b8 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/diskio/diskio_wl.h @@ -0,0 +1,39 @@ +// Copyright 2015-2017 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. + +#ifndef _DISKIO_WL_DEFINED +#define _DISKIO_WL_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +#include "wear_levelling.h" + + +/** + * Register spi flash partition + * + * @param pdrv drive number + * @param flash_handle handle of the wear levelling partition. + */ +esp_err_t ff_diskio_register_wl_partition(unsigned char pdrv, wl_handle_t flash_handle); +unsigned char ff_diskio_get_pdrv_wl(wl_handle_t flash_handle); +void ff_diskio_clear_pdrv_wl(wl_handle_t flash_handle); + +#ifdef __cplusplus +} +#endif + +#endif // _DISKIO_WL_DEFINED diff --git a/tools/sdk/esp32c3/include/fatfs/src/diskio.h b/tools/sdk/esp32c3/include/fatfs/src/diskio.h new file mode 100644 index 00000000..31776b8b --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/src/diskio.h @@ -0,0 +1,77 @@ +/*-----------------------------------------------------------------------/ +/ Low level disk interface modlue include file (C)ChaN, 2014 / +/-----------------------------------------------------------------------*/ + +#ifndef _DISKIO_DEFINED +#define _DISKIO_DEFINED + +#ifdef __cplusplus +extern "C" { +#endif + +/* Status of Disk Functions */ +typedef BYTE DSTATUS; + +/* Results of Disk Functions */ +typedef enum { + RES_OK = 0, /* 0: Successful */ + RES_ERROR, /* 1: R/W Error */ + RES_WRPRT, /* 2: Write Protected */ + RES_NOTRDY, /* 3: Not Ready */ + RES_PARERR /* 4: Invalid Parameter */ +} DRESULT; + + +/*---------------------------------------*/ +/* Prototypes for disk control functions */ + + +DSTATUS disk_initialize (BYTE pdrv); +DSTATUS disk_status (BYTE pdrv); +DRESULT disk_read (BYTE pdrv, BYTE* buff, DWORD sector, UINT count); +DRESULT disk_write (BYTE pdrv, const BYTE* buff, DWORD sector, UINT count); +DRESULT disk_ioctl (BYTE pdrv, BYTE cmd, void* buff); + + +/* Disk Status Bits (DSTATUS) */ + +#define STA_NOINIT 0x01 /* Drive not initialized */ +#define STA_NODISK 0x02 /* No medium in the drive */ +#define STA_PROTECT 0x04 /* Write protected */ + + +/* Command code for disk_ioctrl fucntion */ + +/* Generic command (Used by FatFs) */ +#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */ +#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */ +#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */ +#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */ +#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */ + +/* Generic command (Not used by FatFs) */ +#define CTRL_POWER 5 /* Get/Set power status */ +#define CTRL_LOCK 6 /* Lock/Unlock media removal */ +#define CTRL_EJECT 7 /* Eject media */ +#define CTRL_FORMAT 8 /* Create physical format on the media */ + +/* MMC/SDC specific ioctl command */ +#define MMC_GET_TYPE 10 /* Get card type */ +#define MMC_GET_CSD 11 /* Get CSD */ +#define MMC_GET_CID 12 /* Get CID */ +#define MMC_GET_OCR 13 /* Get OCR */ +#define MMC_GET_SDSTAT 14 /* Get SD status */ +#define ISDIO_READ 55 /* Read data form SD iSDIO register */ +#define ISDIO_WRITE 56 /* Write data to SD iSDIO register */ +#define ISDIO_MRITE 57 /* Masked write data to SD iSDIO register */ + +/* ATA/CF specific ioctl command */ +#define ATA_GET_REV 20 /* Get F/W revision */ +#define ATA_GET_MODEL 21 /* Get model name */ +#define ATA_GET_SN 22 /* Get serial number */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/fatfs/src/ff.h b/tools/sdk/esp32c3/include/fatfs/src/ff.h new file mode 100644 index 00000000..d8ebeb83 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/src/ff.h @@ -0,0 +1,405 @@ +/*----------------------------------------------------------------------------/ +/ FatFs - Generic FAT Filesystem module R0.13c / +/-----------------------------------------------------------------------------/ +/ +/ Copyright (C) 2018, ChaN, all right reserved. +/ +/ FatFs module is an open source software. Redistribution and use of FatFs in +/ source and binary forms, with or without modification, are permitted provided +/ that the following condition is met: + +/ 1. Redistributions of source code must retain the above copyright notice, +/ this condition and the following disclaimer. +/ +/ This software is provided by the copyright holder and contributors "AS IS" +/ and any warranties related to this software are DISCLAIMED. +/ The copyright owner or contributors be NOT LIABLE for any damages caused +/ by use of this software. +/ +/----------------------------------------------------------------------------*/ + + +#ifndef FF_DEFINED +#define FF_DEFINED 86604 /* Revision ID */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "ffconf.h" /* FatFs configuration options */ + +#if FF_DEFINED != FFCONF_DEF +#error Wrong configuration file (ffconf.h). +#endif + + +/* Integer types used for FatFs API */ + +#if defined(_WIN32) /* Main development platform */ +#define FF_INTDEF 2 +#include +typedef unsigned __int64 QWORD; +#elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__cplusplus) /* C99 or later */ +#define FF_INTDEF 2 +#include +typedef unsigned int UINT; /* int must be 16-bit or 32-bit */ +typedef unsigned char BYTE; /* char must be 8-bit */ +typedef uint16_t WORD; /* 16-bit unsigned integer */ +typedef uint16_t WCHAR; /* 16-bit unsigned integer */ +typedef uint32_t DWORD; /* 32-bit unsigned integer */ +typedef uint64_t QWORD; /* 64-bit unsigned integer */ +#else /* Earlier than C99 */ +#define FF_INTDEF 1 +typedef unsigned int UINT; /* int must be 16-bit or 32-bit */ +typedef unsigned char BYTE; /* char must be 8-bit */ +typedef unsigned short WORD; /* 16-bit unsigned integer */ +typedef unsigned short WCHAR; /* 16-bit unsigned integer */ +typedef unsigned long DWORD; /* 32-bit unsigned integer */ +#endif + + +/* Definitions of volume management */ + +#if FF_MULTI_PARTITION /* Multiple partition configuration */ +typedef struct { + BYTE pd; /* Physical drive number */ + BYTE pt; /* Partition: 0:Auto detect, 1-4:Forced partition) */ +} PARTITION; +extern PARTITION VolToPart[]; /* Volume - Partition resolution table */ +#endif + +#if FF_STR_VOLUME_ID +#ifndef FF_VOLUME_STRS +extern const char* VolumeStr[FF_VOLUMES]; /* User defied volume ID */ +#endif +#endif + + + +/* Type of path name strings on FatFs API */ + +#ifndef _INC_TCHAR +#define _INC_TCHAR + +#if FF_USE_LFN && FF_LFN_UNICODE == 1 /* Unicode in UTF-16 encoding */ +typedef WCHAR TCHAR; +#define _T(x) L ## x +#define _TEXT(x) L ## x +#elif FF_USE_LFN && FF_LFN_UNICODE == 2 /* Unicode in UTF-8 encoding */ +typedef char TCHAR; +#define _T(x) u8 ## x +#define _TEXT(x) u8 ## x +#elif FF_USE_LFN && FF_LFN_UNICODE == 3 /* Unicode in UTF-32 encoding */ +typedef DWORD TCHAR; +#define _T(x) U ## x +#define _TEXT(x) U ## x +#elif FF_USE_LFN && (FF_LFN_UNICODE < 0 || FF_LFN_UNICODE > 3) +#error Wrong FF_LFN_UNICODE setting +#else /* ANSI/OEM code in SBCS/DBCS */ +typedef char TCHAR; +#define _T(x) x +#define _TEXT(x) x +#endif + +#endif + + + +/* Type of file size variables */ + +#if FF_FS_EXFAT +#if FF_INTDEF != 2 +#error exFAT feature wants C99 or later +#endif +typedef QWORD FSIZE_t; +#else +typedef DWORD FSIZE_t; +#endif + + + +/* Filesystem object structure (FATFS) */ + +typedef struct { + BYTE fs_type; /* Filesystem type (0:not mounted) */ + BYTE pdrv; /* Associated physical drive */ + BYTE n_fats; /* Number of FATs (1 or 2) */ + BYTE wflag; /* win[] flag (b0:dirty) */ + BYTE fsi_flag; /* FSINFO flags (b7:disabled, b0:dirty) */ + WORD id; /* Volume mount ID */ + WORD n_rootdir; /* Number of root directory entries (FAT12/16) */ + WORD csize; /* Cluster size [sectors] */ +#if FF_MAX_SS != FF_MIN_SS + WORD ssize; /* Sector size (512, 1024, 2048 or 4096) */ +#endif +#if FF_USE_LFN + WCHAR* lfnbuf; /* LFN working buffer */ +#endif +#if FF_FS_EXFAT + BYTE* dirbuf; /* Directory entry block scratchpad buffer for exFAT */ +#endif +#if FF_FS_REENTRANT + FF_SYNC_t sobj; /* Identifier of sync object */ +#endif +#if !FF_FS_READONLY + DWORD last_clst; /* Last allocated cluster */ + DWORD free_clst; /* Number of free clusters */ +#endif +#if FF_FS_RPATH + DWORD cdir; /* Current directory start cluster (0:root) */ +#if FF_FS_EXFAT + DWORD cdc_scl; /* Containing directory start cluster (invalid when cdir is 0) */ + DWORD cdc_size; /* b31-b8:Size of containing directory, b7-b0: Chain status */ + DWORD cdc_ofs; /* Offset in the containing directory (invalid when cdir is 0) */ +#endif +#endif + DWORD n_fatent; /* Number of FAT entries (number of clusters + 2) */ + DWORD fsize; /* Size of an FAT [sectors] */ + DWORD volbase; /* Volume base sector */ + DWORD fatbase; /* FAT base sector */ + DWORD dirbase; /* Root directory base sector/cluster */ + DWORD database; /* Data base sector */ +#if FF_FS_EXFAT + DWORD bitbase; /* Allocation bitmap base sector */ +#endif + DWORD winsect; /* Current sector appearing in the win[] */ + BYTE win[FF_MAX_SS]; /* Disk access window for Directory, FAT (and file data at tiny cfg) */ +} FATFS; + + + +/* Object ID and allocation information (FFOBJID) */ + +typedef struct { + FATFS* fs; /* Pointer to the hosting volume of this object */ + WORD id; /* Hosting volume mount ID */ + BYTE attr; /* Object attribute */ + BYTE stat; /* Object chain status (b1-0: =0:not contiguous, =2:contiguous, =3:fragmented in this session, b2:sub-directory stretched) */ + DWORD sclust; /* Object data start cluster (0:no cluster or root directory) */ + FSIZE_t objsize; /* Object size (valid when sclust != 0) */ +#if FF_FS_EXFAT + DWORD n_cont; /* Size of first fragment - 1 (valid when stat == 3) */ + DWORD n_frag; /* Size of last fragment needs to be written to FAT (valid when not zero) */ + DWORD c_scl; /* Containing directory start cluster (valid when sclust != 0) */ + DWORD c_size; /* b31-b8:Size of containing directory, b7-b0: Chain status (valid when c_scl != 0) */ + DWORD c_ofs; /* Offset in the containing directory (valid when file object and sclust != 0) */ +#endif +#if FF_FS_LOCK + UINT lockid; /* File lock ID origin from 1 (index of file semaphore table Files[]) */ +#endif +} FFOBJID; + + + +/* File object structure (FIL) */ + +typedef struct { + FFOBJID obj; /* Object identifier (must be the 1st member to detect invalid object pointer) */ + BYTE flag; /* File status flags */ + BYTE err; /* Abort flag (error code) */ + FSIZE_t fptr; /* File read/write pointer (Zeroed on file open) */ + DWORD clust; /* Current cluster of fpter (invalid when fptr is 0) */ + DWORD sect; /* Sector number appearing in buf[] (0:invalid) */ +#if !FF_FS_READONLY + DWORD dir_sect; /* Sector number containing the directory entry (not used at exFAT) */ + BYTE* dir_ptr; /* Pointer to the directory entry in the win[] (not used at exFAT) */ +#endif +#if FF_USE_FASTSEEK + DWORD* cltbl; /* Pointer to the cluster link map table (nulled on open, set by application) */ +#endif +#if !FF_FS_TINY + BYTE buf[FF_MAX_SS]; /* File private data read/write window */ +#endif +} FIL; + + + +/* Directory object structure (FF_DIR) */ + +typedef struct { + FFOBJID obj; /* Object identifier */ + DWORD dptr; /* Current read/write offset */ + DWORD clust; /* Current cluster */ + DWORD sect; /* Current sector (0:Read operation has terminated) */ + BYTE* dir; /* Pointer to the directory item in the win[] */ + BYTE fn[12]; /* SFN (in/out) {body[8],ext[3],status[1]} */ +#if FF_USE_LFN + DWORD blk_ofs; /* Offset of current entry block being processed (0xFFFFFFFF:Invalid) */ +#endif +#if FF_USE_FIND + const TCHAR* pat; /* Pointer to the name matching pattern */ +#endif +} FF_DIR; + + + +/* File information structure (FILINFO) */ + +typedef struct { + FSIZE_t fsize; /* File size */ + WORD fdate; /* Modified date */ + WORD ftime; /* Modified time */ + BYTE fattrib; /* File attribute */ +#if FF_USE_LFN + TCHAR altname[FF_SFN_BUF + 1];/* Altenative file name */ + TCHAR fname[FF_LFN_BUF + 1]; /* Primary file name */ +#else + TCHAR fname[12 + 1]; /* File name */ +#endif +} FILINFO; + + + +/* File function return code (FRESULT) */ + +typedef enum { + FR_OK = 0, /* (0) Succeeded */ + FR_DISK_ERR, /* (1) A hard error occurred in the low level disk I/O layer */ + FR_INT_ERR, /* (2) Assertion failed */ + FR_NOT_READY, /* (3) The physical drive cannot work */ + FR_NO_FILE, /* (4) Could not find the file */ + FR_NO_PATH, /* (5) Could not find the path */ + FR_INVALID_NAME, /* (6) The path name format is invalid */ + FR_DENIED, /* (7) Access denied due to prohibited access or directory full */ + FR_EXIST, /* (8) Access denied due to prohibited access */ + FR_INVALID_OBJECT, /* (9) The file/directory object is invalid */ + FR_WRITE_PROTECTED, /* (10) The physical drive is write protected */ + FR_INVALID_DRIVE, /* (11) The logical drive number is invalid */ + FR_NOT_ENABLED, /* (12) The volume has no work area */ + FR_NO_FILESYSTEM, /* (13) There is no valid FAT volume */ + FR_MKFS_ABORTED, /* (14) The f_mkfs() aborted due to any problem */ + FR_TIMEOUT, /* (15) Could not get a grant to access the volume within defined period */ + FR_LOCKED, /* (16) The operation is rejected according to the file sharing policy */ + FR_NOT_ENOUGH_CORE, /* (17) LFN working buffer could not be allocated */ + FR_TOO_MANY_OPEN_FILES, /* (18) Number of open files > FF_FS_LOCK */ + FR_INVALID_PARAMETER /* (19) Given parameter is invalid */ +} FRESULT; + + + +/*--------------------------------------------------------------*/ +/* FatFs module application interface */ + +FRESULT f_open (FIL* fp, const TCHAR* path, BYTE mode); /* Open or create a file */ +FRESULT f_close (FIL* fp); /* Close an open file object */ +FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br); /* Read data from the file */ +FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw); /* Write data to the file */ +FRESULT f_lseek (FIL* fp, FSIZE_t ofs); /* Move file pointer of the file object */ +FRESULT f_truncate (FIL* fp); /* Truncate the file */ +FRESULT f_sync (FIL* fp); /* Flush cached data of the writing file */ +FRESULT f_opendir (FF_DIR* dp, const TCHAR* path); /* Open a directory */ +FRESULT f_closedir (FF_DIR* dp); /* Close an open directory */ +FRESULT f_readdir (FF_DIR* dp, FILINFO* fno); /* Read a directory item */ +FRESULT f_findfirst (FF_DIR* dp, FILINFO* fno, const TCHAR* path, const TCHAR* pattern); /* Find first file */ +FRESULT f_findnext (FF_DIR* dp, FILINFO* fno); /* Find next file */ +FRESULT f_mkdir (const TCHAR* path); /* Create a sub directory */ +FRESULT f_unlink (const TCHAR* path); /* Delete an existing file or directory */ +FRESULT f_rename (const TCHAR* path_old, const TCHAR* path_new); /* Rename/Move a file or directory */ +FRESULT f_stat (const TCHAR* path, FILINFO* fno); /* Get file status */ +FRESULT f_chmod (const TCHAR* path, BYTE attr, BYTE mask); /* Change attribute of a file/dir */ +FRESULT f_utime (const TCHAR* path, const FILINFO* fno); /* Change timestamp of a file/dir */ +FRESULT f_chdir (const TCHAR* path); /* Change current directory */ +FRESULT f_chdrive (const TCHAR* path); /* Change current drive */ +FRESULT f_getcwd (TCHAR* buff, UINT len); /* Get current directory */ +FRESULT f_getfree (const TCHAR* path, DWORD* nclst, FATFS** fatfs); /* Get number of free clusters on the drive */ +FRESULT f_getlabel (const TCHAR* path, TCHAR* label, DWORD* vsn); /* Get volume label */ +FRESULT f_setlabel (const TCHAR* label); /* Set volume label */ +FRESULT f_forward (FIL* fp, UINT(*func)(const BYTE*,UINT), UINT btf, UINT* bf); /* Forward data to the stream */ +FRESULT f_expand (FIL* fp, FSIZE_t fsz, BYTE opt); /* Allocate a contiguous block to the file */ +FRESULT f_mount (FATFS* fs, const TCHAR* path, BYTE opt); /* Mount/Unmount a logical drive */ +FRESULT f_mkfs (const TCHAR* path, BYTE opt, DWORD au, void* work, UINT len); /* Create a FAT volume */ +FRESULT f_fdisk (BYTE pdrv, const DWORD* szt, void* work); /* Divide a physical drive into some partitions */ +FRESULT f_setcp (WORD cp); /* Set current code page */ +int f_putc (TCHAR c, FIL* fp); /* Put a character to the file */ +int f_puts (const TCHAR* str, FIL* cp); /* Put a string to the file */ +int f_printf (FIL* fp, const TCHAR* str, ...); /* Put a formatted string to the file */ +TCHAR* f_gets (TCHAR* buff, int len, FIL* fp); /* Get a string from the file */ + +#define f_eof(fp) ((int)((fp)->fptr == (fp)->obj.objsize)) +#define f_error(fp) ((fp)->err) +#define f_tell(fp) ((fp)->fptr) +#define f_size(fp) ((fp)->obj.objsize) +#define f_rewind(fp) f_lseek((fp), 0) +#define f_rewinddir(dp) f_readdir((dp), 0) +#define f_rmdir(path) f_unlink(path) +#define f_unmount(path) f_mount(0, path, 0) + +#ifndef EOF +#define EOF (-1) +#endif + + + + +/*--------------------------------------------------------------*/ +/* Additional user defined functions */ + +/* RTC function */ +#if !FF_FS_READONLY && !FF_FS_NORTC +DWORD get_fattime (void); +#endif + +/* LFN support functions */ +#if FF_USE_LFN >= 1 /* Code conversion (defined in unicode.c) */ +WCHAR ff_oem2uni (WCHAR oem, WORD cp); /* OEM code to Unicode conversion */ +WCHAR ff_uni2oem (DWORD uni, WORD cp); /* Unicode to OEM code conversion */ +DWORD ff_wtoupper (DWORD uni); /* Unicode upper-case conversion */ +#endif +#if FF_USE_LFN == 3 /* Dynamic memory allocation */ +void* ff_memalloc (UINT msize); /* Allocate memory block */ +void ff_memfree (void* mblock); /* Free memory block */ +#endif + +/* Sync functions */ +#if FF_FS_REENTRANT +int ff_cre_syncobj (BYTE vol, FF_SYNC_t* sobj); /* Create a sync object */ +int ff_req_grant (FF_SYNC_t sobj); /* Lock sync object */ +void ff_rel_grant (FF_SYNC_t sobj); /* Unlock sync object */ +int ff_del_syncobj (FF_SYNC_t sobj); /* Delete a sync object */ +#endif + + + + +/*--------------------------------------------------------------*/ +/* Flags and offset address */ + + +/* File access mode and open method flags (3rd argument of f_open) */ +#define FA_READ 0x01 +#define FA_WRITE 0x02 +#define FA_OPEN_EXISTING 0x00 +#define FA_CREATE_NEW 0x04 +#define FA_CREATE_ALWAYS 0x08 +#define FA_OPEN_ALWAYS 0x10 +#define FA_OPEN_APPEND 0x30 + +/* Fast seek controls (2nd argument of f_lseek) */ +#define CREATE_LINKMAP ((FSIZE_t)0 - 1) + +/* Format options (2nd argument of f_mkfs) */ +#define FM_FAT 0x01 +#define FM_FAT32 0x02 +#define FM_EXFAT 0x04 +#define FM_ANY 0x07 +#define FM_SFD 0x08 + +/* Filesystem type (FATFS.fs_type) */ +#define FS_FAT12 1 +#define FS_FAT16 2 +#define FS_FAT32 3 +#define FS_EXFAT 4 + +/* File attribute bits for directory entry (FILINFO.fattrib) */ +#define AM_RDO 0x01 /* Read only */ +#define AM_HID 0x02 /* Hidden */ +#define AM_SYS 0x04 /* System */ +#define AM_DIR 0x10 /* Directory */ +#define AM_ARC 0x20 /* Archive */ + + +#ifdef __cplusplus +} +#endif + +#endif /* FF_DEFINED */ diff --git a/tools/sdk/esp32c3/include/fatfs/src/ffconf.h b/tools/sdk/esp32c3/include/fatfs/src/ffconf.h new file mode 100644 index 00000000..6578122c --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/src/ffconf.h @@ -0,0 +1,325 @@ +#include "sdkconfig.h" + +/*---------------------------------------------------------------------------/ +/ FatFs Functional Configurations +/---------------------------------------------------------------------------*/ + +#define FFCONF_DEF 86604 /* Revision ID */ + +/*---------------------------------------------------------------------------/ +/ Function Configurations +/---------------------------------------------------------------------------*/ + +#define FF_FS_READONLY 0 +/* This option switches read-only configuration. (0:Read/Write or 1:Read-only) +/ Read-only configuration removes writing API functions, f_write(), f_sync(), +/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree() +/ and optional writing functions as well. */ + + +#define FF_FS_MINIMIZE 0 +/* This option defines minimization level to remove some basic API functions. +/ +/ 0: Basic functions are fully enabled. +/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename() +/ are removed. +/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1. +/ 3: f_lseek() function is removed in addition to 2. */ + + +#define FF_USE_STRFUNC 0 +/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf(). +/ +/ 0: Disable string functions. +/ 1: Enable without LF-CRLF conversion. +/ 2: Enable with LF-CRLF conversion. */ + + +#define FF_USE_FIND 0 +/* This option switches filtered directory read functions, f_findfirst() and +/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */ + + +#define FF_USE_MKFS 1 +/* This option switches f_mkfs() function. (0:Disable or 1:Enable) */ + + +#define FF_USE_FASTSEEK CONFIG_FATFS_USE_FASTSEEK +/* This option switches fast seek function. (0:Disable or 1:Enable) */ + + +#define FF_USE_EXPAND 0 +/* This option switches f_expand function. (0:Disable or 1:Enable) */ + + +#define FF_USE_CHMOD 1 +/* This option switches attribute manipulation functions, f_chmod() and f_utime(). +/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */ + + +#define FF_USE_LABEL 0 +/* This option switches volume label functions, f_getlabel() and f_setlabel(). +/ (0:Disable or 1:Enable) */ + + +#define FF_USE_FORWARD 0 +/* This option switches f_forward() function. (0:Disable or 1:Enable) */ + + +/*---------------------------------------------------------------------------/ +/ Locale and Namespace Configurations +/---------------------------------------------------------------------------*/ + +#define FF_CODE_PAGE CONFIG_FATFS_CODEPAGE +/* This option specifies the OEM code page to be used on the target system. +/ Incorrect code page setting can cause a file open failure. +/ +/ 437 - U.S. +/ 720 - Arabic +/ 737 - Greek +/ 771 - KBL +/ 775 - Baltic +/ 850 - Latin 1 +/ 852 - Latin 2 +/ 855 - Cyrillic +/ 857 - Turkish +/ 860 - Portuguese +/ 861 - Icelandic +/ 862 - Hebrew +/ 863 - Canadian French +/ 864 - Arabic +/ 865 - Nordic +/ 866 - Russian +/ 869 - Greek 2 +/ 932 - Japanese (DBCS) +/ 936 - Simplified Chinese (DBCS) +/ 949 - Korean (DBCS) +/ 950 - Traditional Chinese (DBCS) +/ 0 - Include all code pages above and configured by f_setcp() +*/ + + +#if defined(CONFIG_FATFS_LFN_STACK) +#define FF_USE_LFN 2 +#elif defined(CONFIG_FATFS_LFN_HEAP) +#define FF_USE_LFN 3 +#else /* CONFIG_FATFS_LFN_NONE */ +#define FF_USE_LFN 0 +#endif + +#ifdef CONFIG_FATFS_MAX_LFN +#define FF_MAX_LFN CONFIG_FATFS_MAX_LFN +#endif + +/* The FF_USE_LFN switches the support for LFN (long file name). +/ +/ 0: Disable LFN. FF_MAX_LFN has no effect. +/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe. +/ 2: Enable LFN with dynamic working buffer on the STACK. +/ 3: Enable LFN with dynamic working buffer on the HEAP. +/ +/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN function +/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and +/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled. +/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can +/ be in range of 12 to 255. It is recommended to be set 255 to fully support LFN +/ specification. +/ When use stack for the working buffer, take care on stack overflow. When use heap +/ memory for the working buffer, memory management functions, ff_memalloc() and +/ ff_memfree() in ffsystem.c, need to be added to the project. */ + + +#ifdef CONFIG_FATFS_API_ENCODING_UTF_8 +#define FF_LFN_UNICODE 2 +#elif defined(CONFIG_FATFS_API_ENCODING_UTF_16) +#define FF_LFN_UNICODE 1 +#else /* CONFIG_FATFS_API_ENCODING_ANSI_OEM */ +#define FF_LFN_UNICODE 0 +#endif +/* This option switches the character encoding on the API when LFN is enabled. +/ +/ 0: ANSI/OEM in current CP (TCHAR = char) +/ 1: Unicode in UTF-16 (TCHAR = WCHAR) +/ 2: Unicode in UTF-8 (TCHAR = char) +/ 3: Unicode in UTF-32 (TCHAR = DWORD) +/ +/ Also behavior of string I/O functions will be affected by this option. +/ When LFN is not enabled, this option has no effect. */ + + +#define FF_LFN_BUF 255 +#define FF_SFN_BUF 12 +/* This set of options defines size of file name members in the FILINFO structure +/ which is used to read out directory items. These values should be suffcient for +/ the file names to read. The maximum possible length of the read file name depends +/ on character encoding. When LFN is not enabled, these options have no effect. */ + + +#define FF_STRF_ENCODE 3 +/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(), +/ f_putc(), f_puts and f_printf() convert the character encoding in it. +/ This option selects assumption of character encoding ON THE FILE to be +/ read/written via those functions. +/ +/ 0: ANSI/OEM in current CP +/ 1: Unicode in UTF-16LE +/ 2: Unicode in UTF-16BE +/ 3: Unicode in UTF-8 +*/ + + +#define FF_FS_RPATH 0 +/* This option configures support for relative path. +/ +/ 0: Disable relative path and remove related functions. +/ 1: Enable relative path. f_chdir() and f_chdrive() are available. +/ 2: f_getcwd() function is available in addition to 1. +*/ + + +/*---------------------------------------------------------------------------/ +/ Drive/Volume Configurations +/---------------------------------------------------------------------------*/ + +#define FF_VOLUMES 2 +/* Number of volumes (logical drives) to be used. (1-10) */ + + +#define FF_STR_VOLUME_ID 0 +#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3" +/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings. +/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive +/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each +/ logical drives. Number of items must not be less than FF_VOLUMES. Valid +/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are +/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is +/ not defined, a user defined volume string table needs to be defined as: +/ +/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",... +*/ + + +#define FF_MULTI_PARTITION 1 +/* This option switches support for multiple volumes on the physical drive. +/ By default (0), each logical drive number is bound to the same physical drive +/ number and only an FAT volume found on the physical drive will be mounted. +/ When this function is enabled (1), each logical drive number can be bound to +/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk() +/ funciton will be available. */ + +/* SD card sector size */ +#define FF_SS_SDCARD 512 +/* wear_levelling library sector size */ +#define FF_SS_WL CONFIG_WL_SECTOR_SIZE + +#define FF_MIN_SS MIN(FF_SS_SDCARD, FF_SS_WL) +#define FF_MAX_SS MAX(FF_SS_SDCARD, FF_SS_WL) +/* This set of options configures the range of sector size to be supported. (512, +/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and +/ harddisk. But a larger value may be required for on-board flash memory and some +/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured +/ for variable sector size mode and disk_ioctl() function needs to implement +/ GET_SECTOR_SIZE command. */ + + +#define FF_USE_TRIM 0 +/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable) +/ To enable Trim function, also CTRL_TRIM command should be implemented to the +/ disk_ioctl() function. */ + + +#define FF_FS_NOFSINFO 0 +/* If you need to know correct free space on the FAT32 volume, set bit 0 of this +/ option, and f_getfree() function at first time after volume mount will force +/ a full FAT scan. Bit 1 controls the use of last allocated cluster number. +/ +/ bit0=0: Use free cluster count in the FSINFO if available. +/ bit0=1: Do not trust free cluster count in the FSINFO. +/ bit1=0: Use last allocated cluster number in the FSINFO if available. +/ bit1=1: Do not trust last allocated cluster number in the FSINFO. +*/ + + + +/*---------------------------------------------------------------------------/ +/ System Configurations +/---------------------------------------------------------------------------*/ + +#define FF_FS_TINY (!CONFIG_FATFS_PER_FILE_CACHE) +/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny) +/ At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes. +/ Instead of private sector buffer eliminated from the file object, common sector +/ buffer in the filesystem object (FATFS) is used for the file data transfer. */ + + +#define FF_FS_EXFAT 0 +/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable) +/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1) +/ Note that enabling exFAT discards ANSI C (C89) compatibility. */ + + +#define FF_FS_NORTC 0 +#define FF_NORTC_MON 1 +#define FF_NORTC_MDAY 1 +#define FF_NORTC_YEAR 2018 +/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have +/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable +/ the timestamp function. Every object modified by FatFs will have a fixed timestamp +/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time. +/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be +/ added to the project to read current time form real-time clock. FF_NORTC_MON, +/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect. +/ These options have no effect at read-only configuration (FF_FS_READONLY = 1). */ + + +#define FF_FS_LOCK CONFIG_FATFS_FS_LOCK +/* The option FF_FS_LOCK switches file lock function to control duplicated file open +/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY +/ is 1. +/ +/ 0: Disable file lock function. To avoid volume corruption, application program +/ should avoid illegal open, remove and rename to the open objects. +/ >0: Enable file lock function. The value defines how many files/sub-directories +/ can be opened simultaneously under file lock control. Note that the file +/ lock control is independent of re-entrancy. */ + + +#define FF_FS_REENTRANT 1 +#define FF_FS_TIMEOUT (CONFIG_FATFS_TIMEOUT_MS / portTICK_PERIOD_MS) +#define FF_SYNC_t SemaphoreHandle_t +/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs +/ module itself. Note that regardless of this option, file access to different +/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs() +/ and f_fdisk() function, are always not re-entrant. Only file/directory access +/ to the same volume is under control of this function. +/ +/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect. +/ 1: Enable re-entrancy. Also user provided synchronization handlers, +/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj() +/ function, must be added to the project. Samples are available in +/ option/syscall.c. +/ +/ The FF_FS_TIMEOUT defines timeout period in unit of time tick. +/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*, +/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be +/ included somewhere in the scope of ff.h. */ + +#include +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +/* Some memory allocation functions are declared here in addition to ff.h, so that + they can be used also by external code when LFN feature is disabled. + */ +void* ff_memalloc (unsigned msize); +void ff_memfree(void*); + + +/*--- End of configuration options ---*/ + +/* Redefine names of disk IO functions to prevent name collisions */ +#define disk_initialize ff_disk_initialize +#define disk_status ff_disk_status +#define disk_read ff_disk_read +#define disk_write ff_disk_write +#define disk_ioctl ff_disk_ioctl diff --git a/tools/sdk/esp32c3/include/fatfs/vfs/esp_vfs_fat.h b/tools/sdk/esp32c3/include/fatfs/vfs/esp_vfs_fat.h new file mode 100644 index 00000000..a3ffe387 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/vfs/esp_vfs_fat.h @@ -0,0 +1,295 @@ +// Copyright 2015-2016 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. + +#pragma once +#include +#include "esp_err.h" +#include "driver/gpio.h" +#include "driver/sdmmc_types.h" +#include "driver/sdspi_host.h" +#include "ff.h" +#include "wear_levelling.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Register FATFS with VFS component + * + * This function registers given FAT drive in VFS, at the specified base path. + * If only one drive is used, fat_drive argument can be an empty string. + * Refer to FATFS library documentation on how to specify FAT drive. + * This function also allocates FATFS structure which should be used for f_mount + * call. + * + * @note This function doesn't mount the drive into FATFS, it just connects + * POSIX and C standard library IO function with FATFS. You need to mount + * desired drive into FATFS separately. + * + * @param base_path path prefix where FATFS should be registered + * @param fat_drive FATFS drive specification; if only one drive is used, can be an empty string + * @param max_files maximum number of files which can be open at the same time + * @param[out] out_fs pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called + * - ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered + */ +esp_err_t esp_vfs_fat_register(const char* base_path, const char* fat_drive, + size_t max_files, FATFS** out_fs); + +/** + * @brief Un-register FATFS from VFS + * + * @note FATFS structure returned by esp_vfs_fat_register is destroyed after + * this call. Make sure to call f_mount function to unmount it before + * calling esp_vfs_fat_unregister_ctx. + * Difference between this function and the one above is that this one + * will release the correct drive, while the one above will release + * the last registered one + * + * @param base_path path prefix where FATFS is registered. This is the same + * used when esp_vfs_fat_register was called + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if FATFS is not registered in VFS + */ +esp_err_t esp_vfs_fat_unregister_path(const char* base_path); + + +/** + * @brief Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount functions + */ +typedef struct { + /** + * If FAT partition can not be mounted, and this parameter is true, + * create partition table and format the filesystem. + */ + bool format_if_mount_failed; + int max_files; ///< Max number of open files + /** + * If format_if_mount_failed is set, and mount fails, format the card + * with given allocation unit size. Must be a power of 2, between sector + * size and 128 * sector size. + * For SD cards, sector size is always 512 bytes. For wear_levelling, + * sector size is determined by CONFIG_WL_SECTOR_SIZE option. + * + * Using larger allocation unit size will result in higher read/write + * performance and higher overhead when storing small files. + * + * Setting this field to 0 will result in allocation unit set to the + * sector size. + */ + size_t allocation_unit_size; +} esp_vfs_fat_mount_config_t; + +// Compatibility definition +typedef esp_vfs_fat_mount_config_t esp_vfs_fat_sdmmc_mount_config_t; + +/** + * @brief Convenience function to get FAT filesystem on SD card registered in VFS + * + * This is an all-in-one function which does the following: + * - initializes SDMMC driver or SPI driver with configuration in host_config + * - initializes SD card with configuration in slot_config + * - mounts FAT partition on SD card using FATFS library, with configuration in mount_config + * - registers FATFS library with VFS, with prefix given by base_prefix variable + * + * This function is intended to make example code more compact. + * For real world applications, developers should implement the logic of + * probing SD card, locating and mounting partition, and registering FATFS in VFS, + * with proper error checking and handling of exceptional conditions. + * + * @note Use this API to mount a card through SDSPI is deprecated. Please call + * `esp_vfs_fat_sdspi_mount()` instead for that case. + * + * @param base_path path where partition should be registered (e.g. "/sdcard") + * @param host_config Pointer to structure describing SDMMC host. When using + * SDMMC peripheral, this structure can be initialized using + * SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, + * this structure can be initialized using SDSPI_HOST_DEFAULT() + * macro. + * @param slot_config Pointer to structure with slot configuration. + * For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t + * structure initialized using SDMMC_SLOT_CONFIG_DEFAULT. + * (Deprecated) For SPI peripheral, pass a pointer to sdspi_slot_config_t + * structure initialized using SDSPI_SLOT_CONFIG_DEFAULT(). + * @param mount_config pointer to structure with extra parameters for mounting FATFS + * @param[out] out_card if not NULL, pointer to the card information structure will be returned via this argument + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called + * - ESP_ERR_NO_MEM if memory can not be allocated + * - ESP_FAIL if partition can not be mounted + * - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers + */ +esp_err_t esp_vfs_fat_sdmmc_mount(const char* base_path, + const sdmmc_host_t* host_config, + const void* slot_config, + const esp_vfs_fat_mount_config_t* mount_config, + sdmmc_card_t** out_card); + +/** + * @brief Convenience function to get FAT filesystem on SD card registered in VFS + * + * This is an all-in-one function which does the following: + * - initializes an SPI Master device based on the SPI Master driver with configuration in + * slot_config, and attach it to an initialized SPI bus. + * - initializes SD card with configuration in host_config_input + * - mounts FAT partition on SD card using FATFS library, with configuration in mount_config + * - registers FATFS library with VFS, with prefix given by base_prefix variable + * + * This function is intended to make example code more compact. + * For real world applications, developers should implement the logic of + * probing SD card, locating and mounting partition, and registering FATFS in VFS, + * with proper error checking and handling of exceptional conditions. + * + * @note This function try to attach the new SD SPI device to the bus specified in host_config. + * Make sure the SPI bus specified in `host_config->slot` have been initialized by + * `spi_bus_initialize()` before. + * + * @param base_path path where partition should be registered (e.g. "/sdcard") + * @param host_config_input Pointer to structure describing SDMMC host. This structure can be + * initialized using SDSPI_HOST_DEFAULT() macro. + * @param slot_config Pointer to structure with slot configuration. + * For SPI peripheral, pass a pointer to sdspi_device_config_t + * structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT(). + * @param mount_config pointer to structure with extra parameters for mounting FATFS + * @param[out] out_card If not NULL, pointer to the card information structure will be returned via + * this argument. It is suggested to hold this handle and use it to unmount the card later if + * needed. Otherwise it's not suggested to use more than one card at the same time and unmount one + * of them in your application. + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called + * - ESP_ERR_NO_MEM if memory can not be allocated + * - ESP_FAIL if partition can not be mounted + * - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers + */ +esp_err_t esp_vfs_fat_sdspi_mount(const char* base_path, + const sdmmc_host_t* host_config_input, + const sdspi_device_config_t* slot_config, + const esp_vfs_fat_mount_config_t* mount_config, + sdmmc_card_t** out_card); + +/** + * @brief Unmount FAT filesystem and release resources acquired using esp_vfs_fat_sdmmc_mount + * + * @deprecated Use `esp_vfs_fat_sdcard_unmount()` instead. + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called + */ +esp_err_t esp_vfs_fat_sdmmc_unmount(void); + +/** + * @brief Unmount an SD card from the FAT filesystem and release resources acquired using + * `esp_vfs_fat_sdmmc_mount()` or `esp_vfs_fat_sdspi_mount()` + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_ARG if the card argument is unregistered + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called + */ +esp_err_t esp_vfs_fat_sdcard_unmount(const char *base_path, sdmmc_card_t *card); + +/** + * @brief Convenience function to initialize FAT filesystem in SPI flash and register it in VFS + * + * This is an all-in-one function which does the following: + * + * - finds the partition with defined partition_label. Partition label should be + * configured in the partition table. + * - initializes flash wear levelling library on top of the given partition + * - mounts FAT partition using FATFS library on top of flash wear levelling + * library + * - registers FATFS library with VFS, with prefix given by base_prefix variable + * + * This function is intended to make example code more compact. + * + * @param base_path path where FATFS partition should be mounted (e.g. "/spiflash") + * @param partition_label label of the partition which should be used + * @param mount_config pointer to structure with extra parameters for mounting FATFS + * @param[out] wl_handle wear levelling driver handle + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount was already called + * - ESP_ERR_NO_MEM if memory can not be allocated + * - ESP_FAIL if partition can not be mounted + * - other error codes from wear levelling library, SPI flash driver, or FATFS drivers + */ +esp_err_t esp_vfs_fat_spiflash_mount(const char* base_path, + const char* partition_label, + const esp_vfs_fat_mount_config_t* mount_config, + wl_handle_t* wl_handle); + +/** + * @brief Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount + * + * @param base_path path where partition should be registered (e.g. "/spiflash") + * @param wl_handle wear levelling driver handle returned by esp_vfs_fat_spiflash_mount + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount hasn't been called + */ + esp_err_t esp_vfs_fat_spiflash_unmount(const char* base_path, wl_handle_t wl_handle); + + +/** + * @brief Convenience function to initialize read-only FAT filesystem and register it in VFS + * + * This is an all-in-one function which does the following: + * + * - finds the partition with defined partition_label. Partition label should be + * configured in the partition table. + * - mounts FAT partition using FATFS library + * - registers FATFS library with VFS, with prefix given by base_prefix variable + * + * @note Wear levelling is not used when FAT is mounted in read-only mode using this function. + * + * @param base_path path where FATFS partition should be mounted (e.g. "/spiflash") + * @param partition_label label of the partition which should be used + * @param mount_config pointer to structure with extra parameters for mounting FATFS + * @return + * - ESP_OK on success + * - ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_rawflash_mount was already called for the same partition + * - ESP_ERR_NO_MEM if memory can not be allocated + * - ESP_FAIL if partition can not be mounted + * - other error codes from SPI flash driver, or FATFS drivers + */ +esp_err_t esp_vfs_fat_rawflash_mount(const char* base_path, + const char* partition_label, + const esp_vfs_fat_mount_config_t* mount_config); + +/** + * @brief Unmount FAT filesystem and release resources acquired using esp_vfs_fat_rawflash_mount + * + * @param base_path path where partition should be registered (e.g. "/spiflash") + * @param partition_label label of partition to be unmounted + * + * @return + * - ESP_OK on success + * - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount hasn't been called + */ + esp_err_t esp_vfs_fat_rawflash_unmount(const char* base_path, const char* partition_label); + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/fatfs/vfs/vfs_fat_internal.h b/tools/sdk/esp32c3/include/fatfs/vfs/vfs_fat_internal.h new file mode 100644 index 00000000..dc3bae27 --- /dev/null +++ b/tools/sdk/esp32c3/include/fatfs/vfs/vfs_fat_internal.h @@ -0,0 +1,30 @@ +// Copyright 2018 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. + +#pragma once + +#include "esp_vfs_fat.h" +#include +#include + +static inline size_t esp_vfs_fat_get_allocation_unit_size( + size_t sector_size, size_t requested_size) +{ + size_t alloc_unit_size = requested_size; + const size_t max_sectors_per_cylinder = 128; + const size_t max_size = sector_size * max_sectors_per_cylinder; + alloc_unit_size = MAX(alloc_unit_size, sector_size); + alloc_unit_size = MIN(alloc_unit_size, max_size); + return alloc_unit_size; +} diff --git a/tools/sdk/esp32c3/include/fb_gfx/include/fb_gfx.h b/tools/sdk/esp32c3/include/fb_gfx/include/fb_gfx.h new file mode 100644 index 00000000..079ff7bf --- /dev/null +++ b/tools/sdk/esp32c3/include/fb_gfx/include/fb_gfx.h @@ -0,0 +1,44 @@ +// Copyright 2015-2016 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. +#ifndef _FB_GFX_H_ +#define _FB_GFX_H_ + +#ifdef __cplusplus +extern "C" { +#endif + + typedef enum { + FB_RGB888, FB_BGR888, FB_RGB565, FB_BGR565 + } fb_format_t; + + typedef struct { + int width; + int height; + int bytes_per_pixel; + fb_format_t format; + uint8_t * data; + } fb_data_t; + + void fb_gfx_fillRect (fb_data_t *fb, int32_t x, int32_t y, int32_t w, int32_t h, uint32_t color); + void fb_gfx_drawFastHLine(fb_data_t *fb, int32_t x, int32_t y, int32_t w, uint32_t color); + void fb_gfx_drawFastVLine(fb_data_t *fb, int32_t x, int32_t y, int32_t h, uint32_t color); + uint8_t fb_gfx_putc (fb_data_t *fb, int32_t x, int32_t y, uint32_t color, unsigned char c); + uint32_t fb_gfx_print (fb_data_t *fb, int32_t x, int32_t y, uint32_t color, const char * str); + uint32_t fb_gfx_printf (fb_data_t *fb, int32_t x, int32_t y, uint32_t color, const char *format, ...); + +#ifdef __cplusplus +} +#endif + +#endif /* _FB_GFX_H_ */ diff --git a/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_common.h b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_common.h new file mode 100644 index 00000000..398af0ba --- /dev/null +++ b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_common.h @@ -0,0 +1,155 @@ +/* Copyright 2018 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. + */ + +#ifndef _MB_IFACE_COMMON_H +#define _MB_IFACE_COMMON_H + +#include "driver/uart.h" // for UART types + +#ifdef __cplusplus +extern "C" { +#endif + +#define MB_CONTROLLER_STACK_SIZE (CONFIG_FMB_CONTROLLER_STACK_SIZE) // Stack size for Modbus controller +#define MB_CONTROLLER_PRIORITY (CONFIG_FMB_PORT_TASK_PRIO - 1) // priority of MB controller task + +// Default port defines +#define MB_DEVICE_ADDRESS (1) // Default slave device address in Modbus +#define MB_DEVICE_SPEED (115200) // Default Modbus speed for now hard defined +#define MB_UART_PORT (UART_NUM_MAX - 1) // Default UART port number +#define MB_PAR_INFO_TOUT (10) // Timeout for get parameter info +#define MB_PARITY_NONE (UART_PARITY_DISABLE) + +// The Macros below handle the endianness while transfer N byte data into buffer +#define _XFER_4_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 0); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 3); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 2); \ + (src) += 4; \ +} + +#define _XFER_2_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 0); \ + (src) += 2; \ +} + +#define _XFER_4_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 3) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 2) = *(uint8_t *)(src)++ ; \ +} + +#define _XFER_2_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ +} + +/** + * @brief Types of actual Modbus implementation + */ +typedef enum +{ + MB_PORT_SERIAL_MASTER = 0x00, /*!< Modbus port type serial master. */ + MB_PORT_SERIAL_SLAVE, /*!< Modbus port type serial slave. */ + MB_PORT_TCP_MASTER, /*!< Modbus port type TCP master. */ + MB_PORT_TCP_SLAVE, /*!< Modbus port type TCP slave. */ + MB_PORT_COUNT, /*!< Modbus port count. */ + MB_PORT_INACTIVE = 0xFF +} mb_port_type_t; + +/** + * @brief Event group for parameters notification + */ +typedef enum +{ + MB_EVENT_NO_EVENTS = 0x00, + MB_EVENT_HOLDING_REG_WR = BIT0, /*!< Modbus Event Write Holding registers. */ + MB_EVENT_HOLDING_REG_RD = BIT1, /*!< Modbus Event Read Holding registers. */ + MB_EVENT_INPUT_REG_RD = BIT3, /*!< Modbus Event Read Input registers. */ + MB_EVENT_COILS_WR = BIT4, /*!< Modbus Event Write Coils. */ + MB_EVENT_COILS_RD = BIT5, /*!< Modbus Event Read Coils. */ + MB_EVENT_DISCRETE_RD = BIT6, /*!< Modbus Event Read Discrete bits. */ + MB_EVENT_STACK_STARTED = BIT7 /*!< Modbus Event Stack started */ +} mb_event_group_t; + +/** + * @brief Type of Modbus parameter + */ +typedef enum { + MB_PARAM_HOLDING = 0x00, /*!< Modbus Holding register. */ + MB_PARAM_INPUT, /*!< Modbus Input register. */ + MB_PARAM_COIL, /*!< Modbus Coils. */ + MB_PARAM_DISCRETE, /*!< Modbus Discrete bits. */ + MB_PARAM_COUNT, + MB_PARAM_UNKNOWN = 0xFF +} mb_param_type_t; + +/*! + * \brief Modbus serial transmission modes (RTU/ASCII). + */ +typedef enum { + MB_MODE_RTU, /*!< RTU transmission mode. */ + MB_MODE_ASCII, /*!< ASCII transmission mode. */ + MB_MODE_TCP, /*!< TCP communication mode. */ + MB_MODE_UDP /*!< UDP communication mode. */ +} mb_mode_type_t; + +/*! + * \brief Modbus TCP type of address. + */ +typedef enum { + MB_IPV4 = 0, /*!< TCP IPV4 addressing */ + MB_IPV6 = 1 /*!< TCP IPV6 addressing */ +} mb_tcp_addr_type_t; + +/** + * @brief Device communication structure to setup Modbus controller + */ +typedef union { + // Serial communication structure + struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t slave_addr; /*!< Modbus slave address field (dummy for master) */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ + uint16_t dummy_port; /*!< Dummy field, unused */ + }; + // TCP/UDP communication structure + struct { + mb_mode_type_t ip_mode; /*!< Modbus communication mode */ + uint16_t ip_port; /*!< Modbus port */ + mb_tcp_addr_type_t ip_addr_type; /*!< Modbus address type */ + void* ip_addr; /*!< Modbus address table for connection */ + void* ip_netif_ptr; /*!< Modbus network interface */ + }; +} mb_communication_info_t; + +/** + * common interface method types + */ +typedef esp_err_t (*iface_init)(void**); /*!< Interface method init */ +typedef esp_err_t (*iface_destroy)(void); /*!< Interface method destroy */ +typedef esp_err_t (*iface_setup)(void*); /*!< Interface method setup */ +typedef esp_err_t (*iface_start)(void); /*!< Interface method start */ + +#ifdef __cplusplus +} +#endif + +#endif // _MB_IFACE_COMMON_H diff --git a/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_master.h b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_master.h new file mode 100644 index 00000000..621348e1 --- /dev/null +++ b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_master.h @@ -0,0 +1,269 @@ +/* Copyright 2018 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. + */ + +#ifndef _ESP_MB_MASTER_INTERFACE_H +#define _ESP_MB_MASTER_INTERFACE_H + +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "esp_modbus_common.h" // for common types + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + * \brief Modbus descriptor table parameter type defines. + */ +typedef enum { + PARAM_TYPE_U8 = 0x00, /*!< Unsigned 8 */ + PARAM_TYPE_U16 = 0x01, /*!< Unsigned 16 */ + PARAM_TYPE_U32 = 0x02, /*!< Unsigned 32 */ + PARAM_TYPE_FLOAT = 0x03, /*!< Float type */ + PARAM_TYPE_ASCII = 0x04 /*!< ASCII type */ +} mb_descr_type_t; + +/*! + * \brief Modbus descriptor table parameter size in bytes. + */ +typedef enum { + PARAM_SIZE_U8 = 0x01, /*!< Unsigned 8 */ + PARAM_SIZE_U16 = 0x02, /*!< Unsigned 16 */ + PARAM_SIZE_U32 = 0x04, /*!< Unsigned 32 */ + PARAM_SIZE_FLOAT = 0x04, /*!< Float size */ + PARAM_SIZE_ASCII = 0x08, /*!< ASCII size */ + PARAM_SIZE_ASCII24 = 0x18, /*!< ASCII24 size */ + PARAM_MAX_SIZE +} mb_descr_size_t; + +/*! + * \brief Modbus parameter options for description table + */ +typedef union { + struct { + int opt1; /*!< Parameter option1 */ + int opt2; /*!< Parameter option2 */ + int opt3; /*!< Parameter option3 */ + }; + struct { + int min; /*!< Parameter minimum value */ + int max; /*!< Parameter maximum value */ + int step; /*!< Step of parameter change tracking */ + }; +} mb_parameter_opt_t; + +/** + * @brief Permissions for the characteristics + */ +typedef enum { + PAR_PERMS_READ = 1 << BIT0, /**< the characteristic of the device are readable */ + PAR_PERMS_WRITE = 1 << BIT1, /**< the characteristic of the device are writable*/ + PAR_PERMS_TRIGGER = 1 << BIT2, /**< the characteristic of the device are triggerable */ + PAR_PERMS_READ_WRITE = PAR_PERMS_READ | PAR_PERMS_WRITE, /**< the characteristic of the device are readable & writable */ + PAR_PERMS_READ_TRIGGER = PAR_PERMS_READ | PAR_PERMS_TRIGGER, /**< the characteristic of the device are readable & triggerable */ + PAR_PERMS_WRITE_TRIGGER = PAR_PERMS_WRITE | PAR_PERMS_TRIGGER, /**< the characteristic of the device are writable & triggerable */ + PAR_PERMS_READ_WRITE_TRIGGER = PAR_PERMS_READ_WRITE | PAR_PERMS_TRIGGER, /**< the characteristic of the device are readable & writable & triggerable */ +} mb_param_perms_t; + +/** + * @brief Characteristics descriptor type is used to describe characteristic and + * link it with Modbus parameters that reflect its data. + */ +typedef struct { + uint16_t cid; /*!< Characteristic cid */ + const char* param_key; /*!< The key (name) of the parameter */ + const char* param_units; /*!< The physical units of the parameter */ + uint8_t mb_slave_addr; /*!< Slave address of device in the Modbus segment */ + mb_param_type_t mb_param_type; /*!< Type of modbus parameter */ + uint16_t mb_reg_start; /*!< This is the Modbus register address. This is the 0 based value. */ + uint16_t mb_size; /*!< Size of mb parameter in registers */ + uint16_t param_offset; /*!< Parameter name (OFFSET in the parameter structure) */ + mb_descr_type_t param_type; /*!< Float, U8, U16, U32, ASCII, etc. */ + mb_descr_size_t param_size; /*!< Number of bytes in the parameter. */ + mb_parameter_opt_t param_opts; /*!< Parameter options used to check limits and etc. */ + mb_param_perms_t access; /*!< Access permissions based on mode */ +} mb_parameter_descriptor_t; + +/** + * @brief Modbus register request type structure + */ +typedef struct { + uint8_t slave_addr; /*!< Modbus slave address */ + uint8_t command; /*!< Modbus command to send */ + uint16_t reg_start; /*!< Modbus start register */ + uint16_t reg_size; /*!< Modbus number of registers */ +} mb_param_request_t; + +/** + * @brief Initialize Modbus controller and stack for TCP port + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_master_init_tcp(void** handler); + +/** + * @brief Initialize Modbus Master controller and stack for Serial port + * + * @param[out] handler handler(pointer) to master data structure + * @param[in] port_type type of stack + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_master_init(mb_port_type_t port_type, void** handler); + +/** + * @brief Initialize Modbus Master controller interface handle + * + * @param[in] handler - pointer to master data structure + */ +void mbc_master_init_iface(void* handler); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Parameter error + */ +esp_err_t mbc_master_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbc_master_start(void); + +/** + * @brief Set Modbus communication parameters for the controller + * + * @param comm_info Communication parameters structure. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Incorrect parameter data + */ +esp_err_t mbc_master_setup(void* comm_info); + +/***************************** Specific interface functions ******************************************** + * Interface functions below provide basic methods to read/write access to slave devices in Modbus + * segment as well as API to read specific supported characteristics linked to Modbus parameters + * of devices in Modbus network. +*******************************************************************************************************/ + +/** + * @brief Assign parameter description table for Modbus controller interface. + * + * @param[in] descriptor pointer to parameter description table + * @param num_elements number of elements in the table + * + * @return + * - esp_err_t ESP_OK - set descriptor successfully + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument in function call + */ +esp_err_t mbc_master_set_descriptor(const mb_parameter_descriptor_t* descriptor, const uint16_t num_elements); + +/** + * @brief Send data request as defined in parameter request, waits response + * from slave and returns status of command execution. This function provides standard way + * for read/write access to Modbus devices in the network. + * + * @param[in] request pointer to request structure of type mb_param_request_t + * @param[in] data_ptr pointer to data buffer to send or received data (dependent of command field in request) + * + * @return + * - esp_err_t ESP_OK - request was successful + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave + * - esp_err_t ESP_ERR_TIMEOUT - operation timeout or no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_FAIL - slave returned an exception or other failure + */ +esp_err_t mbc_master_send_request(mb_param_request_t* request, void* data_ptr); + +/** + * @brief Get information about supported characteristic defined as cid. Uses parameter description table to get + * this information. The function will check if characteristic defined as a cid parameter is supported + * and returns its description in param_info. Returns ESP_ERR_NOT_FOUND if characteristic is not supported. + * + * @param[in] cid characteristic id + * @param param_info pointer to pointer of characteristic data. + * + * @return + * - esp_err_t ESP_OK - request was successful and buffer contains the supported characteristic name + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_NOT_FOUND - the characteristic (cid) not found + * - esp_err_t ESP_FAIL - unknown error during lookup table processing +*/ +esp_err_t mbc_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t** param_info); + +/** + * @brief Read parameter from modbus slave device whose name is defined by name and has cid. + * The additional data for request is taken from parameter description (lookup) table. + * + * @param[in] cid id of the characteristic for parameter + * @param[in] name pointer into string name (key) of parameter (null terminated) + * @param[out] value pointer to data buffer of parameter + * @param[out] type parameter type associated with the name returned from parameter description table. + * + * @return + * - esp_err_t ESP_OK - request was successful and value buffer contains + * representation of actual parameter data from slave + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave + * - esp_err_t ESP_ERR_INVALID_STATE - invalid state during data processing or allocation failure + * - esp_err_t ESP_ERR_TIMEOUT - operation timed out and no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_ERR_NOT_FOUND - the parameter is not found in the parameter description table + * - esp_err_t ESP_FAIL - slave returned an exception or other failure +*/ +esp_err_t mbc_master_get_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type); + +/** + * @brief Set characteristic's value defined as a name and cid parameter. + * The additional data for cid parameter request is taken from master parameter lookup table. + * + * @param[in] cid id of the characteristic for parameter + * @param[in] name pointer into string name (key) of parameter (null terminated) + * @param[out] value pointer to data buffer of parameter (actual representation of json value field in binary form) + * @param[out] type pointer to parameter type associated with the name returned from parameter lookup table. + * + * @return + * - esp_err_t ESP_OK - request was successful and value was saved in the slave device registers + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave during processing of parameter + * - esp_err_t ESP_ERR_INVALID_STATE - invalid state during data processing or allocation failure + * - esp_err_t ESP_ERR_TIMEOUT - operation timed out and no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_FAIL - slave returned an exception or other failure +*/ +esp_err_t mbc_master_set_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_MB_MASTER_INTERFACE_H diff --git a/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_slave.h b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_slave.h new file mode 100644 index 00000000..fa6a53bc --- /dev/null +++ b/tools/sdk/esp32c3/include/freemodbus/common/include/esp_modbus_slave.h @@ -0,0 +1,151 @@ +/* Copyright 2018 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. + */ + +#ifndef _ESP_MB_SLAVE_INTERFACE_H +#define _ESP_MB_SLAVE_INTERFACE_H + +// Public interface header for slave +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "freertos/FreeRTOS.h" // for task creation and queues access +#include "freertos/event_groups.h" // for event groups +#include "esp_modbus_common.h" // for common types + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parameter access event information type + */ +typedef struct { + uint32_t time_stamp; /*!< Timestamp of Modbus Event (uS)*/ + uint16_t mb_offset; /*!< Modbus register offset */ + mb_event_group_t type; /*!< Modbus event type */ + uint8_t* address; /*!< Modbus data storage address */ + size_t size; /*!< Modbus event register size (number of registers)*/ +} mb_param_info_t; + +/** + * @brief Parameter storage area descriptor + */ +typedef struct { + uint16_t start_offset; /*!< Modbus start address for area descriptor */ + mb_param_type_t type; /*!< Type of storage area descriptor */ + void* address; /*!< Instance address for storage area descriptor */ + size_t size; /*!< Instance size for area descriptor (bytes) */ +} mb_register_area_descriptor_t; + +/** + * @brief Initialize Modbus Slave controller and stack for TCP port + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_slave_init_tcp(void** handler); + +/** + * @brief Initialize Modbus Slave controller and stack for Serial port + * + * @param[out] handler handler(pointer) to master data structure + * @param[in] port_type the type of port + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_slave_init(mb_port_type_t port_type, void** handler); + +/** + * @brief Initialize Modbus Slave controller interface handle + * + * @param[in] handler - pointer to slave interface data structure + */ +void mbc_slave_init_iface(void* handler); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Parameter error + */ +esp_err_t mbc_slave_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbc_slave_start(void); + +/** + * @brief Set Modbus communication parameters for the controller + * + * @param comm_info Communication parameters structure. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Incorrect parameter data + */ +esp_err_t mbc_slave_setup(void* comm_info); + +/** + * @brief Wait for specific event on parameter change. + * + * @param group Group event bit mask to wait for change + * + * @return + * - mb_event_group_t event bits triggered + */ +mb_event_group_t mbc_slave_check_event(mb_event_group_t group); + +/** + * @brief Get parameter information + * + * @param[out] reg_info parameter info structure + * @param timeout Timeout in milliseconds to read information from + * parameter queue + * @return + * - ESP_OK Success + * - ESP_ERR_TIMEOUT Can not get data from parameter queue + * or queue overflow + */ +esp_err_t mbc_slave_get_param_info(mb_param_info_t* reg_info, uint32_t timeout); + +/** + * @brief Set Modbus area descriptor + * + * @param descr_data Modbus registers area descriptor structure + * + * @return + * - ESP_OK: The appropriate descriptor is set + * - ESP_ERR_INVALID_ARG: The argument is incorrect + */ +esp_err_t mbc_slave_set_descriptor(mb_register_area_descriptor_t descr_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/freemodbus/common/include/mbcontroller.h b/tools/sdk/esp32c3/include/freemodbus/common/include/mbcontroller.h new file mode 100644 index 00000000..08b3c183 --- /dev/null +++ b/tools/sdk/esp32c3/include/freemodbus/common/include/mbcontroller.h @@ -0,0 +1,32 @@ +/* Copyright 2018 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. +*/ +// mbcontroller.h +// mbcontroller - common Modbus controller header file + +#ifndef _MODBUS_CONTROLLER_COMMON +#define _MODBUS_CONTROLLER_COMMON + +#include // for standard int types definition +#include // for NULL and std defines +#include "string.h" // for strerror() +#include "errno.h" // for errno +#include "esp_err.h" // for error handling +#include "driver/uart.h" // for uart port number defines +#include "sdkconfig.h" // for KConfig options + +#include "esp_modbus_master.h" +#include "esp_modbus_slave.h" + +#endif diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOS.h b/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOS.h new file mode 100644 index 00000000..2c9c5b13 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOS.h @@ -0,0 +1,1329 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef INC_FREERTOS_H +#define INC_FREERTOS_H + +/* + * Include the generic headers required for the FreeRTOS port being used. + */ +#include + +/* + * If stdint.h cannot be located then: + * + If using GCC ensure the -nostdint options is *not* being used. + * + Ensure the project's include path includes the directory in which your + * compiler stores stdint.h. + * + Set any compiler options necessary for it to support C99, as technically + * stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any + * other way). + * + The FreeRTOS download includes a simple stdint.h definition that can be + * used in cases where none is provided by the compiler. The files only + * contains the typedefs required to build FreeRTOS. Read the instructions + * in FreeRTOS/source/stdint.readme for more information. + */ +#include /* READ COMMENT ABOVE. */ + +#ifdef __cplusplus +extern "C" { +#endif +/* for likely and unlikely */ +#include "esp_compiler.h" + +/* Application specific configuration options. */ +#include "freertos/FreeRTOSConfig.h" + +/* Basic FreeRTOS definitions. */ +#include "projdefs.h" + +/* Definitions specific to the port being used. */ +#include "portable.h" + +/* Must be defaulted before configUSE_NEWLIB_REENTRANT is used below. */ +#ifndef configUSE_NEWLIB_REENTRANT + #define configUSE_NEWLIB_REENTRANT 0 +#endif + +/* Required if struct _reent is used. */ +#if ( configUSE_NEWLIB_REENTRANT == 1 ) + #include +#endif +/* + * Check all the required application specific macros have been defined. + * These macros are application specific and (as downloaded) are defined + * within FreeRTOSConfig.h. + */ + +#ifndef configMINIMAL_STACK_SIZE + #error Missing definition: configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h. configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task. Refer to the demo project provided for your port for a suitable value. +#endif + +#ifndef configMAX_PRIORITIES + #error Missing definition: configMAX_PRIORITIES must be defined in FreeRTOSConfig.h. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#if configMAX_PRIORITIES < 1 + #error configMAX_PRIORITIES must be defined to be greater than or equal to 1. +#endif + +#ifndef configUSE_PREEMPTION + #error Missing definition: configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_IDLE_HOOK + #error Missing definition: configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_TICK_HOOK + #error Missing definition: configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_16_BIT_TICKS + #error Missing definition: configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0. See the Configuration section of the FreeRTOS API documentation for details. +#endif + +#ifndef configUSE_CO_ROUTINES + #define configUSE_CO_ROUTINES 0 +#endif + +#ifndef INCLUDE_vTaskPrioritySet + #define INCLUDE_vTaskPrioritySet 0 +#endif + +#ifndef INCLUDE_uxTaskPriorityGet + #define INCLUDE_uxTaskPriorityGet 0 +#endif + +#ifndef INCLUDE_vTaskDelete + #define INCLUDE_vTaskDelete 0 +#endif + +#ifndef INCLUDE_vTaskSuspend + #define INCLUDE_vTaskSuspend 0 +#endif + +#ifndef INCLUDE_vTaskDelayUntil + #define INCLUDE_vTaskDelayUntil 0 +#endif + +#ifndef INCLUDE_vTaskDelay + #define INCLUDE_vTaskDelay 0 +#endif + +#ifndef INCLUDE_xTaskGetIdleTaskHandle + #define INCLUDE_xTaskGetIdleTaskHandle 0 +#endif + +#ifndef INCLUDE_xTaskAbortDelay + #define INCLUDE_xTaskAbortDelay 0 +#endif + +#ifndef INCLUDE_xQueueGetMutexHolder + #define INCLUDE_xQueueGetMutexHolder 0 +#endif + +#ifndef INCLUDE_xSemaphoreGetMutexHolder + #define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder +#endif + +#ifndef INCLUDE_xTaskGetHandle + #define INCLUDE_xTaskGetHandle 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark + #define INCLUDE_uxTaskGetStackHighWaterMark 0 +#endif + +#ifndef INCLUDE_uxTaskGetStackHighWaterMark2 + #define INCLUDE_uxTaskGetStackHighWaterMark2 0 +#endif + +#ifndef INCLUDE_eTaskGetState + #define INCLUDE_eTaskGetState 0 +#endif + +#ifndef INCLUDE_xTaskResumeFromISR + #define INCLUDE_xTaskResumeFromISR 1 +#endif + +#ifndef INCLUDE_xTimerPendFunctionCall + #define INCLUDE_xTimerPendFunctionCall 0 +#endif + +#ifndef INCLUDE_xTaskGetSchedulerState + #define INCLUDE_xTaskGetSchedulerState 0 +#endif + +#ifndef INCLUDE_xTaskGetCurrentTaskHandle + #define INCLUDE_xTaskGetCurrentTaskHandle 0 +#endif + +#if configUSE_CO_ROUTINES != 0 + #ifndef configMAX_CO_ROUTINE_PRIORITIES + #error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1. + #endif +#endif + +#ifndef configUSE_DAEMON_TASK_STARTUP_HOOK + #define configUSE_DAEMON_TASK_STARTUP_HOOK 0 +#endif + +#ifndef configUSE_APPLICATION_TASK_TAG + #define configUSE_APPLICATION_TASK_TAG 0 +#endif + +#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS + #define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0 +#endif + +#ifndef configUSE_RECURSIVE_MUTEXES + #define configUSE_RECURSIVE_MUTEXES 0 +#endif + +#ifndef configUSE_MUTEXES + #define configUSE_MUTEXES 0 +#endif + +#ifndef configUSE_TIMERS + #define configUSE_TIMERS 0 +#endif + +#ifndef configUSE_COUNTING_SEMAPHORES + #define configUSE_COUNTING_SEMAPHORES 0 +#endif + +#ifndef configUSE_ALTERNATIVE_API + #define configUSE_ALTERNATIVE_API 0 +#endif + +#ifndef portCRITICAL_NESTING_IN_TCB + #define portCRITICAL_NESTING_IN_TCB 0 +#endif + +#ifndef configMAX_TASK_NAME_LEN + #define configMAX_TASK_NAME_LEN 16 +#endif + +#ifndef configIDLE_SHOULD_YIELD + #define configIDLE_SHOULD_YIELD 1 +#endif + +#if configMAX_TASK_NAME_LEN < 1 + #error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h +#endif + +#ifndef configASSERT + #define configASSERT( x ) + #define configASSERT_DEFINED 0 +#else + #define configASSERT_DEFINED 1 +#endif + +/* configPRECONDITION should be resolve to configASSERT. + The CBMC proofs need a way to track assumptions and assertions. + A configPRECONDITION statement should express an implicit invariant or assumption made. + A configASSERT statement should express an invariant that must hold explicit before calling + the code. */ +#ifndef configPRECONDITION + #define configPRECONDITION( X ) configASSERT(X) + #define configPRECONDITION_DEFINED 0 +#else + #define configPRECONDITION_DEFINED 1 +#endif + +#ifndef portMEMORY_BARRIER + #define portMEMORY_BARRIER() +#endif + +/* The timers module relies on xTaskGetSchedulerState(). */ +#if configUSE_TIMERS == 1 + + #ifndef configTIMER_TASK_PRIORITY + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined. + #endif /* configTIMER_TASK_PRIORITY */ + + #ifndef configTIMER_QUEUE_LENGTH + #error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined. + #endif /* configTIMER_QUEUE_LENGTH */ + + #ifndef configTIMER_TASK_STACK_DEPTH + #error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined. + #endif /* configTIMER_TASK_STACK_DEPTH */ + +#endif /* configUSE_TIMERS */ + +#ifndef portSET_INTERRUPT_MASK_FROM_ISR + #define portSET_INTERRUPT_MASK_FROM_ISR() 0 +#endif + +#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR + #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue +#endif + +#ifndef portCLEAN_UP_TCB + #define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef portPRE_TASK_DELETE_HOOK + #define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending ) +#endif + +#ifndef portSETUP_TCB + #define portSETUP_TCB( pxTCB ) ( void ) pxTCB +#endif + +#ifndef configQUEUE_REGISTRY_SIZE + #define configQUEUE_REGISTRY_SIZE 0U +#endif + +#if ( configQUEUE_REGISTRY_SIZE < 1 ) + #define vQueueAddToRegistry( xQueue, pcName ) + #define vQueueUnregisterQueue( xQueue ) + #define pcQueueGetName( xQueue ) +#endif + +#ifndef portPOINTER_SIZE_TYPE + #define portPOINTER_SIZE_TYPE uint32_t +#endif + +/* Remove any unused trace macros. */ +#ifndef traceSTART + /* Used to perform any necessary initialisation - for example, open a file + into which trace is to be written. */ + #define traceSTART() +#endif + +#ifndef traceEND + /* Use to close a trace, for example close a file into which trace has been + written. */ + #define traceEND() +#endif + +#ifndef traceTASK_SWITCHED_IN + /* Called after a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the selected task. */ + #define traceTASK_SWITCHED_IN() +#endif + +#ifndef traceINCREASE_TICK_COUNT + /* Called before stepping the tick count after waking from tickless idle + sleep. */ + #define traceINCREASE_TICK_COUNT( x ) +#endif + +#ifndef traceLOW_POWER_IDLE_BEGIN + /* Called immediately before entering tickless idle. */ + #define traceLOW_POWER_IDLE_BEGIN() +#endif + +#ifndef traceLOW_POWER_IDLE_END + /* Called when returning to the Idle task after a tickless idle. */ + #define traceLOW_POWER_IDLE_END() +#endif + +#ifndef traceTASK_SWITCHED_OUT + /* Called before a task has been selected to run. pxCurrentTCB holds a pointer + to the task control block of the task being switched out. */ + #define traceTASK_SWITCHED_OUT() +#endif + +#ifndef traceTASK_PRIORITY_INHERIT + /* Called when a task attempts to take a mutex that is already held by a + lower priority task. pxTCBOfMutexHolder is a pointer to the TCB of the task + that holds the mutex. uxInheritedPriority is the priority the mutex holder + will inherit (the priority of the task that is attempting to obtain the + muted. */ + #define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority ) +#endif + +#ifndef traceTASK_PRIORITY_DISINHERIT + /* Called when a task releases a mutex, the holding of which had resulted in + the task inheriting the priority of a higher priority task. + pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the + mutex. uxOriginalPriority is the task's configured (base) priority. */ + #define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_RECEIVE + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_PEEK + /* Task is about to block because it cannot read from a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the read was attempted. pxCurrentTCB points to the TCB of the + task that attempted the read. */ + #define traceBLOCKING_ON_QUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceBLOCKING_ON_QUEUE_SEND + /* Task is about to block because it cannot write to a + queue/mutex/semaphore. pxQueue is a pointer to the queue/mutex/semaphore + upon which the write was attempted. pxCurrentTCB points to the TCB of the + task that attempted the write. */ + #define traceBLOCKING_ON_QUEUE_SEND( pxQueue ) +#endif + +#ifndef configCHECK_FOR_STACK_OVERFLOW + #define configCHECK_FOR_STACK_OVERFLOW 0 +#endif + +#ifndef configRECORD_STACK_HIGH_ADDRESS + #define configRECORD_STACK_HIGH_ADDRESS 0 +#endif + +#ifndef configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H + #define configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H 0 +#endif + +/* The following event macros are embedded in the kernel API calls. */ + +#ifndef traceMOVED_TASK_TO_READY_STATE + #define traceMOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef tracePOST_MOVED_TASK_TO_READY_STATE + #define tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +#endif + +#ifndef traceQUEUE_CREATE + #define traceQUEUE_CREATE( pxNewQueue ) +#endif + +#ifndef traceQUEUE_CREATE_FAILED + #define traceQUEUE_CREATE_FAILED( ucQueueType ) +#endif + +#ifndef traceCREATE_MUTEX + #define traceCREATE_MUTEX( pxNewQueue ) +#endif + +#ifndef traceCREATE_MUTEX_FAILED + #define traceCREATE_MUTEX_FAILED() +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE + #define traceGIVE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED + #define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE + #define traceTAKE_MUTEX_RECURSIVE( pxMutex ) +#endif + +#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED + #define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ) +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE + #define traceCREATE_COUNTING_SEMAPHORE() +#endif + +#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED + #define traceCREATE_COUNTING_SEMAPHORE_FAILED() +#endif + +#ifndef traceQUEUE_SEMAPHORE_RECEIVE + #define traceQUEUE_SEMAPHORE_RECEIVE( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND + #define traceQUEUE_SEND( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FAILED + #define traceQUEUE_SEND_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE + #define traceQUEUE_RECEIVE( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK + #define traceQUEUE_PEEK( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FAILED + #define traceQUEUE_PEEK_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR + #define traceQUEUE_PEEK_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FAILED + #define traceQUEUE_RECEIVE_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR + #define traceQUEUE_SEND_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_SEND_FROM_ISR_FAILED + #define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR + #define traceQUEUE_RECEIVE_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED + #define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED + #define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceQUEUE_DELETE + #define traceQUEUE_DELETE( pxQueue ) +#endif + +#ifndef traceQUEUE_GIVE_FROM_ISR + #define traceQUEUE_GIVE_FROM_ISR( pxQueue ) +#endif + +#ifndef traceQUEUE_GIVE_FROM_ISR_FAILED + #define traceQUEUE_GIVE_FROM_ISR_FAILED( pxQueue ) +#endif + +#ifndef traceTASK_CREATE + #define traceTASK_CREATE( pxNewTCB ) +#endif + +#ifndef traceTASK_CREATE_FAILED + #define traceTASK_CREATE_FAILED() +#endif + +#ifndef traceTASK_DELETE + #define traceTASK_DELETE( pxTaskToDelete ) +#endif + +#ifndef traceTASK_DELAY_UNTIL + #define traceTASK_DELAY_UNTIL( x ) +#endif + +#ifndef traceTASK_DELAY + #define traceTASK_DELAY() +#endif + +#ifndef traceTASK_PRIORITY_SET + #define traceTASK_PRIORITY_SET( pxTask, uxNewPriority ) +#endif + +#ifndef traceTASK_SUSPEND + #define traceTASK_SUSPEND( pxTaskToSuspend ) +#endif + +#ifndef traceTASK_RESUME + #define traceTASK_RESUME( pxTaskToResume ) +#endif + +#ifndef traceTASK_RESUME_FROM_ISR + #define traceTASK_RESUME_FROM_ISR( pxTaskToResume ) +#endif + +#ifndef traceTASK_INCREMENT_TICK + #define traceTASK_INCREMENT_TICK( xTickCount ) +#endif + +#ifndef traceTIMER_CREATE + #define traceTIMER_CREATE( pxNewTimer ) +#endif + +#ifndef traceTIMER_CREATE_FAILED + #define traceTIMER_CREATE_FAILED() +#endif + +#ifndef traceTIMER_COMMAND_SEND + #define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn ) +#endif + +#ifndef traceTIMER_EXPIRED + #define traceTIMER_EXPIRED( pxTimer ) +#endif + +#ifndef traceTIMER_COMMAND_RECEIVED + #define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue ) +#endif + +#ifndef traceMALLOC + #define traceMALLOC( pvAddress, uiSize ) +#endif + +#ifndef traceFREE + #define traceFREE( pvAddress, uiSize ) +#endif + +#ifndef traceEVENT_GROUP_CREATE + #define traceEVENT_GROUP_CREATE( xEventGroup ) +#endif + +#ifndef traceEVENT_GROUP_CREATE_FAILED + #define traceEVENT_GROUP_CREATE_FAILED() +#endif + +#ifndef traceEVENT_GROUP_SYNC_BLOCK + #define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_SYNC_END + #define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK + #define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor ) +#endif + +#ifndef traceEVENT_GROUP_WAIT_BITS_END + #define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS + #define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR + #define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS + #define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR + #define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet ) +#endif + +#ifndef traceEVENT_GROUP_DELETE + #define traceEVENT_GROUP_DELETE( xEventGroup ) +#endif + +#ifndef tracePEND_FUNC_CALL + #define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret) +#endif + +#ifndef tracePEND_FUNC_CALL_FROM_ISR + #define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret) +#endif + +#ifndef traceQUEUE_REGISTRY_ADD + #define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName) +#endif + +#ifndef traceTASK_NOTIFY_TAKE_BLOCK + #define traceTASK_NOTIFY_TAKE_BLOCK() +#endif + +#ifndef traceTASK_NOTIFY_TAKE + #define traceTASK_NOTIFY_TAKE() +#endif + +#ifndef traceTASK_NOTIFY_WAIT_BLOCK + #define traceTASK_NOTIFY_WAIT_BLOCK() +#endif + +#ifndef traceTASK_NOTIFY_WAIT + #define traceTASK_NOTIFY_WAIT() +#endif + +#ifndef traceTASK_NOTIFY + #define traceTASK_NOTIFY() +#endif + +#ifndef traceTASK_NOTIFY_FROM_ISR + #define traceTASK_NOTIFY_FROM_ISR() +#endif + +#ifndef traceTASK_NOTIFY_GIVE_FROM_ISR + #define traceTASK_NOTIFY_GIVE_FROM_ISR() +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_FAILED + #define traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE_STATIC_FAILED + #define traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_CREATE + #define traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_DELETE + #define traceSTREAM_BUFFER_DELETE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RESET + #define traceSTREAM_BUFFER_RESET( xStreamBuffer ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_SEND + #define traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND + #define traceSTREAM_BUFFER_SEND( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FAILED + #define traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_SEND_FROM_ISR + #define traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xBytesSent ) +#endif + +#ifndef traceBLOCKING_ON_STREAM_BUFFER_RECEIVE + #define traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE + #define traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FAILED + #define traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ) +#endif + +#ifndef traceSTREAM_BUFFER_RECEIVE_FROM_ISR + #define traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ) +#endif + +#ifndef traceISR_EXIT_TO_SCHEDULER + #define traceISR_EXIT_TO_SCHEDULER() +#endif + +#ifndef traceISR_EXIT + #define traceISR_EXIT() +#endif + +#ifndef traceISR_ENTER + #define traceISR_ENTER(_n_) +#endif + +#ifndef configGENERATE_RUN_TIME_STATS + #define configGENERATE_RUN_TIME_STATS 0 +#endif + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + #ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined. portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base. + #endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */ + + #ifndef portGET_RUN_TIME_COUNTER_VALUE + #ifndef portALT_GET_RUN_TIME_COUNTER_VALUE + #error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined. See the examples provided and the FreeRTOS web site for more information. + #endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */ + #endif /* portGET_RUN_TIME_COUNTER_VALUE */ + +#endif /* configGENERATE_RUN_TIME_STATS */ + +#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS + #define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() +#endif + +#ifndef configUSE_MALLOC_FAILED_HOOK + #define configUSE_MALLOC_FAILED_HOOK 0 +#endif + +#ifndef portPRIVILEGE_BIT + #define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 ) +#endif + +#ifndef portYIELD_WITHIN_API + #define portYIELD_WITHIN_API portYIELD +#endif + +#ifndef portSUPPRESS_TICKS_AND_SLEEP + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) +#endif + +#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP + #define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2 +#endif + +#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2 + #error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2 +#endif + +#ifndef configUSE_TICKLESS_IDLE + #define configUSE_TICKLESS_IDLE 0 +#endif + +#ifndef configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING + #define configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPRE_SLEEP_PROCESSING + #define configPRE_SLEEP_PROCESSING( x ) +#endif + +#ifndef configPOST_SLEEP_PROCESSING + #define configPOST_SLEEP_PROCESSING( x ) +#endif + +#ifndef configUSE_QUEUE_SETS + #define configUSE_QUEUE_SETS 0 +#endif + +#ifndef portTASK_USES_FLOATING_POINT + #define portTASK_USES_FLOATING_POINT() +#endif + +#ifndef portALLOCATE_SECURE_CONTEXT + #define portALLOCATE_SECURE_CONTEXT( ulSecureStackSize ) +#endif + +#ifndef portDONT_DISCARD + #define portDONT_DISCARD +#endif + +#ifndef configUSE_TIME_SLICING + #define configUSE_TIME_SLICING 1 +#endif + +#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS + #define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0 +#endif + +#ifndef configUSE_STATS_FORMATTING_FUNCTIONS + #define configUSE_STATS_FORMATTING_FUNCTIONS 0 +#endif + +#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() +#endif + +#ifndef configUSE_TRACE_FACILITY + #define configUSE_TRACE_FACILITY 0 +#endif + +#ifndef mtCOVERAGE_TEST_MARKER + #define mtCOVERAGE_TEST_MARKER() +#endif + +#ifndef mtCOVERAGE_TEST_DELAY + #define mtCOVERAGE_TEST_DELAY() +#endif + +#ifndef portASSERT_IF_IN_ISR + #define portASSERT_IF_IN_ISR() +#endif + +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 +#endif + +#ifndef configAPPLICATION_ALLOCATED_HEAP + #define configAPPLICATION_ALLOCATED_HEAP 0 +#endif + +#ifndef configUSE_TASK_NOTIFICATIONS + #define configUSE_TASK_NOTIFICATIONS 1 +#endif + +#ifndef configUSE_POSIX_ERRNO + #define configUSE_POSIX_ERRNO 0 +#endif + +#ifndef portTICK_TYPE_IS_ATOMIC + #define portTICK_TYPE_IS_ATOMIC 0 +#endif + +#ifndef configSUPPORT_STATIC_ALLOCATION + /* Defaults to 0 for backward compatibility. */ + #define configSUPPORT_STATIC_ALLOCATION 0 +#endif + +#ifndef configSUPPORT_DYNAMIC_ALLOCATION + /* Defaults to 1 for backward compatibility. */ + #define configSUPPORT_DYNAMIC_ALLOCATION 1 +#endif + +#ifndef configSTACK_DEPTH_TYPE + /* Defaults to uint16_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if uint16_t is too restrictive. */ + #define configSTACK_DEPTH_TYPE uint16_t +#endif + +#ifndef configMESSAGE_BUFFER_LENGTH_TYPE + /* Defaults to size_t for backward compatibility, but can be overridden + in FreeRTOSConfig.h if lengths will always be less than the number of bytes + in a size_t. */ + #define configMESSAGE_BUFFER_LENGTH_TYPE size_t +#endif + +/* Sanity check the configuration. */ +#if( configUSE_TICKLESS_IDLE != 0 ) + #if( INCLUDE_vTaskSuspend != 1 ) + #error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0 + #endif /* INCLUDE_vTaskSuspend */ +#endif /* configUSE_TICKLESS_IDLE */ + +#if( ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) ) + #error configSUPPORT_STATIC_ALLOCATION and configSUPPORT_DYNAMIC_ALLOCATION cannot both be 0, but can both be 1. +#endif + +#if( ( configUSE_RECURSIVE_MUTEXES == 1 ) && ( configUSE_MUTEXES != 1 ) ) + #error configUSE_MUTEXES must be set to 1 to use recursive mutexes +#endif + +#ifndef configINITIAL_TICK_COUNT + #define configINITIAL_TICK_COUNT 0 +#endif + +#if( portTICK_TYPE_IS_ATOMIC == 0 ) + /* Either variables of tick type cannot be read atomically, or + portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when + the tick count is returned to the standard critical section macros. */ + #define portTICK_TYPE_ENTER_CRITICAL(mux) portENTER_CRITICAL(mux) + #define portTICK_TYPE_EXIT_CRITICAL(mux) portEXIT_CRITICAL(mux) + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) ) +#else + /* The tick type can be read atomically, so critical sections used when the + tick count is returned can be defined away. */ + #define portTICK_TYPE_ENTER_CRITICAL() + #define portTICK_TYPE_EXIT_CRITICAL() + #define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0 + #define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x +#endif + +/* Definitions to allow backward compatibility with FreeRTOS versions prior to +V8 if desired. */ +#ifndef configENABLE_BACKWARD_COMPATIBILITY + #define configENABLE_BACKWARD_COMPATIBILITY 1 +#endif + +#ifndef configPRINTF + /* configPRINTF() was not defined, so define it away to nothing. To use + configPRINTF() then define it as follows (where MyPrintFunction() is + provided by the application writer): + + void MyPrintFunction(const char *pcFormat, ... ); + #define configPRINTF( X ) MyPrintFunction X + + Then call like a standard printf() function, but placing brackets around + all parameters so they are passed as a single parameter. For example: + configPRINTF( ("Value = %d", MyVariable) ); */ + #define configPRINTF( X ) +#endif + +#ifndef configMAX + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) ) +#endif + +#ifndef configMIN + /* The application writer has not provided their own MAX macro, so define + the following generic implementation. */ + #define configMIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) ) +#endif + +#if configENABLE_BACKWARD_COMPATIBILITY == 1 + #define eTaskStateGet eTaskGetState + #define portTickType TickType_t + #define xTaskHandle TaskHandle_t + #define xQueueHandle QueueHandle_t + #define xSemaphoreHandle SemaphoreHandle_t + #define xQueueSetHandle QueueSetHandle_t + #define xQueueSetMemberHandle QueueSetMemberHandle_t + #define xTimeOutType TimeOut_t + #define xMemoryRegion MemoryRegion_t + #define xTaskParameters TaskParameters_t + #define xTaskStatusType TaskStatus_t + #define xTimerHandle TimerHandle_t + #define xCoRoutineHandle CoRoutineHandle_t + #define pdTASK_HOOK_CODE TaskHookFunction_t + #define portTICK_RATE_MS portTICK_PERIOD_MS + #define pcTaskGetTaskName pcTaskGetName + #define pcTimerGetTimerName pcTimerGetName + #define pcQueueGetQueueName pcQueueGetName + #define vTaskGetTaskInfo vTaskGetInfo + + /* Backward compatibility within the scheduler code only - these definitions + are not really required but are included for completeness. */ + #define tmrTIMER_CALLBACK TimerCallbackFunction_t + #define pdTASK_CODE TaskFunction_t + #define xListItem ListItem_t + #define xList List_t + + /* For libraries that break the list data hiding, and access list structure + members directly (which is not supposed to be done). */ + #define pxContainer pvContainer +#endif /* configENABLE_BACKWARD_COMPATIBILITY */ + +#ifndef configESP32_PER_TASK_DATA + #define configESP32_PER_TASK_DATA 1 +#endif + +#if( configUSE_ALTERNATIVE_API != 0 ) + #error The alternative API was deprecated some time ago, and was removed in FreeRTOS V9.0 0 +#endif + +/* Set configUSE_TASK_FPU_SUPPORT to 0 to omit floating point support even +if floating point hardware is otherwise supported by the FreeRTOS port in use. +This constant is not supported by all FreeRTOS ports that include floating +point support. */ +#ifndef configUSE_TASK_FPU_SUPPORT + #define configUSE_TASK_FPU_SUPPORT 1 +#endif + +/* Set configENABLE_MPU to 1 to enable MPU support and 0 to disable it. This is +currently used in ARMv8M ports. */ +#ifndef configENABLE_MPU + #define configENABLE_MPU 0 +#endif + +/* Set configENABLE_FPU to 1 to enable FPU support and 0 to disable it. This is +currently used in ARMv8M ports. */ +#ifndef configENABLE_FPU + #define configENABLE_FPU 1 +#endif + +/* Set configENABLE_TRUSTZONE to 1 enable TrustZone support and 0 to disable it. +This is currently used in ARMv8M ports. */ +#ifndef configENABLE_TRUSTZONE + #define configENABLE_TRUSTZONE 1 +#endif + +/* Set configRUN_FREERTOS_SECURE_ONLY to 1 to run the FreeRTOS ARMv8M port on +the Secure Side only. */ +#ifndef configRUN_FREERTOS_SECURE_ONLY + #define configRUN_FREERTOS_SECURE_ONLY 0 +#endif + +/* Sometimes the FreeRTOSConfig.h settings only allow a task to be created using + * dynamically allocated RAM, in which case when any task is deleted it is known + * that both the task's stack and TCB need to be freed. Sometimes the + * FreeRTOSConfig.h settings only allow a task to be created using statically + * allocated RAM, in which case when any task is deleted it is known that neither + * the task's stack or TCB should be freed. Sometimes the FreeRTOSConfig.h + * settings allow a task to be created using either statically or dynamically + * allocated RAM, in which case a member of the TCB is used to record whether the + * stack and/or TCB were allocated statically or dynamically, so when a task is + * deleted the RAM that was allocated dynamically is freed again and no attempt is + * made to free the RAM that was allocated statically. + * tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE is only true if it is possible for a + * task to be created using either statically or dynamically allocated RAM. Note + * that if portUSING_MPU_WRAPPERS is 1 then a protected task can be created with + * a statically allocated stack and a dynamically allocated TCB. + * + * The following table lists various combinations of portUSING_MPU_WRAPPERS, + * configSUPPORT_DYNAMIC_ALLOCATION and configSUPPORT_STATIC_ALLOCATION and + * when it is possible to have both static and dynamic allocation: + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | MPU | Dynamic | Static | Available Functions | Possible Allocations | Both Dynamic and | Need Free | + * | | | | | | Static Possible | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + * | 0 | 0 | 1 | xTaskCreateStatic | TCB - Static, Stack - Static | No | No | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 0 | xTaskCreate | TCB - Dynamic, Stack - Dynamic | No | Yes | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 0 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic | 2. TCB - Static, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 0 | 1 | xTaskCreateStatic, | TCB - Static, Stack - Static | No | No | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 0 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateRestricted | 2. TCB - Dynamic, Stack - Static | | | + * +-----|---------|--------|-----------------------------|-----------------------------------|------------------|-----------| + * | 1 | 1 | 1 | xTaskCreate, | 1. TCB - Dynamic, Stack - Dynamic | Yes | Yes | + * | | | | xTaskCreateStatic, | 2. TCB - Dynamic, Stack - Static | | | + * | | | | xTaskCreateRestricted, | 3. TCB - Static, Stack - Static | | | + * | | | | xTaskCreateRestrictedStatic | | | | + * +-----+---------+--------+-----------------------------+-----------------------------------+------------------+-----------+ + */ +#define tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE ( ( ( portUSING_MPU_WRAPPERS == 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) || \ + ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) ) + +/* + * In line with software engineering best practice, FreeRTOS implements a strict + * data hiding policy, so the real structures used by FreeRTOS to maintain the + * state of tasks, queues, semaphores, etc. are not accessible to the application + * code. However, if the application writer wants to statically allocate such + * an object then the size of the object needs to be know. Dummy structures + * that are guaranteed to have the same size and alignment requirements of the + * real objects are used for this purpose. The dummy list and list item + * structures below are used for inclusion in such a dummy structure. + */ +struct xSTATIC_LIST_ITEM +{ + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 4 ]; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy4; + #endif +}; +typedef struct xSTATIC_LIST_ITEM StaticListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +struct xSTATIC_MINI_LIST_ITEM +{ + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + TickType_t xDummy2; + void *pvDummy3[ 2 ]; +}; +typedef struct xSTATIC_MINI_LIST_ITEM StaticMiniListItem_t; + +/* See the comments above the struct xSTATIC_LIST_ITEM definition. */ +typedef struct xSTATIC_LIST +{ + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy1; + #endif + UBaseType_t uxDummy2; + void *pvDummy3; + StaticMiniListItem_t xDummy4; + #if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 1 ) + TickType_t xDummy5; + #endif +} StaticList_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Task structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a task then + * the size of the task object needs to be know. The StaticTask_t structure + * below is provided for this purpose. Its sizes and alignment requirements are + * guaranteed to match those of the genuine structure, no matter which + * architecture is being used, and no matter how the values in FreeRTOSConfig.h + * are set. Its contents are somewhat obfuscated in the hope users will + * recognise that it would be unwise to make direct use of the structure members. + */ +typedef struct xSTATIC_TCB +{ + void *pxDummy1; + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xDummy2; + #endif + StaticListItem_t xDummy3[ 2 ]; + UBaseType_t uxDummy5; + void *pxDummy6; + uint8_t ucDummy7[ configMAX_TASK_NAME_LEN ]; + BaseType_t xDummyCore; + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + void *pxDummy8; + #endif + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxDummy9; + #endif + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy10[ 2 ]; + #endif + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxDummy12[ 2 ]; + #endif + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + void *pxDummy14; + #endif + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvDummy15[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #if ( configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS ) + void *pvDummyLocalStorageCallBack[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + #endif + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulDummy16; + #endif + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + struct _reent xDummy17; + #endif + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + uint32_t ulDummy18; + uint8_t ucDummy19; + #endif + #if ( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + uint8_t uxDummy20; + #endif + + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDummy21; + #endif + #if ( configUSE_POSIX_ERRNO == 1 ) + int iDummy22; + #endif +} StaticTask_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the Queue structure used internally by + * FreeRTOS is not accessible to application code. However, if the application + * writer wants to statically allocate the memory required to create a queue + * then the size of the queue object needs to be know. The StaticQueue_t + * structure below is provided for this purpose. Its sizes and alignment + * requirements are guaranteed to match those of the genuine structure, no + * matter which architecture is being used, and no matter how the values in + * FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in the hope + * users will recognise that it would be unwise to make direct use of the + * structure members. + */ +typedef struct xSTATIC_QUEUE +{ + void *pvDummy1[ 3 ]; + + union + { + void *pvDummy2; + UBaseType_t uxDummy2; + } u; + + StaticList_t xDummy3[ 2 ]; + UBaseType_t uxDummy4[ 3 ]; + uint8_t ucDummy5[ 2 ]; + + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy6; + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + void *pvDummy7; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy8; + uint8_t ucDummy9; + #endif + + portMUX_TYPE xDummy10; + +} StaticQueue_t; +typedef StaticQueue_t StaticSemaphore_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the event group structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create an event group then the size of the event group object needs to be + * know. The StaticEventGroup_t structure below is provided for this purpose. + * Its sizes and alignment requirements are guaranteed to match those of the + * genuine structure, no matter which architecture is being used, and no matter + * how the values in FreeRTOSConfig.h are set. Its contents are somewhat + * obfuscated in the hope users will recognise that it would be unwise to make + * direct use of the structure members. + */ +typedef struct xSTATIC_EVENT_GROUP +{ + TickType_t xDummy1; + StaticList_t xDummy2; + + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy3; + #endif + + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucDummy4; + #endif + + portMUX_TYPE xDummy5; + +} StaticEventGroup_t; + +/* + * In line with software engineering best practice, especially when supplying a + * library that is likely to change in future versions, FreeRTOS implements a + * strict data hiding policy. This means the software timer structure used + * internally by FreeRTOS is not accessible to application code. However, if + * the application writer wants to statically allocate the memory required to + * create a software timer then the size of the queue object needs to be know. + * The StaticTimer_t structure below is provided for this purpose. Its sizes + * and alignment requirements are guaranteed to match those of the genuine + * structure, no matter which architecture is being used, and no matter how the + * values in FreeRTOSConfig.h are set. Its contents are somewhat obfuscated in + * the hope users will recognise that it would be unwise to make direct use of + * the structure members. + */ +typedef struct xSTATIC_TIMER +{ + void *pvDummy1; + StaticListItem_t xDummy2; + TickType_t xDummy3; + void *pvDummy5; + TaskFunction_t pvDummy6; + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy7; + #endif + uint8_t ucDummy8; +} StaticTimer_t; + +/* +* In line with software engineering best practice, especially when supplying a +* library that is likely to change in future versions, FreeRTOS implements a +* strict data hiding policy. This means the stream buffer structure used +* internally by FreeRTOS is not accessible to application code. However, if +* the application writer wants to statically allocate the memory required to +* create a stream buffer then the size of the stream buffer object needs to be +* know. The StaticStreamBuffer_t structure below is provided for this purpose. +* Its size and alignment requirements are guaranteed to match those of the +* genuine structure, no matter which architecture is being used, and no matter +* how the values in FreeRTOSConfig.h are set. Its contents are somewhat +* obfuscated in the hope users will recognise that it would be unwise to make +* direct use of the structure members. +*/ +typedef struct xSTATIC_STREAM_BUFFER +{ + size_t uxDummy1[ 4 ]; + void * pvDummy2[ 3 ]; + uint8_t ucDummy3; + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxDummy4; + #endif + + portMUX_TYPE xDummy5; + +} StaticStreamBuffer_t; + +/* Message buffers are built on stream buffers. */ +typedef StaticStreamBuffer_t StaticMessageBuffer_t; + +#ifdef __cplusplus +} +#endif + +#endif /* INC_FREERTOS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOSConfig.h b/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOSConfig.h new file mode 100644 index 00000000..1796f188 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/FreeRTOSConfig.h @@ -0,0 +1,300 @@ +/* + FreeRTOS V10 - Copyright (C) 2021 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS 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. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +#include "sdkconfig.h" +// The arch-specific FreeRTOSConfig.h in port//include. +#include_next "freertos/FreeRTOSConfig.h" + +#if !(defined(FREERTOS_CONFIG_XTENSA_H) || defined(FREERTOS_CONFIG_RISCV_H)) +#error "Needs architecture-speific FreeRTOSConfig.h!" +#endif + +#ifndef CONFIG_FREERTOS_UNICORE +#define portNUM_PROCESSORS 2 +#else +#define portNUM_PROCESSORS 1 +#endif + +#define configASSERT_2 0 +#define portUSING_MPU_WRAPPERS 0 +#define configUSE_MUTEX 1 + +#define configNUM_THREAD_LOCAL_STORAGE_POINTERS CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS +#define configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS 1 + +/* configASSERT behaviour */ +#ifndef __ASSEMBLER__ +#include + +// If CONFIG_FREERTOS_ASSERT_DISABLE is set then configASSERT is defined empty later in FreeRTOS.h and the macro +// configASSERT_DEFINED remains unset (meaning some warnings are avoided) + +#if defined(CONFIG_FREERTOS_ASSERT_FAIL_PRINT_CONTINUE) +#define configASSERT(a) if (unlikely(!(a))) { \ + esp_rom_printf("%s:%d (%s)- assert failed!\n", __FILE__, __LINE__, \ + __FUNCTION__); \ + } +#elif defined(CONFIG_FREERTOS_ASSERT_FAIL_ABORT) +#define configASSERT(a) assert(a) +#endif + +#if CONFIG_FREERTOS_ASSERT_ON_UNTESTED_FUNCTION +#define UNTESTED_FUNCTION() { esp_rom_printf("Untested FreeRTOS function %s\r\n", __FUNCTION__); configASSERT(false); } while(0) +#else +#define UNTESTED_FUNCTION() +#endif + +#endif /* def __ASSEMBLER__ */ + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * Note that the default heap size is deliberately kept small so that + * the build is more likely to succeed for configurations with limited + * memory. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + *----------------------------------------------------------*/ + +#define configUSE_PREEMPTION 1 +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 1 +#define configRECORD_STACK_HIGH_ADDRESS 1 +#define configTICK_RATE_HZ ( CONFIG_FREERTOS_HZ ) + +/* This has impact on speed of search for highest priority */ +#ifdef SMALL_TEST +#define configMAX_PRIORITIES ( 7 ) +#else +#define configMAX_PRIORITIES ( 25 ) +#endif + +/* Various things that impact minimum stack sizes */ + +/* Higher stack checker modes cause overhead on each function call */ +#if CONFIG_STACK_CHECK_ALL || CONFIG_STACK_CHECK_STRONG +#define configSTACK_OVERHEAD_CHECKER 256 +#else +#define configSTACK_OVERHEAD_CHECKER 0 +#endif + +/* with optimizations disabled, scheduler uses additional stack */ +#if CONFIG_COMPILER_OPTIMIZATION_NONE +#define configSTACK_OVERHEAD_OPTIMIZATION 320 +#else +#define configSTACK_OVERHEAD_OPTIMIZATION 0 +#endif + +/* apptrace mdule increases minimum stack usage */ +#if CONFIG_APPTRACE_ENABLE +#define configSTACK_OVERHEAD_APPTRACE 1280 +#else +#define configSTACK_OVERHEAD_APPTRACE 0 +#endif + +#define configSTACK_OVERHEAD_TOTAL ( \ + configSTACK_OVERHEAD_CHECKER + \ + configSTACK_OVERHEAD_OPTIMIZATION + \ + configSTACK_OVERHEAD_APPTRACE \ + ) + +#define configMINIMAL_STACK_SIZE (768 + configSTACK_OVERHEAD_TOTAL) + +#ifndef configIDLE_TASK_STACK_SIZE +#define configIDLE_TASK_STACK_SIZE CONFIG_FREERTOS_IDLE_TASK_STACKSIZE +#endif + +/* Minimal heap size to make sure examples can run on memory limited + configs. Adjust this to suit your system. */ + + +//We define the heap to span all of the non-statically-allocated shared RAM. ToDo: Make sure there +//is some space left for the app and main cpu when running outside of a thread. +#define configAPPLICATION_ALLOCATED_HEAP 1 +#define configTOTAL_HEAP_SIZE (&_heap_end - &_heap_start)//( ( size_t ) (64 * 1024) ) + +#define configMAX_TASK_NAME_LEN ( CONFIG_FREERTOS_MAX_TASK_NAME_LEN ) + +#ifdef CONFIG_FREERTOS_USE_TRACE_FACILITY +#define configUSE_TRACE_FACILITY 1 /* Used by uxTaskGetSystemState(), and other trace facility functions */ +#endif + +#ifdef CONFIG_FREERTOS_USE_STATS_FORMATTING_FUNCTIONS +#define configUSE_STATS_FORMATTING_FUNCTIONS 1 /* Used by vTaskList() */ +#endif + +#ifdef CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID +#define configTASKLIST_INCLUDE_COREID 1 +#endif + +#ifdef CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS +#define configGENERATE_RUN_TIME_STATS 1 /* Used by vTaskGetRunTimeStats() */ +#endif + +#define configUSE_TRACE_FACILITY_2 0 +#define configBENCHMARK 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 0 +#define configQUEUE_REGISTRY_SIZE CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE + +#define configUSE_MUTEXES 1 +#define configUSE_RECURSIVE_MUTEXES 1 +#define configUSE_COUNTING_SEMAPHORES 1 + +#if CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE +#define configCHECK_FOR_STACK_OVERFLOW 0 +#elif CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL +#define configCHECK_FOR_STACK_OVERFLOW 1 +#elif CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY +#define configCHECK_FOR_STACK_OVERFLOW 2 +#endif + + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 +#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) + +/* Set the following definitions to 1 to include the API function, or zero + to exclude the API function. */ + +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 0 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_uxTaskGetStackHighWaterMark 1 +#define INCLUDE_pcTaskGetTaskName 1 +#define INCLUDE_xTaskGetIdleTaskHandle 1 +#define INCLUDE_pxTaskGetStackStart 1 + +#define INCLUDE_xSemaphoreGetMutexHolder 1 + +/* The priority at which the tick interrupt runs. This should probably be + kept at 1. */ +#define configKERNEL_INTERRUPT_PRIORITY 1 + +#define configUSE_NEWLIB_REENTRANT 1 + +#define configSUPPORT_DYNAMIC_ALLOCATION 1 +#define configSUPPORT_STATIC_ALLOCATION 1 + +#ifndef __ASSEMBLER__ +#if CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP +extern void vPortCleanUpTCB ( void *pxTCB ); +#define portCLEAN_UP_TCB( pxTCB ) vPortCleanUpTCB( pxTCB ) +#endif +#endif + +/* Test FreeRTOS timers (with timer task) and more. */ +/* Some files don't compile if this flag is disabled */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY +#define configTIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH +#define configTIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH + +#define INCLUDE_xTimerPendFunctionCall 1 +#define INCLUDE_eTaskGetState 1 +#define configUSE_QUEUE_SETS 1 + +#define configUSE_TICKLESS_IDLE CONFIG_FREERTOS_USE_TICKLESS_IDLE +#if configUSE_TICKLESS_IDLE +#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP CONFIG_FREERTOS_IDLE_TIME_BEFORE_SLEEP +#endif //configUSE_TICKLESS_IDLE + + +#if CONFIG_ESP_COREDUMP_ENABLE +#define configENABLE_TASK_SNAPSHOT 1 +#endif +#ifndef configENABLE_TASK_SNAPSHOT +#define configENABLE_TASK_SNAPSHOT 1 +#endif + +#if CONFIG_SYSVIEW_ENABLE +#ifndef __ASSEMBLER__ +#include "SEGGER_SYSVIEW_FreeRTOS.h" +#undef INLINE // to avoid redefinition +#endif /* def __ASSEMBLER__ */ +#endif + +#if CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER +#define configCHECK_MUTEX_GIVEN_BY_OWNER 1 +#else +#define configCHECK_MUTEX_GIVEN_BY_OWNER 0 +#endif + +#endif /* FREERTOS_CONFIG_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/atomic.h b/tools/sdk/esp32c3/include/freertos/include/freertos/atomic.h new file mode 100644 index 00000000..df52a0f0 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/atomic.h @@ -0,0 +1,418 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/** + * @file atomic.h + * @brief FreeRTOS atomic operation support. + * + * This file implements atomic by disabling interrupts globally. + * Implementation with architecture specific atomic instructions + * are to be provided under each compiler directory. + */ + +#ifndef ATOMIC_H +#define ATOMIC_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include atomic.h" +#endif + +/* Standard includes. */ +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Port specific definitions -- entering/exiting critical section. + * Refer template -- ./lib/FreeRTOS/portable/Compiler/Arch/portmacro.h + * + * Every call to ATOMIC_EXIT_CRITICAL() must be closely paired with + * ATOMIC_ENTER_CRITICAL(). + * */ +#if defined( portSET_INTERRUPT_MASK_FROM_ISR ) + + /* Nested interrupt scheme is supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() \ + UBaseType_t uxCriticalSectionType = portSET_INTERRUPT_MASK_FROM_ISR() + + #define ATOMIC_EXIT_CRITICAL() \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxCriticalSectionType ) + +#else + + /* Nested interrupt scheme is NOT supported in this port. */ + #define ATOMIC_ENTER_CRITICAL() portENTER_CRITICAL() + #define ATOMIC_EXIT_CRITICAL() portEXIT_CRITICAL() + +#endif /* portSET_INTERRUPT_MASK_FROM_ISR() */ + +/* Port specific definition -- "always inline". + * Inline is compiler specific, and may not always get inlined depending on your optimization level. + * Also, inline is considerred as performance optimization for atomic. + * Thus, if portFORCE_INLINE is not provided by portmacro.h, instead of resulting error, + * simply define it. + */ +#ifndef portFORCE_INLINE + #define portFORCE_INLINE +#endif + +#define ATOMIC_COMPARE_AND_SWAP_SUCCESS 0x1U /**< Compare and swap succeeded, swapped. */ +#define ATOMIC_COMPARE_AND_SWAP_FAILURE 0x0U /**< Compare and swap failed, did not swap. */ + +/*----------------------------- Swap && CAS ------------------------------*/ + +/** + * Atomic compare-and-swap + * + * @brief Performs an atomic compare-and-swap operation on the specified values. + * + * @param[in, out] pDestination Pointer to memory location from where value is + * to be loaded and checked. + * @param[in] ulExchange If condition meets, write this value to memory. + * @param[in] ulComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *pDestination with ulExchange, if previous + * *pDestination value equals ulComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwap_u32( + uint32_t volatile * pDestination, + uint32_t ulExchange, + uint32_t ulComparand ) +{ + + uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + + ATOMIC_ENTER_CRITICAL(); + + if ( *pDestination == ulComparand ) + { + *pDestination = ulExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; + +} + +/** + * Atomic swap (pointers) + * + * @brief Atomically sets the address pointed to by *ppDestination to the value + * of *pExchange. + * + * @param[in, out] ppDestination Pointer to memory location from where a pointer + * value is to be loaded and written back to. + * @param[in] pExchange Pointer value to be written to *ppDestination. + * + * @return The initial value of *ppDestination. + */ +static portFORCE_INLINE void * Atomic_SwapPointers_p32( + void * volatile * ppDestination, + void * pExchange ) +{ + void * pReturnValue; + + ATOMIC_ENTER_CRITICAL(); + + pReturnValue = *ppDestination; + + *ppDestination = pExchange; + + ATOMIC_EXIT_CRITICAL(); + + return pReturnValue; +} + +/** + * Atomic compare-and-swap (pointers) + * + * @brief Performs an atomic compare-and-swap operation on the specified pointer + * values. + * + * @param[in, out] ppDestination Pointer to memory location from where a pointer + * value is to be loaded and checked. + * @param[in] pExchange If condition meets, write this value to memory. + * @param[in] pComparand Swap condition. + * + * @return Unsigned integer of value 1 or 0. 1 for swapped, 0 for not swapped. + * + * @note This function only swaps *ppDestination with pExchange, if previous + * *ppDestination value equals pComparand. + */ +static portFORCE_INLINE uint32_t Atomic_CompareAndSwapPointers_p32( + void * volatile * ppDestination, + void * pExchange, void * pComparand ) +{ + uint32_t ulReturnValue = ATOMIC_COMPARE_AND_SWAP_FAILURE; + + ATOMIC_ENTER_CRITICAL(); + + if ( *ppDestination == pComparand ) + { + *ppDestination = pExchange; + ulReturnValue = ATOMIC_COMPARE_AND_SWAP_SUCCESS; + } + + ATOMIC_EXIT_CRITICAL(); + + return ulReturnValue; +} + + +/*----------------------------- Arithmetic ------------------------------*/ + +/** + * Atomic add + * + * @brief Atomically adds count to the value of the specified pointer points to. + * + * @param[in,out] pAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be added to *pAddend. + * + * @return previous *pAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Add_u32( + uint32_t volatile * pAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pAddend; + + *pAddend += ulCount; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic subtract + * + * @brief Atomically subtracts count from the value of the specified pointer + * pointers to. + * + * @param[in,out] pAddend Pointer to memory location from where value is to be + * loaded and written back to. + * @param[in] ulCount Value to be subtract from *pAddend. + * + * @return previous *pAddend value. + */ +static portFORCE_INLINE uint32_t Atomic_Subtract_u32( + uint32_t volatile * pAddend, + uint32_t ulCount ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pAddend; + + *pAddend -= ulCount; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic increment + * + * @brief Atomically increments the value of the specified pointer points to. + * + * @param[in,out] pAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pAddend value before increment. + */ +static portFORCE_INLINE uint32_t Atomic_Increment_u32( uint32_t volatile * pAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pAddend; + + *pAddend += 1; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic decrement + * + * @brief Atomically decrements the value of the specified pointer points to + * + * @param[in,out] pAddend Pointer to memory location from where value is to be + * loaded and written back to. + * + * @return *pAddend value before decrement. + */ +static portFORCE_INLINE uint32_t Atomic_Decrement_u32( uint32_t volatile * pAddend ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pAddend; + + *pAddend -= 1; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/*----------------------------- Bitwise Logical ------------------------------*/ + +/** + * Atomic OR + * + * @brief Performs an atomic OR operation on the specified values. + * + * @param [in, out] pDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ORed with *pDestination. + * + * @return The original value of *pDestination. + */ +static portFORCE_INLINE uint32_t Atomic_OR_u32( + uint32_t volatile * pDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pDestination; + + *pDestination |= ulValue; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic AND + * + * @brief Performs an atomic AND operation on the specified values. + * + * @param [in, out] pDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be ANDed with *pDestination. + * + * @return The original value of *pDestination. + */ +static portFORCE_INLINE uint32_t Atomic_AND_u32( + uint32_t volatile * pDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pDestination; + + *pDestination &= ulValue; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic NAND + * + * @brief Performs an atomic NAND operation on the specified values. + * + * @param [in, out] pDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be NANDed with *pDestination. + * + * @return The original value of *pDestination. + */ +static portFORCE_INLINE uint32_t Atomic_NAND_u32( + uint32_t volatile * pDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pDestination; + + *pDestination = ~(ulCurrent & ulValue); + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +/** + * Atomic XOR + * + * @brief Performs an atomic XOR operation on the specified values. + * + * @param [in, out] pDestination Pointer to memory location from where value is + * to be loaded and written back to. + * @param [in] ulValue Value to be XORed with *pDestination. + * + * @return The original value of *pDestination. + */ +static portFORCE_INLINE uint32_t Atomic_XOR_u32( + uint32_t volatile * pDestination, + uint32_t ulValue ) +{ + uint32_t ulCurrent; + + ATOMIC_ENTER_CRITICAL(); + + ulCurrent = *pDestination; + + *pDestination ^= ulValue; + + ATOMIC_EXIT_CRITICAL(); + + return ulCurrent; +} + +#ifdef __cplusplus +} +#endif + +#endif /* ATOMIC_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/croutine.h b/tools/sdk/esp32c3/include/freertos/include/freertos/croutine.h new file mode 100644 index 00000000..8b3b41b9 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/croutine.h @@ -0,0 +1,720 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef CO_ROUTINE_H +#define CO_ROUTINE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include croutine.h" +#endif + +#include "list.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Used to hide the implementation of the co-routine control block. The +control block structure however has to be included in the header due to +the macro implementation of the co-routine functionality. */ +typedef void * CoRoutineHandle_t; + +/* Defines the prototype to which co-routine functions must conform. */ +typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t ); + +typedef struct corCoRoutineControlBlock +{ + crCOROUTINE_CODE pxCoRoutineFunction; + ListItem_t xGenericListItem; /*< List item used to place the CRCB in ready and blocked queues. */ + ListItem_t xEventListItem; /*< List item used to place the CRCB in event lists. */ + UBaseType_t uxPriority; /*< The priority of the co-routine in relation to other co-routines. */ + UBaseType_t uxIndex; /*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */ + uint16_t uxState; /*< Used internally by the co-routine implementation. */ +} CRCB_t; /* Co-routine control block. Note must be identical in size down to uxPriority with TCB_t. */ + +/** + * croutine. h + *
+ BaseType_t xCoRoutineCreate(
+                                 crCOROUTINE_CODE pxCoRoutineCode,
+                                 UBaseType_t uxPriority,
+                                 UBaseType_t uxIndex
+                               );
+ * + * Create a new co-routine and add it to the list of co-routines that are + * ready to run. + * + * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine + * functions require special syntax - see the co-routine section of the WEB + * documentation for more information. + * + * @param uxPriority The priority with respect to other co-routines at which + * the co-routine will run. + * + * @param uxIndex Used to distinguish between different co-routines that + * execute the same function. See the example below and the co-routine section + * of the WEB documentation for further information. + * + * @return pdPASS if the co-routine was successfully created and added to a ready + * list, otherwise an error code defined with ProjDefs.h. + * + * Example usage: +
+ // Co-routine to be created.
+ void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ static const char cLedToFlash[ 2 ] = { 5, 6 };
+ static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // This co-routine just delays for a fixed period, then toggles
+         // an LED.  Two co-routines are created using this function, so
+         // the uxIndex parameter is used to tell the co-routine which
+         // LED to flash and how int32_t to delay.  This assumes xQueue has
+         // already been created.
+         vParTestToggleLED( cLedToFlash[ uxIndex ] );
+         crDELAY( xHandle, uxFlashRates[ uxIndex ] );
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }
+
+ // Function that creates two co-routines.
+ void vOtherFunction( void )
+ {
+ uint8_t ucParameterToPass;
+ TaskHandle_t xHandle;
+
+     // Create two co-routines at priority 0.  The first is given index 0
+     // so (from the code above) toggles LED 5 every 200 ticks.  The second
+     // is given index 1 so toggles LED 6 every 400 ticks.
+     for( uxIndex = 0; uxIndex < 2; uxIndex++ )
+     {
+         xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
+     }
+ }
+   
+ * \defgroup xCoRoutineCreate xCoRoutineCreate + * \ingroup Tasks + */ +BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex ); + + +/** + * croutine. h + *
+ void vCoRoutineSchedule( void );
+ * + * Run a co-routine. + * + * vCoRoutineSchedule() executes the highest priority co-routine that is able + * to run. The co-routine will execute until it either blocks, yields or is + * preempted by a task. Co-routines execute cooperatively so one + * co-routine cannot be preempted by another, but can be preempted by a task. + * + * If an application comprises of both tasks and co-routines then + * vCoRoutineSchedule should be called from the idle task (in an idle task + * hook). + * + * Example usage: +
+ // This idle task hook will schedule a co-routine each time it is called.
+ // The rest of the idle task will execute between co-routine calls.
+ void vApplicationIdleHook( void )
+ {
+	vCoRoutineSchedule();
+ }
+
+ // Alternatively, if you do not require any other part of the idle task to
+ // execute, the idle task hook can call vCoRoutineScheduler() within an
+ // infinite loop.
+ void vApplicationIdleHook( void )
+ {
+    for( ;; )
+    {
+        vCoRoutineSchedule();
+    }
+ }
+ 
+ * \defgroup vCoRoutineSchedule vCoRoutineSchedule + * \ingroup Tasks + */ +void vCoRoutineSchedule( void ); + +/** + * croutine. h + *
+ crSTART( CoRoutineHandle_t xHandle );
+ * + * This macro MUST always be called at the start of a co-routine function. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+          // Co-routine functionality goes here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }
+ * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0: + +/** + * croutine. h + *
+ crEND();
+ * + * This macro MUST always be called at the end of a co-routine function. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+          // Co-routine functionality goes here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }
+ * \defgroup crSTART crSTART + * \ingroup Tasks + */ +#define crEND() } + +/* + * These macros are intended for internal use by the co-routine implementation + * only. The macros should not be used directly by application writers. + */ +#define crSET_STATE0( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2): +#define crSET_STATE1( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1): + +/** + * croutine. h + *
+ crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );
+ * + * Delay a co-routine for a fixed period of time. + * + * crDELAY can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * @param xHandle The handle of the co-routine to delay. This is the xHandle + * parameter of the co-routine function. + * + * @param xTickToDelay The number of ticks that the co-routine should delay + * for. The actual amount of time this equates to is defined by + * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS + * can be used to convert ticks to milliseconds. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ // We are to delay for 200ms.
+ static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+        // Delay for 200ms.
+        crDELAY( xHandle, xDelayTime );
+
+        // Do something here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }
+ * \defgroup crDELAY crDELAY + * \ingroup Tasks + */ +#define crDELAY( xHandle, xTicksToDelay ) \ + if( ( xTicksToDelay ) > 0 ) \ + { \ + vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \ + } \ + crSET_STATE0( ( xHandle ) ); + +/** + *
+ crQUEUE_SEND(
+                  CoRoutineHandle_t xHandle,
+                  QueueHandle_t pxQueue,
+                  void *pvItemToQueue,
+                  TickType_t xTicksToWait,
+                  BaseType_t *pxResult
+             )
+ * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_SEND can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue on which the data will be posted. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvItemToQueue A pointer to the data being posted onto the queue. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied from pvItemToQueue into the queue + * itself. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for space to become available on the queue, should space not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example + * below). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully posted onto the queue, otherwise it will be set to an + * error defined within ProjDefs.h. + * + * Example usage: +
+ // Co-routine function that blocks for a fixed period then posts a number onto
+ // a queue.
+ static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xNumberToPost = 0;
+ static BaseType_t xResult;
+
+    // Co-routines must begin with a call to crSTART().
+    crSTART( xHandle );
+
+    for( ;; )
+    {
+        // This assumes the queue has already been created.
+        crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
+
+        if( xResult != pdPASS )
+        {
+            // The message was not posted!
+        }
+
+        // Increment the number to be posted onto the queue.
+        xNumberToPost++;
+
+        // Delay for 100 ticks.
+        crDELAY( xHandle, 100 );
+    }
+
+    // Co-routines must end with a call to crEND().
+    crEND();
+ }
+ * \defgroup crQUEUE_SEND crQUEUE_SEND + * \ingroup Tasks + */ +#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \ +{ \ + *( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \ + } \ + if( *pxResult == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *pxResult = pdPASS; \ + } \ +} + +/** + * croutine. h + *
+  crQUEUE_RECEIVE(
+                     CoRoutineHandle_t xHandle,
+                     QueueHandle_t pxQueue,
+                     void *pvBuffer,
+                     TickType_t xTicksToWait,
+                     BaseType_t *pxResult
+                 )
+ * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_RECEIVE can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue from which the data will be received. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvBuffer The buffer into which the received item is to be copied. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied into pvBuffer. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for data to become available from the queue, should data not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the + * crQUEUE_SEND example). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully retrieved from the queue, otherwise it will be set to + * an error code as defined within ProjDefs.h. + * + * Example usage: +
+ // A co-routine receives the number of an LED to flash from a queue.  It
+ // blocks on the queue until the number is received.
+ static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xResult;
+ static UBaseType_t uxLEDToFlash;
+
+    // All co-routines must start with a call to crSTART().
+    crSTART( xHandle );
+
+    for( ;; )
+    {
+        // Wait for data to become available on the queue.
+        crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+        if( xResult == pdPASS )
+        {
+            // We received the LED to flash - flash it!
+            vParTestToggleLED( uxLEDToFlash );
+        }
+    }
+
+    crEND();
+ }
+ * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \ +{ \ + *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) ); \ + if( *( pxResult ) == errQUEUE_BLOCKED ) \ + { \ + crSET_STATE0( ( xHandle ) ); \ + *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 ); \ + } \ + if( *( pxResult ) == errQUEUE_YIELD ) \ + { \ + crSET_STATE1( ( xHandle ) ); \ + *( pxResult ) = pdPASS; \ + } \ +} + +/** + * croutine. h + *
+  crQUEUE_SEND_FROM_ISR(
+                            QueueHandle_t pxQueue,
+                            void *pvItemToQueue,
+                            BaseType_t xCoRoutinePreviouslyWoken
+                       )
+ * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue + * that is being used from within a co-routine. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto + * the same queue multiple times from a single interrupt. The first call + * should always pass in pdFALSE. Subsequent calls should pass in + * the value returned from the previous call. + * + * @return pdTRUE if a co-routine was woken by posting onto the queue. This is + * used by the ISR to determine if a context switch may be required following + * the ISR. + * + * Example usage: +
+ // A co-routine that blocks on a queue waiting for characters to be received.
+ static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ char cRxedChar;
+ BaseType_t xResult;
+
+     // All co-routines must start with a call to crSTART().
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // Wait for data to become available on the queue.  This assumes the
+         // queue xCommsRxQueue has already been created!
+         crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+         // Was a character received?
+         if( xResult == pdPASS )
+         {
+             // Process the character here.
+         }
+     }
+
+     // All co-routines must end with a call to crEND().
+     crEND();
+ }
+
+ // An ISR that uses a queue to send characters received on a serial port to
+ // a co-routine.
+ void vUART_ISR( void )
+ {
+ char cRxedChar;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+     // We loop around reading characters until there are none left in the UART.
+     while( UART_RX_REG_NOT_EMPTY() )
+     {
+         // Obtain the character from the UART.
+         cRxedChar = UART_RX_REG;
+
+         // Post the character onto a queue.  xCRWokenByPost will be pdFALSE
+         // the first time around the loop.  If the post causes a co-routine
+         // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
+         // In this manner we can ensure that if more than one co-routine is
+         // blocked on the queue only one is woken by this ISR no matter how
+         // many characters are posted to the queue.
+         xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
+     }
+ }
+ * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) ) + + +/** + * croutine. h + *
+  crQUEUE_SEND_FROM_ISR(
+                            QueueHandle_t pxQueue,
+                            void *pvBuffer,
+                            BaseType_t * pxCoRoutineWoken
+                       )
+ * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data + * from a queue that is being used from within a co-routine (a co-routine + * posted to the queue). + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvBuffer A pointer to a buffer into which the received item will be + * placed. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from the queue into + * pvBuffer. + * + * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become + * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a + * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise + * *pxCoRoutineWoken will remain unchanged. + * + * @return pdTRUE an item was successfully received from the queue, otherwise + * pdFALSE. + * + * Example usage: +
+ // A co-routine that posts a character to a queue then blocks for a fixed
+ // period.  The character is incremented each time.
+ static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // cChar holds its value while this co-routine is blocked and must therefore
+ // be declared static.
+ static char cCharToTx = 'a';
+ BaseType_t xResult;
+
+     // All co-routines must start with a call to crSTART().
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // Send the next character to the queue.
+         crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
+
+         if( xResult == pdPASS )
+         {
+             // The character was successfully posted to the queue.
+         }
+		 else
+		 {
+			// Could not post the character to the queue.
+		 }
+
+         // Enable the UART Tx interrupt to cause an interrupt in this
+		 // hypothetical UART.  The interrupt will obtain the character
+		 // from the queue and send it.
+		 ENABLE_RX_INTERRUPT();
+
+		 // Increment to the next character then block for a fixed period.
+		 // cCharToTx will maintain its value across the delay as it is
+		 // declared static.
+		 cCharToTx++;
+		 if( cCharToTx > 'x' )
+		 {
+			cCharToTx = 'a';
+		 }
+		 crDELAY( 100 );
+     }
+
+     // All co-routines must end with a call to crEND().
+     crEND();
+ }
+
+ // An ISR that uses a queue to receive characters to send on a UART.
+ void vUART_ISR( void )
+ {
+ char cCharToTx;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+     while( UART_TX_REG_EMPTY() )
+     {
+         // Are there any characters in the queue waiting to be sent?
+		 // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
+		 // is woken by the post - ensuring that only a single co-routine is
+		 // woken no matter how many times we go around this loop.
+         if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
+		 {
+			 SEND_CHARACTER( cCharToTx );
+		 }
+     }
+ }
+ * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR + * \ingroup Tasks + */ +#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) ) + +/* + * This function is intended for internal use by the co-routine macros only. + * The macro nature of the co-routine implementation requires that the + * prototype appears here. The function should not be used by application + * writers. + * + * Removes the current co-routine from its ready list and places it in the + * appropriate delayed list. + */ +void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList ); + +/* + * This function is intended for internal use by the queue implementation only. + * The function should not be used by application writers. + * + * Removes the highest priority co-routine from the event list and places it in + * the pending ready list. + */ +BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList ); + +#ifdef __cplusplus +} +#endif + +#endif /* CO_ROUTINE_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/deprecated_definitions.h b/tools/sdk/esp32c3/include/freertos/include/freertos/deprecated_definitions.h new file mode 100644 index 00000000..70fc403b --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/deprecated_definitions.h @@ -0,0 +1,278 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef DEPRECATED_DEFINITIONS_H +#define DEPRECATED_DEFINITIONS_H + + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a +pre-processor definition was used to ensure the pre-processor found the correct +portmacro.h file for the port being used. That scheme was deprecated in favour +of setting the compiler's include path such that it found the correct +portmacro.h file - removing the need for the constant and allowing the +portmacro.h file to be located anywhere in relation to the port being used. The +definitions below remain in the code for backward compatibility only. New +projects should not use them. */ + +#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT + #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); +#endif + +#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT + #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h" + typedef void ( __interrupt __far *pxISR )(); +#endif + +#ifdef GCC_MEGA_AVR + #include "../portable/GCC/ATMega323/portmacro.h" +#endif + +#ifdef IAR_MEGA_AVR + #include "../portable/IAR/ATMega323/portmacro.h" +#endif + +#ifdef MPLAB_PIC24_PORT + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" +#endif + +#ifdef MPLAB_DSPIC_PORT + #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h" +#endif + +#ifdef MPLAB_PIC18F_PORT + #include "../../Source/portable/MPLAB/PIC18F/portmacro.h" +#endif + +#ifdef MPLAB_PIC32MX_PORT + #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h" +#endif + +#ifdef _FEDPICC + #include "libFreeRTOS/Include/portmacro.h" +#endif + +#ifdef SDCC_CYGNAL + #include "../../Source/portable/SDCC/Cygnal/portmacro.h" +#endif + +#ifdef GCC_ARM7 + #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h" +#endif + +#ifdef GCC_ARM7_ECLIPSE + #include "portmacro.h" +#endif + +#ifdef ROWLEY_LPC23xx + #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h" +#endif + +#ifdef IAR_MSP430 + #include "..\..\Source\portable\IAR\MSP430\portmacro.h" +#endif + +#ifdef GCC_MSP430 + #include "../../Source/portable/GCC/MSP430F449/portmacro.h" +#endif + +#ifdef ROWLEY_MSP430 + #include "../../Source/portable/Rowley/MSP430F449/portmacro.h" +#endif + +#ifdef ARM7_LPC21xx_KEIL_RVDS + #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h" +#endif + +#ifdef SAM7_GCC + #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h" +#endif + +#ifdef SAM7_IAR + #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h" +#endif + +#ifdef SAM9XE_IAR + #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h" +#endif + +#ifdef LPC2000_IAR + #include "..\..\Source\portable\IAR\LPC2000\portmacro.h" +#endif + +#ifdef STR71X_IAR + #include "..\..\Source\portable\IAR\STR71x\portmacro.h" +#endif + +#ifdef STR75X_IAR + #include "..\..\Source\portable\IAR\STR75x\portmacro.h" +#endif + +#ifdef STR75X_GCC + #include "..\..\Source\portable\GCC\STR75x\portmacro.h" +#endif + +#ifdef STR91X_IAR + #include "..\..\Source\portable\IAR\STR91x\portmacro.h" +#endif + +#ifdef GCC_H8S + #include "../../Source/portable/GCC/H8S2329/portmacro.h" +#endif + +#ifdef GCC_AT91FR40008 + #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h" +#endif + +#ifdef RVDS_ARMCM3_LM3S102 + #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h" +#endif + +#ifdef GCC_ARMCM3_LM3S102 + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" +#endif + +#ifdef GCC_ARMCM3 + #include "../../Source/portable/GCC/ARM_CM3/portmacro.h" +#endif + +#ifdef IAR_ARM_CM3 + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" +#endif + +#ifdef IAR_ARMCM3_LM + #include "../../Source/portable/IAR/ARM_CM3/portmacro.h" +#endif + +#ifdef HCS12_CODE_WARRIOR + #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h" +#endif + +#ifdef MICROBLAZE_GCC + #include "../../Source/portable/GCC/MicroBlaze/portmacro.h" +#endif + +#ifdef TERN_EE + #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h" +#endif + +#ifdef GCC_HCS12 + #include "../../Source/portable/GCC/HCS12/portmacro.h" +#endif + +#ifdef GCC_MCF5235 + #include "../../Source/portable/GCC/MCF5235/portmacro.h" +#endif + +#ifdef COLDFIRE_V2_GCC + #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h" +#endif + +#ifdef COLDFIRE_V2_CODEWARRIOR + #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h" +#endif + +#ifdef GCC_PPC405 + #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h" +#endif + +#ifdef GCC_PPC440 + #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h" +#endif + +#ifdef _16FX_SOFTUNE + #include "..\..\Source\portable\Softune\MB96340\portmacro.h" +#endif + +#ifdef BCC_INDUSTRIAL_PC_PORT + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\PC\prtmacro.h" + typedef void ( __interrupt __far *pxISR )(); +#endif + +#ifdef BCC_FLASH_LITE_186_PORT + /* A short file name has to be used in place of the normal + FreeRTOSConfig.h when using the Borland compiler. */ + #include "frconfig.h" + #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h" + typedef void ( __interrupt __far *pxISR )(); +#endif + +#ifdef __GNUC__ + #ifdef __AVR32_AVR32A__ + #include "portmacro.h" + #endif +#endif + +#ifdef __ICCAVR32__ + #ifdef __CORE__ + #if __CORE__ == __AVR32A__ + #include "portmacro.h" + #endif + #endif +#endif + +#ifdef __91467D + #include "portmacro.h" +#endif + +#ifdef __96340 + #include "portmacro.h" +#endif + + +#ifdef __IAR_V850ES_Fx3__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx3__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx3_L__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Jx2__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_V850ES_Hx2__ + #include "../../Source/portable/IAR/V850ES/portmacro.h" +#endif + +#ifdef __IAR_78K0R_Kx3__ + #include "../../Source/portable/IAR/78K0R/portmacro.h" +#endif + +#ifdef __IAR_78K0R_Kx3L__ + #include "../../Source/portable/IAR/78K0R/portmacro.h" +#endif + +#endif /* DEPRECATED_DEFINITIONS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/event_groups.h b/tools/sdk/esp32c3/include/freertos/include/freertos/event_groups.h new file mode 100644 index 00000000..5773e8d9 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/event_groups.h @@ -0,0 +1,697 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef EVENT_GROUPS_H +#define EVENT_GROUPS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include event_groups.h" +#endif + +/* FreeRTOS includes. */ +#include "timers.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * An event group is a collection of bits to which an application can assign a + * meaning. For example, an application may create an event group to convey + * the status of various CAN bus related events in which bit 0 might mean "A CAN + * message has been received and is ready for processing", bit 1 might mean "The + * application has queued a message that is ready for sending onto the CAN + * network", and bit 2 might mean "It is time to send a SYNC message onto the + * CAN network" etc. A task can then test the bit values to see which events + * are active, and optionally enter the Blocked state to wait for a specified + * bit or a group of specified bits to be active. To continue the CAN bus + * example, a CAN controlling task can enter the Blocked state (and therefore + * not consume any processing time) until either bit 0, bit 1 or bit 2 are + * active, at which time the bit that was actually active would inform the task + * which action it had to take (process a received message, send a message, or + * send a SYNC). + * + * The event groups implementation contains intelligence to avoid race + * conditions that would otherwise occur were an application to use a simple + * variable for the same purpose. This is particularly important with respect + * to when a bit within an event group is to be cleared, and when bits have to + * be set and then tested atomically - as is the case where event groups are + * used to create a synchronisation point between multiple tasks (a + * 'rendezvous'). + * + */ + + + +/** + * event_groups.h + * + * Type by which event groups are referenced. For example, a call to + * xEventGroupCreate() returns an EventGroupHandle_t variable that can then + * be used as a parameter to other event group functions. + * + * \defgroup EventGroupHandle_t EventGroupHandle_t + * \ingroup EventGroup + */ +struct EventGroupDef_t; +//typedef struct EventGroupDef_t * EventGroupHandle_t; +typedef void * EventGroupHandle_t; + +/* + * The type that holds event bits always matches TickType_t - therefore the + * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1, + * 32 bits if set to 0. + * + * \defgroup EventBits_t EventBits_t + * \ingroup EventGroup + */ +typedef TickType_t EventBits_t; + +/** + * + * + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGropuCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see http://www.freertos.org/a00111.html). If an event group is created + * using xEventGropuCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @return If the event group was created then a handle to the event group is + * returned. If there was insufficient FreeRTOS heap available to create the + * event group then NULL is returned. See http://www.freertos.org/a00111.html + * + * Example usage: + * @code{c} + * // Declare a variable to hold the created event group. + * EventGroupHandle_t xCreatedEventGroup; + * + * // Attempt to create the event group. + * xCreatedEventGroup = xEventGroupCreate(); + * + * // Was the event group created successfully? + * if( xCreatedEventGroup == NULL ) + * { + * // The event group was not created because there was insufficient + * // FreeRTOS heap available. + * } + * else + * { + * // The event group was created. + * } + * @endcode + * \ingroup EventGroup + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION; +#endif + +/** + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGropuCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see http://www.freertos.org/a00111.html). If an event group is created + * using xEventGropuCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type + * StaticEventGroup_t, which will be then be used to hold the event group's data + * structures, removing the need for the memory to be allocated dynamically. + * + * @return If the event group was created then a handle to the event group is + * returned. If pxEventGroupBuffer was NULL then NULL is returned. + * + * Example usage: + * @code{c} + * // StaticEventGroup_t is a publicly accessible structure that has the same + * // size and alignment requirements as the real event group structure. It is + * // provided as a mechanism for applications to know the size of the event + * // group (which is dependent on the architecture and configuration file + * // settings) without breaking the strict data hiding policy by exposing the + * // real event group internals. This StaticEventGroup_t variable is passed + * // into the xSemaphoreCreateEventGroupStatic() function and is used to store + * // the event group's data structures + * StaticEventGroup_t xEventGroupBuffer; + * + * // Create the event group without dynamically allocating any memory. + * xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); + * @endcode + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; +#endif + +/** + * [Potentially] block to wait for one or more bits to be set within a + * previously created event group. + * + * This function cannot be called from an interrupt. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and/or bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within + * uxBitsToWaitFor that are set within the event group will be cleared before + * xEventGroupWaitBits() returns if the wait condition was met (if the function + * returns for a reason other than a timeout). If xClearOnExit is set to + * pdFALSE then the bits set in the event group are not altered when the call to + * xEventGroupWaitBits() returns. + * + * @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then + * xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor + * are set or the specified block time expires. If xWaitForAllBits is set to + * pdFALSE then xEventGroupWaitBits() will return when any one of the bits set + * in uxBitsToWaitFor is set or the specified block time expires. The block + * time is specified by the xTicksToWait parameter. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for one/all (depending on the xWaitForAllBits value) of the bits specified by + * uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupWaitBits() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupWaitBits() returned because the bits it was waiting for were set + * then the returned value is the event group value before any bits were + * automatically cleared in the case that xClearOnExit parameter was set to + * pdTRUE. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; + * + * // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within + * // the event group. Clear the bits before exiting. + * uxBits = xEventGroupWaitBits( + * xEventGroup, // The event group being tested. + * BIT_0 | BIT_4, // The bits within the event group to wait for. + * pdTRUE, // BIT_0 and BIT_4 should be cleared before returning. + * pdFALSE, // Don't wait for both bits, either bit will do. + * xTicksToWait ); // Wait a maximum of 100ms for either bit to be set. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // xEventGroupWaitBits() returned because both bits were set. + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // xEventGroupWaitBits() returned because just BIT_0 was set. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // xEventGroupWaitBits() returned because just BIT_4 was set. + * } + * else + * { + * // xEventGroupWaitBits() returned because xTicksToWait ticks passed + * // without either BIT_0 or BIT_4 becoming set. + * } + * } + * @endcode{c} + * \ingroup EventGroup + */ +EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * + * Clear bits within an event group. This function cannot be called from an + * interrupt. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear + * in the event group. For example, to clear bit 3 only, set uxBitsToClear to + * 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. + * + * @return The value of the event group before the specified bits were cleared. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * + * // Clear bit 0 and bit 4 in xEventGroup. + * uxBits = xEventGroupClearBits( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 );// The bits being cleared. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // Both bit 0 and bit 4 were set before xEventGroupClearBits() was + * // called. Both will now be clear (not set). + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // Bit 0 was set before xEventGroupClearBits() was called. It will + * // now be clear. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // Bit 4 was set before xEventGroupClearBits() was called. It will + * // now be clear. + * } + * else + * { + * // Neither bit 0 nor bit 4 were set in the first place. + * } + * } + * @endcode + * \ingroup EventGroup + */ +EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; + +/** + * + * A version of xEventGroupClearBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed + * while interrupts are disabled, so protects event groups that are accessed + * from tasks by suspending the scheduler rather than disabling interrupts. As + * a result event groups cannot be accessed directly from an interrupt service + * routine. Therefore xEventGroupClearBitsFromISR() sends a message to the + * timer task to have the clear operation performed in the context of the timer + * task. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear. + * For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 + * and bit 0 set uxBitsToClear to 0x09. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * // An event group which it is assumed has already been created by a call to + * // xEventGroupCreate(). + * EventGroupHandle_t xEventGroup; + * + * void anInterruptHandler( void ) + * { + * // Clear bit 0 and bit 4 in xEventGroup. + * xResult = xEventGroupClearBitsFromISR( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 ); // The bits being set. + * + * if( xResult == pdPASS ) + * { + * // The message was posted successfully. + * } + * } + * @endcode + * \ingroup EventGroup + */ +#if( configUSE_TRACE_FACILITY == 1 ) + BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION; +#else + #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ) +#endif + +/** + * + * Set bits within an event group. + * This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() + * is a version that can be called from an interrupt. + * + * Setting bits in an event group will automatically unblock tasks that are + * blocked waiting for the bits. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @return The value of the event group at the time the call to + * xEventGroupSetBits() returns. There are two reasons why the returned value + * might have the bits specified by the uxBitsToSet parameter cleared. First, + * if setting a bit results in a task that was waiting for the bit leaving the + * blocked state then it is possible the bit will be cleared automatically + * (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any + * unblocked (or otherwise Ready state) task that has a priority above that of + * the task that called xEventGroupSetBits() will execute and may change the + * event group value before the call to xEventGroupSetBits() returns. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * void aFunction( EventGroupHandle_t xEventGroup ) + * { + * EventBits_t uxBits; + * + * // Set bit 0 and bit 4 in xEventGroup. + * uxBits = xEventGroupSetBits( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 );// The bits being set. + * + * if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) ) + * { + * // Both bit 0 and bit 4 remained set when the function returned. + * } + * else if( ( uxBits & BIT_0 ) != 0 ) + * { + * // Bit 0 remained set when the function returned, but bit 4 was + * // cleared. It might be that bit 4 was cleared automatically as a + * // task that was waiting for bit 4 was removed from the Blocked + * // state. + * } + * else if( ( uxBits & BIT_4 ) != 0 ) + * { + * // Bit 4 remained set when the function returned, but bit 0 was + * // cleared. It might be that bit 0 was cleared automatically as a + * // task that was waiting for bit 0 was removed from the Blocked + * // state. + * } + * else + * { + * // Neither bit 0 nor bit 4 remained set. It might be that a task + * // was waiting for both of the bits to be set, and the bits were + * // cleared as the task left the Blocked state. + * } + * } + * @endcode{c} + * \ingroup EventGroup + */ +EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION; + +/** + * + * A version of xEventGroupSetBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed in + * interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() + * sends a message to the timer task to have the set operation performed in the + * context of the timer task - where a scheduler lock is used in place of a + * critical section. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task is higher than the priority of the + * currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE by + * xEventGroupSetBitsFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: + * @code{c} + * #define BIT_0 ( 1 << 0 ) + * #define BIT_4 ( 1 << 4 ) + * + * // An event group which it is assumed has already been created by a call to + * // xEventGroupCreate(). + * EventGroupHandle_t xEventGroup; + * + * void anInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken, xResult; + * + * // xHigherPriorityTaskWoken must be initialised to pdFALSE. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Set bit 0 and bit 4 in xEventGroup. + * xResult = xEventGroupSetBitsFromISR( + * xEventGroup, // The event group being updated. + * BIT_0 | BIT_4 // The bits being set. + * &xHigherPriorityTaskWoken ); + * + * // Was the message posted successfully? + * if( xResult == pdPASS ) + * { + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and + * // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - + * // refer to the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * } + * @endcode + * \ingroup EventGroup + */ +#if( configUSE_TRACE_FACILITY == 1 ) + BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#else + #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ) +#endif + +/** + * + * Atomically set bits within an event group, then wait for a combination of + * bits to be set within the same event group. This functionality is typically + * used to synchronise multiple tasks, where each task has to wait for the other + * tasks to reach a synchronisation point before proceeding. + * + * This function cannot be used from an interrupt. + * + * The function will return before its block time expires if the bits specified + * by the uxBitsToWait parameter are set, or become set within that time. In + * this case all the bits specified by uxBitsToWait will be automatically + * cleared before the function returns. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToSet The bits to set in the event group before determining + * if, and possibly waiting for, all the bits specified by the uxBitsToWait + * parameter are set. + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for all of the bits specified by uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupSync() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupSync() returned because all the bits it was waiting for were + * set then the returned value is the event group value before any bits were + * automatically cleared. + * + * Example usage: + * @code{c} + * // Bits used by the three tasks. + * #define TASK_0_BIT ( 1 << 0 ) + * #define TASK_1_BIT ( 1 << 1 ) + * #define TASK_2_BIT ( 1 << 2 ) + * + * #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT ) + * + * // Use an event group to synchronise three tasks. It is assumed this event + * // group has already been created elsewhere. + * EventGroupHandle_t xEventBits; + * + * void vTask0( void *pvParameters ) + * { + * EventBits_t uxReturn; + * TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS; + * + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 0 in the event flag to note this task has reached the + * // sync point. The other two tasks will set the other two bits defined + * // by ALL_SYNC_BITS. All three tasks have reached the synchronisation + * // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms + * // for this to happen. + * uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait ); + * + * if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS ) + * { + * // All three tasks reached the synchronisation point before the call + * // to xEventGroupSync() timed out. + * } + * } + * } + * + * void vTask1( void *pvParameters ) + * { + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 1 in the event flag to note this task has reached the + * // synchronisation point. The other two tasks will set the other two + * // bits defined by ALL_SYNC_BITS. All three tasks have reached the + * // synchronisation point when all the ALL_SYNC_BITS are set. Wait + * // indefinitely for this to happen. + * xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY ); + * + * // xEventGroupSync() was called with an indefinite block time, so + * // this task will only reach here if the syncrhonisation was made by all + * // three tasks, so there is no need to test the return value. + * } + * } + * + * void vTask2( void *pvParameters ) + * { + * for( ;; ) + * { + * // Perform task functionality here. + * + * // Set bit 2 in the event flag to note this task has reached the + * // synchronisation point. The other two tasks will set the other two + * // bits defined by ALL_SYNC_BITS. All three tasks have reached the + * // synchronisation point when all the ALL_SYNC_BITS are set. Wait + * // indefinitely for this to happen. + * xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY ); + * + * // xEventGroupSync() was called with an indefinite block time, so + * // this task will only reach here if the syncrhonisation was made by all + * // three tasks, so there is no need to test the return value. + * } + * } + * + * @endcode + * \ingroup EventGroup + */ +EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + + +/** + * + * Returns the current value of the bits in an event group. This function + * cannot be used from an interrupt. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBits() was called. + * + * \ingroup EventGroup + */ +#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 ) + +/** + * + * A version of xEventGroupGetBits() that can be called from an ISR. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBitsFromISR() was called. + * + * \ingroup EventGroup + */ +EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/** + * Delete an event group that was previously created by a call to + * xEventGroupCreate(). Tasks that are blocked on the event group will be + * unblocked and obtain 0 as the event group's value. + * + * @param xEventGroup The event group being deleted. + */ +void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/** @cond */ + +/* For internal use only. */ +void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; +void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; + + +#if (configUSE_TRACE_FACILITY == 1) + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; + void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; +#endif + +/** @endcond */ + +#ifdef __cplusplus +} +#endif + +#endif /* EVENT_GROUPS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/list.h b/tools/sdk/esp32c3/include/freertos/include/freertos/list.h new file mode 100644 index 00000000..d06481e2 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/list.h @@ -0,0 +1,411 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * This is the list implementation used by the scheduler. While it is tailored + * heavily for the schedulers needs, it is also available for use by + * application code. + * + * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a + * numeric value (xItemValue). Most of the time the lists are sorted in + * descending item value order. + * + * Lists are created already containing one list item. The value of this + * item is the maximum possible that can be stored, it is therefore always at + * the end of the list and acts as a marker. The list member pxHead always + * points to this marker - even though it is at the tail of the list. This + * is because the tail contains a wrap back pointer to the true head of + * the list. + * + * In addition to it's value, each list item contains a pointer to the next + * item in the list (pxNext), a pointer to the list it is in (pxContainer) + * and a pointer to back to the object that contains it. These later two + * pointers are included for efficiency of list manipulation. There is + * effectively a two way link between the object containing the list item and + * the list item itself. + * + * + * \page ListIntroduction List Implementation + * \ingroup FreeRTOSIntro + */ + +#ifndef INC_FREERTOS_H + #error FreeRTOS.h must be included before list.h +#endif + +#ifndef LIST_H +#define LIST_H + +/* + * The list structure members are modified from within interrupts, and therefore + * by rights should be declared volatile. However, they are only modified in a + * functionally atomic way (within critical sections of with the scheduler + * suspended) and are either passed by reference into a function or indexed via + * a volatile variable. Therefore, in all use cases tested so far, the volatile + * qualifier can be omitted in order to provide a moderate performance + * improvement without adversely affecting functional behaviour. The assembly + * instructions generated by the IAR, ARM and GCC compilers when the respective + * compiler's options were set for maximum optimisation has been inspected and + * deemed to be as intended. That said, as compiler technology advances, and + * especially if aggressive cross module optimisation is used (a use case that + * has not been exercised to any great extend) then it is feasible that the + * volatile qualifier will be needed for correct optimisation. It is expected + * that a compiler removing essential code because, without the volatile + * qualifier on the list structure members and with aggressive cross module + * optimisation, the compiler deemed the code unnecessary will result in + * complete and obvious failure of the scheduler. If this is ever experienced + * then the volatile qualifier can be inserted in the relevant places within the + * list structures by simply defining configLIST_VOLATILE to volatile in + * FreeRTOSConfig.h (as per the example at the bottom of this comment block). + * If configLIST_VOLATILE is not defined then the preprocessor directives below + * will simply #define configLIST_VOLATILE away completely. + * + * To use volatile list structure members then add the following line to + * FreeRTOSConfig.h (without the quotes): + * "#define configLIST_VOLATILE volatile" + */ +#ifndef configLIST_VOLATILE + #define configLIST_VOLATILE +#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Macros that can be used to place known values within the list structures, +then check that the known values do not get corrupted during the execution of +the application. These may catch the list data structures being overwritten in +memory. They will not catch data errors caused by incorrect configuration or +use of FreeRTOS.*/ +#if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) +#else + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + + /* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + + /* Define macros that will assert if one of the structure members does not + contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) +#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ + + +/* + * Definition of the only type of object that a list can contain. + */ +struct xLIST; +struct xLIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +}; +typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ + +struct xMINI_LIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; +}; +typedef struct xMINI_LIST_ITEM MiniListItem_t; + +/* + * Definition of the type of queue used by the scheduler. + */ +typedef struct xLIST +{ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + volatile UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +} List_t; + +/* + * Access macro to set the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) + +/* + * Access macro to get the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) + +/* + * Access macro to set the value of the list item. In most cases the value is + * used to sort the list in descending order. + * + * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) + +/* + * Access macro to retrieve the value of the list item. The value can + * represent anything - for example the priority of a task, or the time at + * which a task should be unblocked. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) + +/* + * Access macro to retrieve the value of the list item at the head of a given + * list. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) + +/* + * Return the list item at the head of the list. + * + * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) + +/* + * Return the next list item. + * + * \page listGET_NEXT listGET_NEXT + * \ingroup LinkedList + */ +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) + +/* + * Return the list item that marks the end of the list + * + * \page listGET_END_MARKER listGET_END_MARKER + * \ingroup LinkedList + */ +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) + +/* + * Access macro to determine if a list contains any items. The macro will + * only have the value true if the list is empty. + * + * \page listLIST_IS_EMPTY listLIST_IS_EMPTY + * \ingroup LinkedList + */ +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) + +/* + * Access macro to return the number of items in the list. + */ +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) + +/* + * Access function to obtain the owner of the next entry in a list. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list + * and returns that entry's pxOwner parameter. Using multiple calls to this + * function it is therefore possible to move through every item contained in + * a list. + * + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxTCB pxTCB is set to the address of the owner of the next list item. + * @param pxList The list from which the next item owner is to be returned. + * + * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ +{ \ +List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ +} + + +/* + * Access function to obtain the owner of the first entry in a list. Lists + * are normally sorted in ascending item value order. + * + * This function returns the pxOwner member of the first item in the list. + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxList The list from which the owner of the head item is to be + * returned. + * + * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner ) + +/* + * Check to see if a list item is within a list. The list item maintains a + * "container" pointer that points to the list it is in. All this macro does + * is check to see if the container and the list match. + * + * @param pxList The list we want to know if the list item is within. + * @param pxListItem The list item we want to know if is in the list. + * @return pdTRUE if the list item is in the list, otherwise pdFALSE. + */ +#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) ) + +/* + * Return the list a list item is contained within (referenced from). + * + * @param pxListItem The list item being queried. + * @return A pointer to the List_t object that references the pxListItem + */ +#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer ) + +/* + * This provides a crude means of knowing if a list has been initialised, as + * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() + * function. + */ +#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) + +/* + * Must be called before a list is used! This initialises all the members + * of the list structure and inserts the xListEnd item into the list as a + * marker to the back of the list. + * + * @param pxList Pointer to the list being initialised. + * + * \page vListInitialise vListInitialise + * \ingroup LinkedList + */ +void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; + +/* + * Must be called before a list item is used. This sets the list container to + * null so the item does not think that it is already contained in a list. + * + * @param pxItem Pointer to the list item being initialised. + * + * \page vListInitialiseItem vListInitialiseItem + * \ingroup LinkedList + */ +void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted into the list in + * a position determined by its item value (descending item value order). + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The item that is to be placed in the list. + * + * \page vListInsert vListInsert + * \ingroup LinkedList + */ +void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page vListInsertEnd vListInsertEnd + * \ingroup LinkedList + */ +void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page uxListRemove uxListRemove + * \ingroup LinkedList + */ +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/message_buffer.h b/tools/sdk/esp32c3/include/freertos/include/freertos/message_buffer.h new file mode 100644 index 00000000..a49324da --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/message_buffer.h @@ -0,0 +1,702 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +/* + * Message buffers build functionality on top of FreeRTOS stream buffers. + * Whereas stream buffers are used to send a continuous stream of data from one + * task or interrupt to another, message buffers are used to send variable + * length discrete messages from one task or interrupt to another. Their + * implementation is light weight, making them particularly suited for interrupt + * to task and core to core communication scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * timeout to 0. + * + * Message buffers hold variable length messages. To enable that, when a + * message is written to the message buffer an additional sizeof( size_t ) bytes + * are also written to store the message's length (that happens internally, with + * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so writing a 10 byte message to a message buffer on a 32-bit + * architecture will actually reduce the available space in the message buffer + * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length + * of the message). + */ + +#ifndef FREERTOS_MESSAGE_BUFFER_H +#define FREERTOS_MESSAGE_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include message_buffer.h" +#endif + +/* Message buffers are built onto of stream buffers. */ +#include "stream_buffer.h" + +#if defined( __cplusplus ) +extern "C" { +#endif + +/** + * Type by which message buffers are referenced. For example, a call to + * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can + * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), + * etc. + */ +typedef void * MessageBufferHandle_t; + +/*-----------------------------------------------------------*/ + +/** + * Creates a new message buffer using dynamically allocated memory. See + * xMessageBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xMessageBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes (not messages) the message + * buffer will be able to hold at any one time. When a message is written to + * the message buffer an additional sizeof( size_t ) bytes are also written to + * store the message's length. sizeof( size_t ) is typically 4 bytes on a + * 32-bit architecture, so on most 32-bit architectures a 10 byte message will + * take up 14 bytes of message buffer space. + * + * @return If NULL is returned, then the message buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the message buffer data structures and storage area. A non-NULL value being + * returned indicates that the message buffer has been created successfully - + * the returned value should be stored as the handle to the created message + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * const size_t xMessageBufferSizeBytes = 100; + * + * // Create a message buffer that can hold 100 bytes. The memory used to hold + * // both the message buffer structure and the messages themselves is allocated + * // dynamically. Each message added to the buffer consumes an additional 4 + * // bytes which are used to hold the lengh of the message. + * xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes ); + * + * if( xMessageBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // message buffer. + * } + * else + * { + * // The message buffer was created successfully and can now be used. + * } + * + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreate( xBufferSizeBytes ) ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE ) + +/** + * Creates a new message buffer using statically allocated memory. See + * xMessageBufferCreate() for a version that uses dynamically allocated memory. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucMessageBufferStorageArea parameter. When a message is written to the + * message buffer an additional sizeof( size_t ) bytes are also written to store + * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so on most 32-bit architecture a 10 byte message will take up + * 14 bytes of message buffer space. The maximum number of bytes that can be + * stored in the message buffer is actually (xBufferSizeBytes - 1). + * + * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes + 1 big. This is the array to which messages are + * copied when they are written to the message buffer. + * + * @param pxStaticMessageBuffer Must point to a variable of type + * StaticMessageBuffer_t, which will be used to hold the message buffer's data + * structure. + * + * @return If the message buffer is created successfully then a handle to the + * created message buffer is returned. If either pucMessageBufferStorageArea or + * pxStaticmessageBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the messages. The available space + * // will actually be one less than this, so 999. + * #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the messages within the message + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the message buffer structure. + * StaticMessageBuffer_t xMessageBufferStruct; + * + * void MyFunction( void ) + * { + * MessageBufferHandle_t xMessageBuffer; + * + * xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ), + * ucBufferStorage, + * &xMessageBufferStruct ); + * + * // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer + * // parameters were NULL, xMessageBuffer will not be NULL, and can be used to + * // reference the created message buffer in other message buffer API calls. + * + * // Other code that uses the message buffer can go here. + * } + * + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer ) + +/** + * Sends a discrete message to the message buffer. The message can be any + * length that fits within the buffer's free space, and is copied into the + * buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param xTicksToWait The maximum amount of time the calling task should remain + * in the Blocked state to wait for enough space to become available in the + * message buffer, should the message buffer have insufficient space when + * xMessageBufferSend() is called. The calling task will never block if + * xTicksToWait is zero. The block time is specified in tick periods, so the + * absolute time it represents is dependent on the tick frequency. The macro + * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into + * a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause + * the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The number of bytes written to the message buffer. If the call to + * xMessageBufferSend() times out before there was enough space to write the + * message into the message buffer then zero is returned. If the call did not + * time out then xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBufferHandle_t xMessageBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the message buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the message buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xMessageBufferSend() times out before there was enough + * // space in the buffer for the data to be written. + * } + * + * // Send the string to the message buffer. Return immediately if there is + * // not enough space in the buffer. + * xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * } + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) + +/** + * Interrupt safe version of the API function that sends a discrete message to + * the message buffer. The message can be any length that fits within the + * buffer's free space, and is copied into the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for data. Calling + * xMessageBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xMessageBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the code example below for an example. + * + * @return The number of bytes actually written to the message buffer. If the + * message buffer didn't have enough free space for the message to be stored + * then 0 is returned, otherwise xDataLengthBytes is returned. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBufferHandle_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the message buffer. + * xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The string could not be added to the message buffer because there was + * // not enough free space in the buffer. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * Receives a discrete message from a message buffer. Messages can be of + * variable length and are copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for a message, should the message buffer be empty. + * xMessageBufferReceive() will return immediately if xTicksToWait is zero and + * the message buffer is empty. The block time is specified in tick periods, so + * the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. If xMessageBufferReceive() times out before a message became available + * then zero is returned. If the length of the message is greater than + * xBufferLengthBytes then the message will be left in the message buffer and + * zero is returned. + * + * Example use: + * @code{c} + * void vAFunction( MessageBuffer_t xMessageBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive the next message from the message buffer. Wait in the Blocked + * // state (so not using any CPU processing time) for a maximum of 100ms for + * // a message to become available. + * xReceivedBytes = xMessageBufferReceive( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * } + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) + + +/** + * An interrupt safe version of the API function that receives a discrete + * message from a message buffer. Messages can be of variable length and are + * copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for space to become available. Calling + * xMessageBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. + * + * Example use: + * @code{c} + * // A message buffer that has already been created. + * MessageBuffer_t xMessageBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next message from the message buffer. + * xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains a message that is xReceivedBytes long. Process + * // the message here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xMessageBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * Deletes a message buffer that was previously created using a call to + * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message + * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), + * then the allocated memory is freed. + * + * A message buffer handle must not be used after the message buffer has been + * deleted. + * + * @param xMessageBuffer The handle of the message buffer to be deleted. + * + */ +#define vMessageBufferDelete( xMessageBuffer ) vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * Tests to see if a message buffer is full. A message buffer is full if it + * cannot accept any more messages, of any size, until space is made available + * by a message being removed from the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is full then + * pdTRUE is returned. Otherwise pdFALSE is returned. + */ +#define xMessageBufferIsFull( xMessageBuffer ) xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * Tests to see if a message buffer is empty (does not contain any messages). + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is empty then + * pdTRUE is returned. Otherwise pdFALSE is returned. + * + */ +#define xMessageBufferIsEmpty( xMessageBuffer ) xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * Resets a message buffer to its initial empty state, discarding any message it + * contained. + * + * A message buffer can only be reset if there are no tasks blocked on it. + * + * @param xMessageBuffer The handle of the message buffer being reset. + * + * @return If the message buffer was reset then pdPASS is returned. If the + * message buffer could not be reset because either there was a task blocked on + * the message queue to wait for space to become available, or to wait for a + * a message to be available, then pdFAIL is returned. + * + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReset( xMessageBuffer ) xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer ) + + +/** + * Returns the number of bytes of free space in the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The number of bytes that can be written to the message buffer before + * the message buffer would be full. When a message is written to the message + * buffer an additional sizeof( size_t ) bytes are also written to store the + * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size + * of the largest message that can be written to the message buffer is 6 bytes. + * + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSpaceAvailable( xMessageBuffer ) xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) +#define xMessageBufferSpacesAvailable( xMessageBuffer ) xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) /* Corrects typo in original macro name. */ + +/** + * Returns the length (in bytes) of the next message in a message buffer. + * Useful if xMessageBufferReceive() returned 0 because the size of the buffer + * passed into xMessageBufferReceive() was too small to hold the next message. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The length (in bytes) of the next message in the message buffer, or 0 + * if the message buffer is empty. + * + * \ingroup MessageBufferManagement + */ +#define xMessageBufferNextLengthBytes( xMessageBuffer ) xStreamBufferNextMessageLengthBytes( ( StreamBufferHandle_t ) xMessageBuffer ) PRIVILEGED_FUNCTION; + +/** + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xMessageBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferSendCompletedFromISR(). If calling + * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +/** + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xMessageBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferReceiveCompletedFromISR(). If calling + * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +#if defined( __cplusplus ) +} /* extern "C" */ +#endif + +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/mpu_wrappers.h b/tools/sdk/esp32c3/include/freertos/include/freertos/mpu_wrappers.h new file mode 100644 index 00000000..7cbad5da --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/mpu_wrappers.h @@ -0,0 +1,186 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef MPU_WRAPPERS_H +#define MPU_WRAPPERS_H + +/* This file redefines API functions to be called through a wrapper macro, but +only for ports that are using the MPU. */ +#if portUSING_MPU_WRAPPERS + + /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + included from queue.c or task.c to prevent it from having an effect within + those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + + /* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ + + /* Map standard tasks.h API functions to the MPU equivalents. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define xTaskCreateRestricted MPU_xTaskCreateRestricted + #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions + #define vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define vTaskDelayUntil MPU_vTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + // #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + // #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskNotifyWait MPU_xTaskNotifyWait + #define ulTaskNotifyTake MPU_ulTaskNotifyTake + #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear + #define xTaskCatchUpTicks MPU_xTaskCatchUpTicks + + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + + /* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset + + #if( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif + + /* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand + + /* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete + + /* Map standard message/stream_buffer.h API functions to the MPU + equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + + + /* Remove the privileged function macro, but keep the PRIVILEGED_DATA + macro so applications can place data in privileged access sections + (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL + + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + + /* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) + + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + +#else /* portUSING_MPU_WRAPPERS */ + + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + #define portUSING_MPU_WRAPPERS 0 + +#endif /* portUSING_MPU_WRAPPERS */ + + +#endif /* MPU_WRAPPERS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/portable.h b/tools/sdk/esp32c3/include/freertos/include/freertos/portable.h new file mode 100644 index 00000000..0c39bb9f --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/portable.h @@ -0,0 +1,203 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/*----------------------------------------------------------- + * Portable layer API. Each function must be defined for each port. + *----------------------------------------------------------*/ + +#ifndef PORTABLE_H +#define PORTABLE_H + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a +pre-processor definition was used to ensure the pre-processor found the correct +portmacro.h file for the port being used. That scheme was deprecated in favour +of setting the compiler's include path such that it found the correct +portmacro.h file - removing the need for the constant and allowing the +portmacro.h file to be located anywhere in relation to the port being used. +Purely for reasons of backward compatibility the old method is still valid, but +to make it clear that new projects should not use it, support for the port +specific constants has been moved into the deprecated_definitions.h header +file. */ +#include "deprecated_definitions.h" + +/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h +did not result in a portmacro.h header file being included - and it should be +included here. In this case the path to the correct portmacro.h header file +must be set in the compiler's include path. */ +#ifndef portENTER_CRITICAL + #include "freertos/portmacro.h" +#endif + +#if portBYTE_ALIGNMENT == 32 + #define portBYTE_ALIGNMENT_MASK ( 0x001f ) +#endif + +#if portBYTE_ALIGNMENT == 16 + #define portBYTE_ALIGNMENT_MASK ( 0x000f ) +#endif + +#if portBYTE_ALIGNMENT == 8 + #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) +#endif + +#if portBYTE_ALIGNMENT == 4 + #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) +#endif + +#if portBYTE_ALIGNMENT == 2 + #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) +#endif + +#if portBYTE_ALIGNMENT == 1 + #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) +#endif + +#ifndef portBYTE_ALIGNMENT_MASK + #error "Invalid portBYTE_ALIGNMENT definition" +#endif + +#ifndef portNUM_CONFIGURABLE_REGIONS + #define portNUM_CONFIGURABLE_REGIONS 1 +#endif + +#ifndef portHAS_STACK_OVERFLOW_CHECKING + #define portHAS_STACK_OVERFLOW_CHECKING 0 +#endif + +#ifndef portARCH_NAME + #define portARCH_NAME NULL +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include "mpu_wrappers.h" + +/* + * Setup the stack of a new task so it is ready to be placed under the + * scheduler control. The registers have to be placed on the stack in + * the order that the port expects to find them. + * + */ +#if( portUSING_MPU_WRAPPERS == 1 ) + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif +#else + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #endif +#endif + +#ifdef configUSE_FREERTOS_PROVIDED_HEAP + +/* Used by heap_5.c to define the start address and size of each memory region +that together comprise the total FreeRTOS heap space. */ +typedef struct HeapRegion +{ + uint8_t *pucStartAddress; + size_t xSizeInBytes; +} HeapRegion_t; + +/* Used to pass information about the heap out of vPortGetHeapStats(). */ +typedef struct xHeapStats +{ + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +} HeapStats_t; + +/* + * Used to define multiple heap regions for use by heap_5.c. This function + * must be called before any calls to pvPortMalloc() - not creating a task, + * queue, semaphore, mutex, software timer, event group, etc. will result in + * pvPortMalloc being called. + * + * pxHeapRegions passes in an array of HeapRegion_t structures - each of which + * defines a region of memory that can be used as the heap. The array is + * terminated by a HeapRegions_t structure that has a size of 0. The region + * with the lowest start address must appear first in the array. + */ +void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; + +/* + * Returns a HeapStats_t structure filled with information about the current + * heap state. + */ +void vPortGetHeapStats( HeapStats_t *pxHeapStats ); +/* + * Map to the memory management routines required for the port. + */ +void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; +void vPortFree( void *pv ) PRIVILEGED_FUNCTION; +void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; +size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; +size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; + +#else // configUSE_FREERTOS_PROVIDED_HEAP + +/* + * Map to the memory management routines required for the port. + * + * Note that libc standard malloc/free are also available for + * non-FreeRTOS-specific code, and behave the same as + * pvPortMalloc()/vPortFree(). + */ +#define pvPortMalloc malloc +#define vPortFree free +#define xPortGetFreeHeapSize esp_get_free_heap_size +#define xPortGetMinimumEverFreeHeapSize esp_get_minimum_free_heap_size + +#endif + +/* + * Setup the hardware ready for the scheduler to take control. This generally + * sets up a tick interrupt and sets timers for the correct tick frequency. + */ +BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so + * the hardware is left in its original condition after the scheduler stops + * executing. + */ +void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; + +#ifdef __cplusplus +} +#endif + +#endif /* PORTABLE_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/projdefs.h b/tools/sdk/esp32c3/include/freertos/include/freertos/projdefs.h new file mode 100644 index 00000000..ce647fb6 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/projdefs.h @@ -0,0 +1,126 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef PROJDEFS_H +#define PROJDEFS_H + +/* + * Defines the prototype to which task functions must conform. Defined in this + * file to ensure the type is known before portable.h is included. + */ +typedef void (*TaskFunction_t)( void * ); + +/* Converts a time in milliseconds to a time in ticks. This macro can be +overridden by a macro of the same name defined in FreeRTOSConfig.h in case the +definition here is not suitable for your application. */ +#ifndef pdMS_TO_TICKS + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) +#endif + +#ifndef pdTICKS_TO_MS + #define pdTICKS_TO_MS( xTicks ) ( ( uint32_t ) ( xTicks ) * 1000 / configTICK_RATE_HZ ) +#endif + + +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) + +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) + +/* FreeRTOS error definitions. */ +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) + +/* Macros used for basic data corruption checks. */ +#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 +#endif + +#if( configUSE_16_BIT_TICKS == 1 ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a +#else + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL +#endif + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS +itself. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ + +/* The following endian values are used by FreeRTOS+ components, not FreeRTOS +itself. */ +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 + +/* Re-defining endian values for generic naming. */ +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN + + +#endif /* PROJDEFS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/queue.h b/tools/sdk/esp32c3/include/freertos/include/freertos/queue.h new file mode 100644 index 00000000..8c354653 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/queue.h @@ -0,0 +1,1480 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef QUEUE_H +#define QUEUE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include queue.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include "task.h" + +/** + * Type by which queues are referenced. For example, a call to xQueueCreate() + * returns an QueueHandle_t variable that can then be used as a parameter to + * xQueueSend(), xQueueReceive(), etc. + */ +struct QueueDefinition; /* Using old naming convention so as not to break kernel aware debuggers. */ +typedef struct QueueDefinition * QueueHandle_t; + +/** + * Type by which queue sets are referenced. For example, a call to + * xQueueCreateSet() returns an xQueueSet variable that can then be used as a + * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. + */ +typedef struct QueueDefinition * QueueSetHandle_t; + +/** + * Queue sets can contain both queues and semaphores, so the + * QueueSetMemberHandle_t is defined as a type to be used where a parameter or + * return value can be either an QueueHandle_t or an SemaphoreHandle_t. + */ +typedef struct QueueDefinition * QueueSetMemberHandle_t; + +/** @cond */ + +/* For internal use only. */ +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) + +/* For internal use only. These definitions *must* match those in queue.c. */ +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) + +/** @endcond */ + +/** + * Creates a new queue instance. This allocates the storage required by the + * new queue and returns a handle for the queue. + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @return If the queue is successfully create then a handle to the newly + * created queue is returned. If the queue cannot be created then 0 is + * returned. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * }; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * if( xQueue1 == 0 ) + * { + * // Queue was not created and must not be used. + * } + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue2 == 0 ) + * { + * // Queue was not created and must not be used. + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) +#endif + +/** + * Creates a new queue instance, and returns a handle by which the new queue + * can be referenced. + * + * Internally, within the FreeRTOS implementation, queues use two blocks of + * memory. The first block is used to hold the queue's data structures. The + * second block is used to hold items placed into the queue. If a queue is + * created using xQueueCreate() then both blocks of memory are automatically + * dynamically allocated inside the xQueueCreate() function. (see + * http://www.freertos.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @param pucQueueStorage If uxItemSize is not zero then + * pucQueueStorageBuffer must point to a uint8_t array that is at least large + * enough to hold the maximum number of items that can be in the queue at any + * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is + * zero then pucQueueStorageBuffer can be NULL. + * + * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which + * will be used to hold the queue's data structure. + * + * @return If the queue is created then a handle to the created queue is + * returned. If pxQueueBuffer is NULL then NULL is returned. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * }; + * + * #define QUEUE_LENGTH 10 + * #define ITEM_SIZE sizeof( uint32_t ) + * + * // xQueueBuffer will hold the queue structure. + * StaticQueue_t xQueueBuffer; + * + * // ucQueueStorage will hold the items posted to the queue. Must be at least + * // [(queue length) * ( queue item size)] bytes long. + * uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ]; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold. + * ITEM_SIZE // The size of each item in the queue + * &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue. + * &xQueueBuffer ); // The buffer that will hold the queue structure. + * + * // The queue is guaranteed to be created successfully as no dynamic memory + * // allocation is used. Therefore xQueue1 is now a handle to a valid queue. + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * Post an item to the front of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT ) + +/** + * This is a macro that calls xQueueGenericSend(). + * + * Post an item to the back of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the queue + * is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * This is a macro that calls xQueueGenericSend(). It is included for + * backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToFront() and xQueueSendToBack() macros. It is + * equivalent to xQueueSendToBack(). + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * Only for use with queues that have a length of one - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * This function must not be called from an interrupt service routine. + * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle of the queue to which the data is being sent. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and + * therefore has the same return values as xQueueSendToFront(). However, pdPASS + * is the only value that can be returned because xQueueOverwrite() will write + * to the queue even when the queue is already full. + * + * Example usage: + * @code{c} + * + * void vFunction( void *pvParameters ) + * { + * QueueHandle_t xQueue; + * uint32_t ulVarToSend, ulValReceived; + * + * // Create a queue to hold one uint32_t value. It is strongly + * // recommended *not* to use xQueueOverwrite() on queues that can + * // contain more than one value, and doing so will trigger an assertion + * // if configASSERT() is defined. + * xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + * + * // Write the value 10 to the queue using xQueueOverwrite(). + * ulVarToSend = 10; + * xQueueOverwrite( xQueue, &ulVarToSend ); + * + * // Peeking the queue should now return 10, but leave the value 10 in + * // the queue. A block time of zero is used as it is known that the + * // queue holds a value. + * ulValReceived = 0; + * xQueuePeek( xQueue, &ulValReceived, 0 ); + * + * if( ulValReceived != 10 ) + * { + * // Error unless the item was removed by a different task. + * } + * + * // The queue is still full. Use xQueueOverwrite() to overwrite the + * // value held in the queue with 100. + * ulVarToSend = 100; + * xQueueOverwrite( xQueue, &ulVarToSend ); + * + * // This time read from the queue, leaving the queue empty once more. + * // A block time of 0 is used again. + * xQueueReceive( xQueue, &ulValReceived, 0 ); + * + * // The value read should be the last value written, even though the + * // queue was already full when the value was written. + * if( ulValReceived != 100 ) + * { + * // Error! + * } + * + * // ... + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE ) + + +/** + * It is preferred that the macros xQueueSend(), xQueueSendToFront() and + * xQueueSendToBack() are used in place of calling this function directly. + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * uint32_t ulVar = 10UL; + * + * void vATask( void *pvParameters ) + * { + * QueueHandle_t xQueue1, xQueue2; + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 uint32_t values. + * xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * + * // ... + * + * if( xQueue1 != 0 ) + * { + * // Send an uint32_t. Wait for 10 ticks for space to become + * // available if necessary. + * if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) + * { + * // Failed to post the message, even after 10 ticks. + * } + * } + * + * if( xQueue2 != 0 ) + * { + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; + +/** + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * This macro must not be used in an interrupt service routine. See + * xQueuePeekFromISR() for an alternative that can be called from an interrupt + * service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue + * is empty. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * QueueHandle_t xQueue; + * + * // Task to create a queue and post a value. + * void vATask( void *pvParameters ) + * { + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * + * // ... Rest of task code. + * } + * + * // Task to peek the data from the queue. + * void vADifferentTask( void *pvParameters ) + * { + * struct AMessage *pxRxedMessage; + * + * if( xQueue != 0 ) + * { + * // Peek a message on the created queue. Block for 10 ticks if a + * // message is not immediately available. + * if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + * { + * // pcRxedMessage now points to the struct AMessage variable posted + * // by vATask, but the item still remains on the queue. + * } + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * A version of xQueuePeek() that can be called from an interrupt service + * routine (ISR). + * + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * \ingroup QueueManagement + */ +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; + +/** + * Receive an item from a queue. The item is received by copy so a buffer of + * adequate size must be provided. The number of bytes copied into the buffer + * was defined when the queue was created. + * + * Successfully received items are removed from the queue. + * + * This function must not be used in an interrupt service routine. See + * xQueueReceiveFromISR for an alternative that can. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. xQueueReceive() will return immediately if xTicksToWait + * is zero and the queue is empty. The time is defined in tick periods so the + * constant portTICK_PERIOD_MS should be used to convert to real time if this is + * required. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * struct AMessage + * { + * char ucMessageID; + * char ucData[ 20 ]; + * } xMessage; + * + * QueueHandle_t xQueue; + * + * // Task to create a queue and post a value. + * void vATask( void *pvParameters ) + * { + * struct AMessage *pxMessage; + * + * // Create a queue capable of containing 10 pointers to AMessage structures. + * // These should be passed by pointer as they contain a lot of data. + * xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Send a pointer to a struct AMessage object. Don't block if the + * // queue is already full. + * pxMessage = & xMessage; + * xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + * + * // ... Rest of task code. + * } + * + * // Task to receive from the queue. + * void vADifferentTask( void *pvParameters ) + * { + * struct AMessage *pxRxedMessage; + * + * if( xQueue != 0 ) + * { + * // Receive a message on the created queue. Block for 10 ticks if a + * // message is not immediately available. + * if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + * { + * // pcRxedMessage now points to the struct AMessage variable posted + * // by vATask. + * } + * } + * + * // ... Rest of task code. + * } + * @endcode + * \ingroup QueueManagement + */ +BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * Return the number of messages stored in a queue. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of messages available in the queue. + * + * \ingroup QueueManagement + */ +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * Return the number of free spaces available in a queue. This is equal to the + * number of items that can be sent to the queue before the queue becomes full + * if no items are removed. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of spaces available in the queue. + * + * \ingroup QueueManagement + */ +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * Delete a queue - freeing all the memory allocated for storing of items + * placed on the queue. + * + * @param xQueue A handle to the queue to be deleted. + * + * \ingroup QueueManagement + */ +void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the front of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param[out] pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPrioritTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * portYIELD_FROM_ISR (); + * } + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT ) + + +/** + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the back of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param[out] pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * portYIELD_FROM_ISR (); + * } + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/** + * A version of xQueueOverwrite() that can be used in an interrupt service + * routine (ISR). + * + * Only for use with queues that can hold a single item - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param[out] pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return xQueueOverwriteFromISR() is a macro that calls + * xQueueGenericSendFromISR(), and therefore has the same return values as + * xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be + * returned because xQueueOverwriteFromISR() will write to the queue even when + * the queue is already full. + * + * Example usage: + * @code{c} + * QueueHandle_t xQueue; + * + * void vFunction( void *pvParameters ) + * { + * // Create a queue to hold one uint32_t value. It is strongly + * // recommended *not* to use xQueueOverwriteFromISR() on queues that can + * // contain more than one value, and doing so will trigger an assertion + * // if configASSERT() is defined. + * xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + * } + * + * void vAnInterruptHandler( void ) + * { + * // xHigherPriorityTaskWoken must be set to pdFALSE before it is used. + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * uint32_t ulVarToSend, ulValReceived; + * + * // Write the value 10 to the queue using xQueueOverwriteFromISR(). + * ulVarToSend = 10; + * xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + * + * // The queue is full, but calling xQueueOverwriteFromISR() again will still + * // pass because the value held in the queue will be overwritten with the + * // new value. + * ulVarToSend = 100; + * xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + * + * // Reading from the queue will now return 100. + * + * // ... + * + * if( xHigherPrioritytaskWoken == pdTRUE ) + * { + * // Writing to the queue caused a task to unblock and the unblocked task + * // has a priority higher than or equal to the priority of the currently + * // executing task (the task this interrupt interrupted). Perform a context + * // switch so this interrupt returns directly to the unblocked task. + * portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. + * } + * } + * @endcode + * \ingroup QueueManagement + */ +#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE ) + +/** + * This is a macro that calls xQueueGenericSendFromISR(). It is included + * for backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() + * macros. + * + * Post an item to the back of a queue. It is safe to use this function from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param[out] pxHigherPriorityTaskWoken xQueueSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWoken; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWoken = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post the byte. + * xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. + * if( xHigherPriorityTaskWoken ) + * { + * // Actual macro used here is port specific. + * portYIELD_FROM_ISR (); + * } + * } + * @endcode + * + * \ingroup QueueManagement + */ +#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/**@{*/ +/** + * It is preferred that the macros xQueueSendFromISR(), + * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place + * of calling this function directly. xQueueGiveFromISR() is an + * equivalent for use by semaphores that don't actually copy any data. + * + * Post an item on a queue. It is safe to use this function from within an + * interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param[out] pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): + * @code{c} + * void vBufferISR( void ) + * { + * char cIn; + * BaseType_t xHigherPriorityTaskWokenByPost; + * + * // We have not woken a task at the start of the ISR. + * xHigherPriorityTaskWokenByPost = pdFALSE; + * + * // Loop until the buffer is empty. + * do + * { + * // Obtain a byte from the buffer. + * cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + * + * // Post each byte. + * xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); + * + * } while( portINPUT_BYTE( BUFFER_COUNT ) ); + * + * // Now the buffer is empty we can switch context if necessary. Note that the + * // name of the yield function required is port specific. + * if( xHigherPriorityTaskWokenByPost ) + * { + * taskYIELD_YIELD_FROM_ISR(); + * } + * } + * @endcode + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +/**@}*/ + +/** + * Receive an item from a queue. It is safe to use this function from within an + * interrupt service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param[out] pxHigherPriorityTaskWoken A task may be blocked waiting for space to become + * available on the queue. If xQueueReceiveFromISR causes such a task to + * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will + * remain unchanged. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: + * @code{c} + * QueueHandle_t xQueue; + * + * // Function to create a queue and post some values. + * void vAFunction( void *pvParameters ) + * { + * char cValueToPost; + * const TickType_t xTicksToWait = ( TickType_t )0xff; + * + * // Create a queue capable of containing 10 characters. + * xQueue = xQueueCreate( 10, sizeof( char ) ); + * if( xQueue == 0 ) + * { + * // Failed to create the queue. + * } + * + * // ... + * + * // Post some characters that will be used within an ISR. If the queue + * // is full then this task will block for xTicksToWait ticks. + * cValueToPost = 'a'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * cValueToPost = 'b'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * + * // ... keep posting characters ... this task may block when the queue + * // becomes full. + * + * cValueToPost = 'c'; + * xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + * } + * + * // ISR that outputs all the characters received on the queue. + * void vISR_Routine( void ) + * { + * BaseType_t xTaskWokenByReceive = pdFALSE; + * char cRxedChar; + * + * while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) + * { + * // A character was received. Output the character now. + * vOutputCharacter( cRxedChar ); + * + * // If removing the character from the queue woke the task that was + * // posting onto the queue cTaskWokenByReceive will have been set to + * // pdTRUE. No matter how many times this loop iterates only one + * // task will be woken. + * } + * + * if( cTaskWokenByPost != ( char ) pdFALSE; + * { + * taskYIELD (); + * } + * } + * @endcode + * \ingroup QueueManagement + */ +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* + * Utilities to query queues that are safe to use from an ISR. These utilities + * should be used only from witin an ISR, or within a critical section. + */ +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** @cond */ +/** + * The functions defined above are for passing data to and from tasks. The + * functions below are the equivalents for passing data to and from + * co-routines. + * + * These functions are called from the co-routine macro implementation and + * should not be called directly from application code. Instead use the macro + * wrappers defined within croutine.h. + */ +BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ); +BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxTaskWoken ); +BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ); +BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ); + +/** + * For internal use only. Use xSemaphoreCreateMutex(), + * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling + * these functions directly. + */ +QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; + +/** + * For internal use only. Use xSemaphoreTakeMutexRecursive() or + * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. + */ +BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; + +/** @endcond */ + +/** + * Reset a queue back to its original empty state. The return value is now + * obsolete and is always set to pdPASS. + */ +#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE ) + +/** + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger. If you are not using a kernel + * aware debugger then this function can be ignored. + * + * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the + * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 + * within FreeRTOSConfig.h for the registry to be available. Its value + * does not effect the number of queues, semaphores and mutexes that can be + * created - just the number that the registry can hold. + * + * @param xQueue The handle of the queue being added to the registry. This + * is the handle returned by a call to xQueueCreate(). Semaphore and mutex + * handles can also be passed in here. + * + * @param pcQueueName The name to be associated with the handle. This is the + * name that the kernel aware debugger will display. The queue registry only + * stores a pointer to the string - so the string must be persistent (global or + * preferably in ROM/Flash), not on the stack. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /**lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/** + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to + * remove the queue, semaphore or mutex from the register. If you are not using + * a kernel aware debugger then this function can be ignored. + * + * @param xQueue The handle of the queue being removed from the registry. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#endif + +/** + * The queue registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call pcQueueGetName() to look + * up and return the name of a queue in the queue registry from the queue's + * handle. + * + * @param xQueue The handle of the queue the name of which will be returned. + * @return If the queue is in the registry then a pointer to the name of the + * queue is returned. If the queue is not in the registry then NULL is + * returned. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /**lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/** + * Generic version of the function used to creaet a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/** + * Generic version of the function used to creaet a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/** + * Queue sets provide a mechanism to allow a task to block (pend) on a read + * operation from multiple queues or semaphores simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * A queue set must be explicitly created using a call to xQueueCreateSet() + * before it can be used. Once created, standard FreeRTOS queues and semaphores + * can be added to the set using calls to xQueueAddToSet(). + * xQueueSelectFromSet() is then used to determine which, if any, of the queues + * or semaphores contained in the set is in a state where a queue read or + * semaphore take operation would be successful. + * + * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: An additional 4 bytes of RAM is required for each space in a every + * queue added to a queue set. Therefore counting semaphores that have a high + * maximum count value should not be added to a queue set. + * + * Note 4: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param uxEventQueueLength Queue sets store events that occur on + * the queues and semaphores contained in the set. uxEventQueueLength specifies + * the maximum number of events that can be queued at once. To be absolutely + * certain that events are not lost uxEventQueueLength should be set to the + * total sum of the length of the queues added to the set, where binary + * semaphores and mutexes have a length of 1, and counting semaphores have a + * length set by their maximum count value. Examples: + * + If a queue set is to hold a queue of length 5, another queue of length 12, + * and a binary semaphore, then uxEventQueueLength should be set to + * (5 + 12 + 1), or 18. + * + If a queue set is to hold three binary semaphores then uxEventQueueLength + * should be set to (1 + 1 + 1 ), or 3. + * + If a queue set is to hold a counting semaphore that has a maximum count of + * 5, and a counting semaphore that has a maximum count of 3, then + * uxEventQueueLength should be set to (5 + 3), or 8. + * + * @return If the queue set is created successfully then a handle to the created + * queue set is returned. Otherwise NULL is returned. + */ +QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; + +/** + * Adds a queue or semaphore to a queue set that was previously created by a + * call to xQueueCreateSet(). + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being added to + * the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set to which the queue or semaphore + * is being added. + * + * @return If the queue or semaphore was successfully added to the queue set + * then pdPASS is returned. If the queue could not be successfully added to the + * queue set because it is already a member of a different queue set then pdFAIL + * is returned. + */ +BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/** + * Removes a queue or semaphore from a queue set. A queue or semaphore can only + * be removed from a set if the queue or semaphore is empty. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being removed + * from the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set in which the queue or semaphore + * is included. + * + * @return If the queue or semaphore was successfully removed from the queue set + * then pdPASS is returned. If the queue was not in the queue set, or the + * queue (or semaphore) was not empty, then pdFAIL is returned. + */ +BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/** + * xQueueSelectFromSet() selects from the members of a queue set a queue or + * semaphore that either contains data (in the case of a queue) or is available + * to take (in the case of a semaphore). xQueueSelectFromSet() effectively + * allows a task to block (pend) on a read operation on all the queues and + * semaphores in a queue set simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueSet The queue set on which the task will (potentially) block. + * + * @param xTicksToWait The maximum time, in ticks, that the calling task will + * remain in the Blocked state (with other tasks executing) to wait for a member + * of the queue set to be ready for a successful queue read or semaphore take + * operation. + * + * @return xQueueSelectFromSet() will return the handle of a queue (cast to + * a QueueSetMemberHandle_t type) contained in the queue set that contains data, + * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained + * in the queue set that is available, or NULL if no such queue or semaphore + * exists before before the specified block time expires. + */ +QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * A version of xQueueSelectFromSet() that can be used from an ISR. + */ +QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/** @cond */ + +/* Not public API functions. */ +void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; +void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** @endcond */ + +#ifdef __cplusplus +} +#endif + +#endif /* QUEUE_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/semphr.h b/tools/sdk/esp32c3/include/freertos/include/freertos/semphr.h new file mode 100644 index 00000000..971d74d4 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/semphr.h @@ -0,0 +1,1093 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef SEMAPHORE_H +#define SEMAPHORE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" +#endif + +#include "queue.h" + +typedef QueueHandle_t SemaphoreHandle_t; + +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + +/** @cond */ +/** + * semphr. h + *
vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore )
+ * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * Macro that implements a semaphore by using the existing queue mechanism. + * The queue length is 1 as this is a binary semaphore. The data size is 0 + * as we don't want to actually store any data - we just want to know if the + * queue is empty or full. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). + * // This is a macro so pass the variable in directly. + * vSemaphoreCreateBinary( xSemaphore ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define vSemaphoreCreateBinary( xSemaphore ) \ + { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } +#endif +/** @endcond */ + +/** + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see http://www.freertos.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @return Handle to the created semaphore, or NULL if the memory required to + * hold the semaphore's data structures could not be allocated. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateBinary(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif + +/** + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * NOTE: In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see http://www.freertos.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param pxStaticSemaphore Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the semaphore is created then a handle to the created semaphore is + * returned. If pxSemaphoreBuffer is NULL then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateBinary() or + * // xSemaphoreCreateBinaryStatic(). + * // The semaphore's data structures will be placed in the xSemaphoreBuffer + * // variable, the address of which is passed into the function. The + * // function's parameter is not NULL, so the function will not attempt any + * // dynamic memory allocation, and therefore the function will not return + * // return NULL. + * xSemaphore = xSemaphoreCreateBinaryStatic( &xSemaphoreBuffer ); + * + * // Rest of task code goes here. + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * Macro to obtain a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). + * + * @param xSemaphore A handle to the semaphore being taken - obtained when + * the semaphore was created. + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. A block + * time of portMAX_DELAY can be used to block indefinitely (provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). + * + * @return pdTRUE if the semaphore was obtained. pdFALSE + * if xBlockTime expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * // A task that creates a semaphore. + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * vSemaphoreCreateBinary( xSemaphore ); + * } + * + * // A task that uses the semaphore. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xSemaphore != NULL ) + * { + * // See if we can obtain the semaphore. If the semaphore is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the semaphore and can now access the + * // shared resource. + * + * // ... + * + * // We have finished accessing the shared resource. Release the + * // semaphore. + * xSemaphoreGive( xSemaphore ); + * } + * else + * { + * // We could not obtain the semaphore and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \ingroup Semaphores + */ +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) + +/** + * Macro to recursively obtain, or 'take', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being obtained. This is the + * handle returned by xSemaphoreCreateRecursiveMutex(); + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. If + * the task already owns the semaphore then xSemaphoreTakeRecursive() will + * return immediately no matter what the value of xBlockTime. + * + * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime + * expired without the semaphore becoming available. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, but instead buried in a more complex + * // call structure. This is just for illustrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \ingroup Semaphores + */ +#define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) + +/** @cond */ +/* + * xSemaphoreAltTake() is an alternative version of xSemaphoreTake(). + * + * The source code that implements the alternative (Alt) API is much + * simpler because it executes everything from within a critical section. + * This is the approach taken by many other RTOSes, but FreeRTOS.org has the + * preferred fully featured API too. The fully featured API has more + * complex code that takes longer to execute, but makes much less use of + * critical sections. Therefore the alternative API sacrifices interrupt + * responsiveness to gain execution speed, whereas the fully featured API + * sacrifices execution speed to ensure better interrupt responsiveness. + */ +#define xSemaphoreAltTake( xSemaphore, xBlockTime ) xQueueAltGenericReceive( ( QueueHandle_t ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE ) +/** @endcond */ + +/** + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). + * + * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for + * an alternative which can be used from an ISR. + * + * This macro must also not be used on semaphores created using + * xSemaphoreCreateRecursiveMutex(). + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. + * Semaphores are implemented using queues. An error can occur if there is + * no space on the queue to post a message - indicating that the + * semaphore was not first obtained correctly. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore = NULL; + * + * void vATask( void * pvParameters ) + * { + * // Create the semaphore to guard a shared resource. + * vSemaphoreCreateBinary( xSemaphore ); + * + * if( xSemaphore != NULL ) + * { + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would expect this call to fail because we cannot give + * // a semaphore without first "taking" it! + * } + * + * // Obtain the semaphore - don't block if the semaphore is not + * // immediately available. + * if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) + * { + * // We now have the semaphore and can access the shared resource. + * + * // ... + * + * // We have finished accessing the shared resource so can free the + * // semaphore. + * if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + * { + * // We would not expect this call to fail because we must have + * // obtained the semaphore to get here. + * } + * } + * } + * } + * @endcode + * \ingroup Semaphores + */ +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) + +/** + * semphr. h + *
xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex )
+ * + * Macro to recursively release, or 'give', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being released, or 'given'. This is the + * handle returned by xSemaphoreCreateMutex(); + * + * @return pdTRUE if the semaphore was given. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xMutex = NULL; + * + * // A task that creates a mutex. + * void vATask( void * pvParameters ) + * { + * // Create the mutex to guard a shared resource. + * xMutex = xSemaphoreCreateRecursiveMutex(); + * } + * + * // A task that uses the mutex. + * void vAnotherTask( void * pvParameters ) + * { + * // ... Do other things. + * + * if( xMutex != NULL ) + * { + * // See if we can obtain the mutex. If the mutex is not available + * // wait 10 ticks to see if it becomes free. + * if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) + * { + * // We were able to obtain the mutex and can now access the + * // shared resource. + * + * // ... + * // For some reason due to the nature of the code further calls to + * // xSemaphoreTakeRecursive() are made on the same mutex. In real + * // code these would not be just sequential calls as this would make + * // no sense. Instead the calls are likely to be buried inside + * // a more complex call structure. + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + * + * // The mutex has now been 'taken' three times, so will not be + * // available to another task until it has also been given back + * // three times. Again it is unlikely that real code would have + * // these calls sequentially, it would be more likely that the calls + * // to xSemaphoreGiveRecursive() would be called as a call stack + * // unwound. This is just for demonstrative purposes. + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * xSemaphoreGiveRecursive( xMutex ); + * + * // Now the mutex can be taken by other tasks. + * } + * else + * { + * // We could not obtain the mutex and can therefore not access + * // the shared resource safely. + * } + * } + * } + * @endcode + * \ingroup Semaphores + */ +#define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) + +/** @cond */ +/* + * xSemaphoreAltGive() is an alternative version of xSemaphoreGive(). + * + * The source code that implements the alternative (Alt) API is much + * simpler because it executes everything from within a critical section. + * This is the approach taken by many other RTOSes, but FreeRTOS.org has the + * preferred fully featured API too. The fully featured API has more + * complex code that takes longer to execute, but makes much less use of + * critical sections. Therefore the alternative API sacrifices interrupt + * responsiveness to gain execution speed, whereas the fully featured API + * sacrifices execution speed to ensure better interrupt responsiveness. + */ +#define xSemaphoreAltGive( xSemaphore ) xQueueAltGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) + +/** @endcond */ + +/** + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR. + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. + * + * Example usage: + * @code{c} + * \#define LONG_TIME 0xffff + * \#define TICKS_TO_WAIT 10 + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Repetitive task. + * void vATask( void * pvParameters ) + * { + * for( ;; ) + * { + * // We want this task to run every 10 ticks of a timer. The semaphore + * // was created before this task was started. + * + * // Block waiting for the semaphore to become available. + * if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) + * { + * // It is time to execute. + * + * // ... + * + * // We have finished our task. Return to the top of the loop where + * // we will block on the semaphore until it is time to execute + * // again. Note when using the semaphore for synchronisation with an + * // ISR in this manner there is no need to 'give' the semaphore back. + * } + * } + * } + * + * // Timer ISR + * void vTimerISR( void * pvParameters ) + * { + * static uint8_t ucLocalTickCount = 0; + * static BaseType_t xHigherPriorityTaskWoken; + * + * // A timer tick has occurred. + * + * // ... Do other time functions. + * + * // Is it time for vATask () to run? + * xHigherPriorityTaskWoken = pdFALSE; + * ucLocalTickCount++; + * if( ucLocalTickCount >= TICKS_TO_WAIT ) + * { + * // Unblock the task by releasing the semaphore. + * xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); + * + * // Reset the count so we release the semaphore again in 10 ticks time. + * ucLocalTickCount = 0; + * } + * + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // We can force a context switch here. Context switching from an + * // ISR uses port specific syntax. Check the demo task for your port + * // to find the syntax required. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) + +/** + * Macro to take a semaphore from an ISR. The semaphore must have + * previously been created with a call to xSemaphoreCreateBinary() or + * xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR, however taking a semaphore from an ISR + * is not a common operation. It is likely to only be useful when taking a + * counting semaphore when an interrupt is obtaining an object from a resource + * pool (when the semaphore count indicates the number of resources available). + * + * @param xSemaphore A handle to the semaphore being taken. This is the + * handle returned when the semaphore was created. + * + * @param[out] pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully taken, otherwise + * pdFALSE + */ +#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * Macro that implements a mutex semaphore by using the existing queue + * mechanism. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * http://www.freertos.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return If the mutex was successfully created then a handle to the created + * semaphore is returned. If there was not enough heap to allocate the mutex + * data structures then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) +#endif + +/** + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * http://www.freertos.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will be used to hold the mutex's data structure, removing the need for + * the memory to be allocated dynamically. + * + * @return If the mutex was successfully created then a handle to the created + * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. + * + * Example usage: + * @code + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A mutex cannot be used before it has been created. xMutexBuffer is + * // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is + * // attempted. + * xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \ingroup Semaphores + */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + + +/** + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * http://www.freertos.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See vSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return xSemaphore Handle to the created mutex semaphore. Should be of type + * SemaphoreHandle_t. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + * // This is a macro so pass the variable in directly. + * xSemaphore = xSemaphoreCreateRecursiveMutex(); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) +#endif + +/** + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * http://www.freertos.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxStaticSemaphore Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the recursive mutex's data structure, + * removing the need for the memory to be allocated dynamically. + * + * @return If the recursive mutex was successfully created then a handle to the + * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is + * returned. + * + * Example usage: + * @code + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xMutexBuffer; + * + * void vATask( void * pvParameters ) + * { + * // A recursive semaphore cannot be used before it is created. Here a + * // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). + * // The address of xMutexBuffer is passed into the function, and will hold + * // the mutexes data structures - so no dynamic memory allocation will be + * // attempted. + * xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); + * + * // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + * // so there is no need to check it. + * } + * @endcode + * \ingroup Semaphores + */ +#if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * http://www.freertos.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer can + * instead optionally provide the memory that will get used by the counting + * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting + * semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @return Handle to the created semaphore. Null if the semaphore could not be + * created. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). + * // The max value to which the semaphore can count should be 10, and the + * // initial value assigned to the count should be 0. + * xSemaphore = xSemaphoreCreateCounting( 10, 0 ); + * + * if( xSemaphore != NULL ) + * { + * // The semaphore was created successfully. + * // The semaphore can now be used. + * } + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) +#endif + +/** + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * http://www.freertos.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer must + * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a + * counting semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the counting semaphore was successfully created then a handle to + * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL + * then NULL is returned. + * + * Example usage: + * @code{c} + * SemaphoreHandle_t xSemaphore; + * StaticSemaphore_t xSemaphoreBuffer; + * + * void vATask( void * pvParameters ) + * { + * SemaphoreHandle_t xSemaphore = NULL; + * + * // Counting semaphore cannot be used before they have been created. Create + * // a counting semaphore using xSemaphoreCreateCountingStatic(). The max + * // value to which the semaphore can count is 10, and the initial value + * // assigned to the count will be 0. The address of xSemaphoreBuffer is + * // passed in and will be used to hold the semaphore structure, so no dynamic + * // memory allocation will be used. + * xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); + * + * // No memory allocation was attempted so xSemaphore cannot be NULL, so there + * // is no need to check its value. + * } + * @endcode + * \ingroup Semaphores + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * Delete a semaphore. This function must be used with care. For example, + * do not delete a mutex type semaphore if the mutex is held by a task. + * + * @param xSemaphore A handle to the semaphore to be deleted. + * + * \ingroup Semaphores + */ +#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + * Note: This is a good way of determining if the calling task is the mutex + * holder, but not a good way of determining the identity of the mutex holder as + * the holder may change between the function exiting and the returned value + * being tested. + */ +#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) + +/** + * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + */ +#define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) + +/** + * semphr.h + *
UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore );
+ * + * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) + +#endif /* SEMAPHORE_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/stack_macros.h b/tools/sdk/esp32c3/include/freertos/include/freertos/stack_macros.h new file mode 100644 index 00000000..b8eca424 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/stack_macros.h @@ -0,0 +1,140 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef STACK_MACROS_H +#define STACK_MACROS_H + +/* + * Call the stack overflow hook function if the stack of the task being swapped + * out is currently overflowed, or looks like it might have overflowed in the + * past. + * + * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check + * the current stack state only - comparing the current top of stack value to + * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 + * will also cause the last few stack bytes to be checked to ensure the value + * to which the bytes were set when the task was created have not been + * overwritten. Note this second test does not guarantee that an overflowed + * stack will always be recognised. + */ + +/*-----------------------------------------------------------*/ + +#if( configCHECK_FOR_STACK_OVERFLOW == 0 ) + + /* FreeRTOSConfig.h is not set to check for stack overflows. */ + #define taskFIRST_CHECK_FOR_STACK_OVERFLOW() + #define taskSECOND_CHECK_FOR_STACK_OVERFLOW() + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 0 */ +/*-----------------------------------------------------------*/ + +#if( configCHECK_FOR_STACK_OVERFLOW == 1 ) + + /* FreeRTOSConfig.h is only set to use the first method of + overflow checking. */ + #define taskSECOND_CHECK_FOR_STACK_OVERFLOW() + +#endif +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH < 0 ) ) + + /* Only the current stack state is to be checked. */ + #define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \ + { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB[ xPortGetCoreID() ]->pxTopOfStack <= pxCurrentTCB[ xPortGetCoreID() ]->pxStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB[ xPortGetCoreID() ], pxCurrentTCB[ xPortGetCoreID() ]->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW > 0 */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH > 0 ) ) + + /* Only the current stack state is to be checked. */ + #define taskFIRST_CHECK_FOR_STACK_OVERFLOW() \ + { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB[ xPortGetCoreID() ]->pxTopOfStack >= pxCurrentTCB[ xPortGetCoreID() ]->pxEndOfStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB[ xPortGetCoreID() ], pxCurrentTCB[ xPortGetCoreID() ]->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) + + #define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \ + { \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pxCurrentTCB[ xPortGetCoreID() ]->pxStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB[ xPortGetCoreID() ], pxCurrentTCB[ xPortGetCoreID() ]->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) + + #define taskSECOND_CHECK_FOR_STACK_OVERFLOW() \ + { \ + int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB[ xPortGetCoreID() ]->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB[ xPortGetCoreID() ], pxCurrentTCB[ xPortGetCoreID() ]->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ + +#endif /* STACK_MACROS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/stream_buffer.h b/tools/sdk/esp32c3/include/freertos/include/freertos/stream_buffer.h new file mode 100644 index 00000000..1a3d8f51 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/stream_buffer.h @@ -0,0 +1,745 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * Stream buffers are used to send a continuous stream of data from one task or + * interrupt to another. Their implementation is light weight, making them + * particularly suited for interrupt to task and core to core communication + * scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferRead()) inside a critical section section and set the + * receive block time to 0. + * + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" +#endif + +#if defined( __cplusplus ) +extern "C" { +#endif + +/** + * Type by which stream buffers are referenced. For example, a call to + * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can + * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), + * etc. + */ +struct StreamBufferDef_t; +typedef struct StreamBufferDef_t * StreamBufferHandle_t; + +/** + * Creates a new stream buffer using dynamically allocated memory. See + * xStreamBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xStreamBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes the stream buffer will be + * able to hold at any one time. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @return If NULL is returned, then the stream buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the stream buffer data structures and storage area. A non-NULL value being + * returned indicates that the stream buffer has been created successfully - + * the returned value should be stored as the handle to the created stream + * buffer. + * + * Example use: + * @code{c} + * + * void vAFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; + * + * // Create a stream buffer that can hold 100 bytes. The memory used to hold + * // both the stream buffer structure and the data in the stream buffer is + * // allocated dynamically. + * xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + * + * if( xStreamBuffer == NULL ) + * { + * // There was not enough heap memory space available to create the + * // stream buffer. + * } + * else + * { + * // The stream buffer was created successfully and can now be used. + * } + * } + * @endcode + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) + +/** + * Creates a new stream buffer using statically allocated memory. See + * xStreamBufferCreate() for a version that uses dynamically allocated memory. + * + * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for + * xStreamBufferCreateStatic() to be available. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucStreamBufferStorageArea parameter. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes + 1 big. This is the array to which streams are + * copied when they are written to the stream buffer. + * + * @param pxStaticStreamBuffer Must point to a variable of type + * StaticStreamBuffer_t, which will be used to hold the stream buffer's data + * structure. + * + * @return If the stream buffer is created successfully then a handle to the + * created stream buffer is returned. If either pucStreamBufferStorageArea or + * pxStaticstreamBuffer are NULL then NULL is returned. + * + * Example use: + * @code{c} + * + * // Used to dimension the array used to hold the streams. The available space + * // will actually be one less than this, so 999. + * #define STORAGE_SIZE_BYTES 1000 + * + * // Defines the memory that will actually hold the streams within the stream + * // buffer. + * static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + * + * // The variable used to hold the stream buffer structure. + * StaticStreamBuffer_t xStreamBufferStruct; + * + * void MyFunction( void ) + * { + * StreamBufferHandle_t xStreamBuffer; + * const size_t xTriggerLevel = 1; + * + * xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ), + * xTriggerLevel, + * ucBufferStorage, + * &xStreamBufferStruct ); + * + * // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer + * // parameters were NULL, xStreamBuffer will not be NULL, and can be used to + * // reference the created stream buffer in other stream buffer API calls. + * + * // Other code that uses the stream buffer can go here. + * } + * + * @endcode + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) + +/** + * Sends bytes to a stream buffer. The bytes are copied into the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the buffer that holds the bytes to be copied + * into the stream buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for enough space to become available in the stream + * buffer, should the stream buffer contain too little space to hold the + * another xDataLengthBytes bytes. The block time is specified in tick periods, + * so the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out + * before it can write all xDataLengthBytes into the buffer it will still write + * as many bytes as possible. A task does not use any CPU time when it is in + * the blocked state. + * + * @return The number of bytes written to the stream buffer. If a task times + * out before it can write all xDataLengthBytes into the buffer it will still + * write as many bytes as possible. + * + * Example use: + * @code{c} + * void vAFunction( StreamBufferHandle_t xStreamBuffer ) + * { + * size_t xBytesSent; + * uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; + * char *pcStringToSend = "String to send"; + * const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + * + * // Send an array to the stream buffer, blocking for a maximum of 100ms to + * // wait for enough space to be available in the stream buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + * + * if( xBytesSent != sizeof( ucArrayToSend ) ) + * { + * // The call to xStreamBufferSend() times out before there was enough + * // space in the buffer for the data to be written, but it did + * // successfully write xBytesSent bytes. + * } + * + * // Send the string to the stream buffer. Return immediately if there is not + * // enough space in the buffer. + * xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // The entire string could not be added to the stream buffer because + * // there was not enough free space in the buffer, but xBytesSent bytes + * // were sent. Could try again to send the remaining bytes. + * } + * } + * @endcode + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * Interrupt safe version of the API function that sends a stream of bytes to + * the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the data that is to be copied into the stream + * buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for data. Calling + * xStreamBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xStreamBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the example code below for an example. + * + * @return The number of bytes actually written to the stream buffer, which will + * be less than xDataLengthBytes if the stream buffer didn't have enough free + * space for all the bytes to be written. + * + * Example use: + * @code{c} + * //A stream buffer that has already been created. + * StreamBufferHandle_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * size_t xBytesSent; + * char *pcStringToSend = "String to send"; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Attempt to send the string to the stream buffer. + * xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, + * ( void * ) pcStringToSend, + * strlen( pcStringToSend ), + * &xHigherPriorityTaskWoken ); + * + * if( xBytesSent != strlen( pcStringToSend ) ) + * { + * // There was not enough free space in the stream buffer for the entire + * // string to be written, ut xBytesSent bytes were written. + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferSendFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * Receives bytes from a stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferReceive() to read from a stream buffer from a task. Use + * xStreamBufferReceiveFromISR() to read from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which bytes are to + * be received. + * + * @param pvRxData A pointer to the buffer into which the received bytes will be + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for data to become available if the stream buffer is + * empty. xStreamBufferReceive() will return immediately if xTicksToWait is + * zero. The block time is specified in tick periods, so the absolute time it + * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can + * be used to convert a time specified in milliseconds into a time specified in + * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait + * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 + * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the + * Blocked state. + * + * @return The number of bytes actually read from the stream buffer, which will + * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed + * out before xBufferLengthBytes were available. + * + * Example use: + * @code{c} + * void vAFunction( StreamBuffer_t xStreamBuffer ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + * + * // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. + * // Wait in the Blocked state (so not using any CPU processing time) for a + * // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be + * // available. + * xReceivedBytes = xStreamBufferReceive( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * xBlockTime ); + * + * if( xReceivedBytes > 0 ) + * { + * // A ucRxData contains another xRecievedBytes bytes of data, which can + * // be processed here.... + * } + * } + * @endcode + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + + +/** + * An interrupt safe version of the API function that receives bytes from a + * stream buffer. + * + * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. + * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which a stream + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received bytes are + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for space to become available. Calling + * xStreamBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The number of bytes read from the stream buffer, if any. + * + * Example use: + * @code{c} + * // A stream buffer that has already been created. + * StreamBuffer_t xStreamBuffer; + * + * void vAnInterruptServiceRoutine( void ) + * { + * uint8_t ucRxData[ 20 ]; + * size_t xReceivedBytes; + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + * + * // Receive the next stream from the stream buffer. + * xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, + * ( void * ) ucRxData, + * sizeof( ucRxData ), + * &xHigherPriorityTaskWoken ); + * + * if( xReceivedBytes > 0 ) + * { + * // ucRxData contains xReceivedBytes read from the stream buffer. + * // Process the stream here.... + * } + * + * // If xHigherPriorityTaskWoken was set to pdTRUE inside + * // xStreamBufferReceiveFromISR() then a task that has a priority above the + * // priority of the currently executing task was unblocked and a context + * // switch should be performed to ensure the ISR returns to the unblocked + * // task. In most FreeRTOS ports this is done by simply passing + * // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + * // variables value, and perform the context switch if necessary. Check the + * // documentation for the port in use for port specific instructions. + * taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * } + * @endcode + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * Deletes a stream buffer that was previously created using a call to + * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream + * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), + * then the allocated memory is freed. + * + * A stream buffer handle must not be used after the stream buffer has been + * deleted. + * + * @param xStreamBuffer The handle of the stream buffer to be deleted. + * + * \ingroup StreamBufferManagement + */ +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * Queries a stream buffer to see if it is full. A stream buffer is full if it + * does not have any free space, and therefore cannot accept any more data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is full then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * Queries a stream buffer to see if it is empty. A stream buffer is empty if + * it does not contain any data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is empty then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * Resets a stream buffer to its initial, empty, state. Any data that was in + * the stream buffer is discarded. A stream buffer can only be reset if there + * are no tasks blocked waiting to either send to or receive from the stream + * buffer. + * + * @param xStreamBuffer The handle of the stream buffer being reset. + * + * @return If the stream buffer is reset then pdPASS is returned. If there was + * a task blocked waiting to send to or read from the stream buffer then the + * stream buffer is not reset and pdFAIL is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * Queries a stream buffer to see how much free space it contains, which is + * equal to the amount of data that can be sent to the stream buffer before it + * is full. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be written to the stream buffer before + * the stream buffer would be full. + * + * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * Queries a stream buffer to see how much data it contains, which is equal to + * the number of bytes that can be read from the stream buffer before the stream + * buffer would be empty. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be read from the stream buffer before + * the stream buffer would be empty. + * + * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * A stream buffer's trigger level is the number of bytes that must be in the + * stream buffer before a task that is blocked on the stream buffer to + * wait for data is moved out of the blocked state. For example, if a task is + * blocked on a read of an empty stream buffer that has a trigger level of 1 + * then the task will be unblocked when a single byte is written to the buffer + * or the task's block time expires. As another example, if a task is blocked + * on a read of an empty stream buffer that has a trigger level of 10 then the + * task will not be unblocked until the stream buffer contains at least 10 bytes + * or the task's block time expires. If a reading task's block time expires + * before the trigger level is reached then the task will still receive however + * many bytes are actually available. Setting a trigger level of 0 will result + * in a trigger level of 1 being used. It is not valid to specify a trigger + * level that is greater than the buffer size. + * + * A trigger level is set when the stream buffer is created, and can be modified + * using xStreamBufferSetTriggerLevel(). + * + * @param xStreamBuffer The handle of the stream buffer being updated. + * + * @param xTriggerLevel The new trigger level for the stream buffer. + * + * @return If xTriggerLevel was less than or equal to the stream buffer's length + * then the trigger level will be updated and pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) PRIVILEGED_FUNCTION; + +/** + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferSendCompletedFromISR(). If calling + * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferReceiveCompletedFromISR(). If calling + * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** @cond */ +/* Functions below here are not part of the public API. */ +StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; + +StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION; + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +#if( configUSE_TRACE_FACILITY == 1 ) + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +#endif + +/** @endcond */ + +#if defined( __cplusplus ) +} +#endif + +#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/task.h b/tools/sdk/esp32c3/include/freertos/include/freertos/task.h new file mode 100644 index 00000000..422948a2 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/task.h @@ -0,0 +1,2563 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef INC_TASK_H +#define INC_TASK_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include task.h" +#endif + +#include "list.h" +#include "freertos/portmacro.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * MACROS AND DEFINITIONS + *----------------------------------------------------------*/ + +#define tskKERNEL_VERSION_NUMBER "V10.2.1" +#define tskKERNEL_VERSION_MAJOR 10 +#define tskKERNEL_VERSION_MINOR 2 +#define tskKERNEL_VERSION_BUILD 1 + +/* MPU region parameters passed in ulParameters + * of MemoryRegion_t struct. */ +#define tskMPU_REGION_READ_ONLY ( 1UL << 0UL ) +#define tskMPU_REGION_READ_WRITE ( 1UL << 1UL ) +#define tskMPU_REGION_EXECUTE_NEVER ( 1UL << 2UL ) +#define tskMPU_REGION_NORMAL_MEMORY ( 1UL << 3UL ) +#define tskMPU_REGION_DEVICE_MEMORY ( 1UL << 4UL ) + +#define tskNO_AFFINITY ( 0x7FFFFFFF ) +/** + * Type by which tasks are referenced. For example, a call to xTaskCreate + * returns (via a pointer parameter) an TaskHandle_t variable that can then + * be used as a parameter to vTaskDelete to delete the task. + * + * \ingroup Tasks + */ +struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +//typedef struct tskTaskControlBlock* TaskHandle_t; +typedef void* TaskHandle_t; +/** + * Defines the prototype to which the application task hook function must + * conform. + */ +typedef BaseType_t (*TaskHookFunction_t)( void * ); + +/** Task states returned by eTaskGetState. */ +typedef enum +{ + eRunning = 0, /* A task is querying the state of itself, so must be running. */ + eReady, /* The task being queried is in a read or pending ready list. */ + eBlocked, /* The task being queried is in the Blocked state. */ + eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ + eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ + eInvalid /* Used as an 'invalid state' value. */ +} eTaskState; + +/* Actions that can be performed when vTaskNotify() is called. */ +typedef enum +{ + eNoAction = 0, /* Notify the task without updating its notify value. */ + eSetBits, /* Set bits in the task's notification value. */ + eIncrement, /* Increment the task's notification value. */ + eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ + eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ +} eNotifyAction; + +/** @cond */ +/** + * Used internally only. + */ +typedef struct xTIME_OUT +{ + BaseType_t xOverflowCount; + TickType_t xTimeOnEntering; +} TimeOut_t; + +/** + * Defines the memory ranges allocated to the task when an MPU is used. + */ +typedef struct xMEMORY_REGION +{ + void *pvBaseAddress; + uint32_t ulLengthInBytes; + uint32_t ulParameters; +} MemoryRegion_t; + +/* + * Parameters required to create an MPU protected task. + */ +typedef struct xTASK_PARAMETERS +{ + TaskFunction_t pvTaskCode; + const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + configSTACK_DEPTH_TYPE usStackDepth; + void *pvParameters; + UBaseType_t uxPriority; + StackType_t *puxStackBuffer; + MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ]; + #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + StaticTask_t * const pxTaskBuffer; + #endif +} TaskParameters_t; + + +/* + * Used with the uxTaskGetSystemState() function to return the state of each task in the system. + */ +typedef struct xTASK_STATUS +{ + TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ + const char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + UBaseType_t xTaskNumber; /* A number unique to the task. */ + eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ + UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ + UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ + uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ + StackType_t *pxStackBase; /* Points to the lowest address of the task's stack area. */ + configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ +#if configTASKLIST_INCLUDE_COREID + BaseType_t xCoreID; /*!< Core this task is pinned to (0, 1, or -1 for tskNO_AFFINITY). This field is present if CONFIG_FREERTOS_VTASKLIST_INCLUDE_COREID is set. */ +#endif +} TaskStatus_t; + +/** + * Used with the uxTaskGetSnapshotAll() function to save memory snapshot of each task in the system. + * We need this struct because TCB_t is defined (hidden) in tasks.c. + */ +typedef struct xTASK_SNAPSHOT +{ + void *pxTCB; /*!< Address of task control block. */ + StackType_t *pxTopOfStack; /*!< Points to the location of the last item placed on the tasks stack. */ + StackType_t *pxEndOfStack; /*!< Points to the end of the stack. pxTopOfStack < pxEndOfStack, stack grows hi2lo + pxTopOfStack > pxEndOfStack, stack grows lo2hi*/ +} TaskSnapshot_t; + +/** @endcond */ + +/** + * Possible return values for eTaskConfirmSleepModeStatus(). + */ +typedef enum +{ + eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ + eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ + eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ +} eSleepModeStatus; + +/** + * Defines the priority used by the idle task. This must not be modified. + * + * \ingroup TaskUtils + */ +#define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U ) + +/** + * Macro for forcing a context switch. + * + * \ingroup SchedulerControl + */ +#define taskYIELD() portYIELD() + +/** + * Macro to mark the start of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * @note This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \ingroup SchedulerControl + */ +#define taskENTER_CRITICAL( x ) portENTER_CRITICAL( x ) +#define taskENTER_CRITICAL_FROM_ISR( ) portSET_INTERRUPT_MASK_FROM_ISR() +#define taskENTER_CRITICAL_ISR(mux) portENTER_CRITICAL_ISR(mux) + +/** + * Macro to mark the end of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * @note This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \ingroup SchedulerControl + */ +#define taskEXIT_CRITICAL( x ) portEXIT_CRITICAL( x ) +#define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) +#define taskEXIT_CRITICAL_ISR(mux) portEXIT_CRITICAL_ISR(mux) + +/** + * Macro to disable all maskable interrupts. + * + * \ingroup SchedulerControl + */ +#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() + +/** + * Macro to enable microcontroller interrupts. + * + * \ingroup SchedulerControl + */ +#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() + +/* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is +0 to generate more optimal code when configASSERT() is defined as the constant +is used in assert() statements. */ +#define taskSCHEDULER_SUSPENDED ( ( BaseType_t ) 0 ) +#define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 ) +#define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 ) + + +/*----------------------------------------------------------- + * TASK CREATION API + *----------------------------------------------------------*/ + +/** + * Create a new task with a specified affinity. + * + * This function is similar to xTaskCreate, but allows setting task affinity + * in SMP system. + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop), or should be + * terminated using vTaskDelete function. + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default + * is 16. + * + * @param usStackDepth The size of the task stack specified as the number of + * bytes. Note that this differs from vanilla FreeRTOS. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task should run. Systems that + * include MPU support can optionally create tasks in a privileged (system) + * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For + * example, to create a privileged task at priority 2 the uxPriority parameter + * should be set to ( 2 | portPRIVILEGE_BIT ). + * + * @param pvCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @param xCoreID If the value is tskNO_AFFINITY, the created task is not + * pinned to any CPU, and the scheduler can run it on any core available. + * Values 0 or 1 indicate the index number of the CPU which the task should + * be pinned to. Specifying values larger than (portNUM_PROCESSORS - 1) will + * cause the function to fail. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * \ingroup Tasks + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + BaseType_t xTaskCreatePinnedToCore( TaskFunction_t pvTaskCode, + const char * const pcName, + const uint32_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pvCreatedTask, + const BaseType_t xCoreID); + +#endif + +/** + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * http://www.freertos.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * See xTaskCreateStatic() for a version that does not use any dynamic memory + * allocation. + * + * xTaskCreate() can only be used to create a task that has unrestricted + * access to the entire microcontroller memory map. Systems that include MPU + * support can alternatively create an MPU constrained task using + * xTaskCreateRestricted(). + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop), or should be + * terminated using vTaskDelete function. + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default + * is 16. + * + * @param usStackDepth The size of the task stack specified as the number of + * bytes. Note that this differs from vanilla FreeRTOS. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task should run. Systems that + * include MPU support can optionally create tasks in a privileged (system) + * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For + * example, to create a privileged task at priority 2 the uxPriority parameter + * should be set to ( 2 | portPRIVILEGE_BIT ). + * + * @param pvCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * @note If program uses thread local variables (ones specified with "__thread" keyword) + * then storage for them will be allocated on the task's stack. + * + * Example usage: + * @code{c} + * // Task to be created. + * void vTaskCode( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * } + * } + * + * // Function that creates a task. + * void vOtherFunction( void ) + * { + * static uint8_t ucParameterToPass; + * TaskHandle_t xHandle = NULL; + * + * // Create the task, storing the handle. Note that the passed parameter ucParameterToPass + * // must exist for the lifetime of the task, so in this case is declared static. If it was just an + * // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time + * // the new task attempts to access it. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); + * configASSERT( xHandle ); + * + * // Use the handle to delete the task. + * if( xHandle != NULL ) + * { + * vTaskDelete( xHandle ); + * } + * } + * @endcode + * \ingroup Tasks + */ + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + static inline IRAM_ATTR BaseType_t xTaskCreate( + TaskFunction_t pvTaskCode, + const char * const pcName, + const uint32_t usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pvCreatedTask) + { + return xTaskCreatePinnedToCore( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pvCreatedTask, tskNO_AFFINITY ); + } + +#endif + + + + +/** + * Create a new task with a specified affinity. + * + * This function is similar to xTaskCreateStatic, but allows specifying + * task affinity in an SMP system. + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop), or should be + * terminated using vTaskDelete function. + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. The maximum length of the string is defined by + * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. + * + * @param ulStackDepth The size of the task stack specified as the number of + * bytes. Note that this differs from vanilla FreeRTOS. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task will run. + * + * @param pxStackBuffer Must point to a StackType_t array that has at least + * ulStackDepth indexes - the array will then be used as the task's stack, + * removing the need for the stack to be allocated dynamically. + * + * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will + * then be used to hold the task's data structures, removing the need for the + * memory to be allocated dynamically. + * + * @param xCoreID If the value is tskNO_AFFINITY, the created task is not + * pinned to any CPU, and the scheduler can run it on any core available. + * Values 0 or 1 indicate the index number of the CPU which the task should + * be pinned to. Specifying values larger than (portNUM_PROCESSORS - 1) will + * cause the function to fail. + * + * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will + * be created and pdPASS is returned. If either pxStackBuffer or pxTaskBuffer + * are NULL then the task will not be created and + * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned. + * + * \ingroup Tasks + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + TaskHandle_t xTaskCreateStaticPinnedToCore( TaskFunction_t pvTaskCode, + const char * const pcName, + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const pxStackBuffer, + StaticTask_t * const pxTaskBuffer, + const BaseType_t xCoreID ); +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * http://www.freertos.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop), or should be + * terminated using vTaskDelete function. + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. The maximum length of the string is defined by + * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. + * + * @param ulStackDepth The size of the task stack specified as the number of + * bytes. Note that this differs from vanilla FreeRTOS. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task will run. + * + * @param pxStackBuffer Must point to a StackType_t array that has at least + * ulStackDepth indexes - the array will then be used as the task's stack, + * removing the need for the stack to be allocated dynamically. + * + * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will + * then be used to hold the task's data structures, removing the need for the + * memory to be allocated dynamically. + * + * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will + * be created and pdPASS is returned. If either pxStackBuffer or pxTaskBuffer + * are NULL then the task will not be created and + * errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY is returned. + * + * @note If program uses thread local variables (ones specified with "__thread" keyword) + * then storage for them will be allocated on the task's stack. + * + * Example usage: + * @code{c} + * + * // Dimensions the buffer that the task being created will use as its stack. + * // NOTE: This is the number of bytes the stack will hold, not the number of + * // words as found in vanilla FreeRTOS. + * #define STACK_SIZE 200 + * + * // Structure that will hold the TCB of the task being created. + * StaticTask_t xTaskBuffer; + * + * // Buffer that the task being created will use as its stack. Note this is + * // an array of StackType_t variables. The size of StackType_t is dependent on + * // the RTOS port. + * StackType_t xStack[ STACK_SIZE ]; + * + * // Function that implements the task being created. + * void vTaskCode( void * pvParameters ) + * { + * // The parameter value is expected to be 1 as 1 is passed in the + * // pvParameters value in the call to xTaskCreateStatic(). + * configASSERT( ( uint32_t ) pvParameters == 1UL ); + * + * for( ;; ) + * { + * // Task code goes here. + * } + * } + * + * // Function that creates a task. + * void vOtherFunction( void ) + * { + * TaskHandle_t xHandle = NULL; + * + * // Create the task without using any dynamic memory allocation. + * xHandle = xTaskCreateStatic( + * vTaskCode, // Function that implements the task. + * "NAME", // Text name for the task. + * STACK_SIZE, // Stack size in bytes, not words. + * ( void * ) 1, // Parameter passed into the task. + * tskIDLE_PRIORITY,// Priority at which the task is created. + * xStack, // Array to use as the task's stack. + * &xTaskBuffer ); // Variable to hold the task's data structure. + * + * // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have + * // been created, and xHandle will be the task's handle. Use the handle + * // to suspend the task. + * vTaskSuspend( xHandle ); + * } + * @endcode + * \ingroup Tasks + */ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + static inline IRAM_ATTR TaskHandle_t xTaskCreateStatic( + TaskFunction_t pvTaskCode, + const char * const pcName, + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const pxStackBuffer, + StaticTask_t * const pxTaskBuffer) + { + return xTaskCreateStaticPinnedToCore( pvTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, pxStackBuffer, pxTaskBuffer, tskNO_AFFINITY ); + } +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/* + * xTaskCreateRestricted() should only be used in systems that include an MPU + * implementation. + * + * Create a new task and add it to the list of tasks that are ready to run. + * The function parameters define the memory regions and associated access + * permissions allocated to the task. + * + * See xTaskCreateRestrictedStatic() for a version that does not use any + * dynamic memory allocation. + * + * param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. + * + * param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: + * @code{c} + * // Create an TaskParameters_t structure that defines the task to be created. + * static const TaskParameters_t xCheckTaskParameters = + * { + * vATask, // pvTaskCode - the function that implements the task. + * "ATask", // pcName - just a text name for the task to assist debugging. + * 100, // usStackDepth - the stack size DEFINED IN WORDS. + * NULL, // pvParameters - passed into the task function as the function parameters. + * ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + * cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + * + * // xRegions - Allocate up to three separate memory regions for access by + * // the task, with appropriate access permissions. Different processors have + * // different memory alignment requirements - refer to the FreeRTOS documentation + * // for full information. + * { + * // Base address Length Parameters + * { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + * { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + * { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + * } + * }; + * + * int main( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task from the const structure defined above. The task handle + * // is requested (the second parameter is not NULL) but in this case just for + * // demonstration purposes as its not actually used. + * xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + * + * // Start the scheduler. + * vTaskStartScheduler(); + * + * // Will only get here if there was insufficient memory to create the idle + * // and/or timer task. + * for( ;; ); + * } + * @endcode + * \ingroup Tasks + */ +#if( portUSING_MPU_WRAPPERS == 1 ) + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ); +#endif + +/* + * xTaskCreateRestrictedStatic() should only be used in systems that include an + * MPU implementation. + * + * Only available when configSUPPORT_STATIC_ALLOCATION is set to 1. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreateRestricted() then the stack is provided by the application writer, + * and the memory used to hold the task's data structure is automatically + * dynamically allocated inside the xTaskCreateRestricted() function. If a task + * is created using xTaskCreateRestrictedStatic() then the application writer + * must provide the memory used to hold the task's data structures too. + * xTaskCreateRestrictedStatic() therefore allows a memory protected task to be + * created without using any dynamic memory allocation. + * + * param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. If configSUPPORT_STATIC_ALLOCATION is set to 1 the structure + * contains an additional member, which is used to point to a variable of type + * StaticTask_t - which is then used to hold the task's data structure. + * + * param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: + * @code{c} + * // Create an TaskParameters_t structure that defines the task to be created. + * // The StaticTask_t variable is only included in the structure when + * // configSUPPORT_STATIC_ALLOCATION is set to 1. The PRIVILEGED_DATA macro can + * // be used to force the variable into the RTOS kernel's privileged data area. + * static PRIVILEGED_DATA StaticTask_t xTaskBuffer; + * static const TaskParameters_t xCheckTaskParameters = + * { + * vATask, // pvTaskCode - the function that implements the task. + * "ATask", // pcName - just a text name for the task to assist debugging. + * 100, // usStackDepth - the stack size DEFINED IN BYTES. + * NULL, // pvParameters - passed into the task function as the function parameters. + * ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + * cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + * + * // xRegions - Allocate up to three separate memory regions for access by + * // the task, with appropriate access permissions. Different processors have + * // different memory alignment requirements - refer to the FreeRTOS documentation + * // for full information. + * { + * // Base address Length Parameters + * { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + * { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + * { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + * } + * + * &xTaskBuffer; // Holds the task's data structure. + * }; + * + * int main( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task from the const structure defined above. The task handle + * // is requested (the second parameter is not NULL) but in this case just for + * // demonstration purposes as its not actually used. + * xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + * + * // Start the scheduler. + * vTaskStartScheduler(); + * + * // Will only get here if there was insufficient memory to create the idle + * // and/or timer task. + * for( ;; ); + * } + * @endcode + * \ingroup Tasks + */ +#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ); +#endif + +/* + * Memory regions are assigned to a restricted task when the task is created by + * a call to xTaskCreateRestricted(). These regions can be redefined using + * vTaskAllocateMPURegions(). + * + * param xTask The handle of the task being updated. + * + * param pxRegions A pointer to an MemoryRegion_t structure that contains the + * new memory region definitions. + * + * Example usage: + * + * @code{c} + * // Define an array of MemoryRegion_t structures that configures an MPU region + * // allowing read/write access for 1024 bytes starting at the beginning of the + * // ucOneKByte array. The other two of the maximum 3 definable regions are + * // unused so set to zero. + * static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = + * { + * // Base address Length Parameters + * { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, + * { 0, 0, 0 }, + * { 0, 0, 0 } + * }; + * + * void vATask( void *pvParameters ) + * { + * // This task was created such that it has access to certain regions of + * // memory as defined by the MPU configuration. At some point it is + * // desired that these MPU regions are replaced with that defined in the + * // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() + * // for this purpose. NULL is used as the task handle to indicate that this + * // function should modify the MPU regions of the calling task. + * vTaskAllocateMPURegions( NULL, xAltRegions ); + * + * // Now the task can continue its function, but from this point on can only + * // access its stack and the ucOneKByte array (unless any other statically + * // defined or shared regions have been declared elsewhere). + * } + * @endcode + * \ingroup Tasks + */ +void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; + +/** + * Remove a task from the RTOS real time kernel's management. The task being + * deleted will be removed from all ready, blocked, suspended and event lists. + * + * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * NOTE: The idle task is responsible for freeing the kernel allocated + * memory from tasks that have been deleted. It is therefore important that + * the idle task is not starved of microcontroller processing time if your + * application makes any calls to vTaskDelete (). Memory allocated by the + * task code is not automatically freed, and should be freed before the task + * is deleted. + * + * See the demo application file death.c for sample code that utilises + * vTaskDelete (). + * + * @param xTaskToDelete The handle of the task to be deleted. Passing NULL will + * cause the calling task to be deleted. + * + * Example usage: + * @code{c} + * void vOtherFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create the task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // Use the handle to delete the task. + * vTaskDelete( xHandle ); + * } + * @endcode + * \ingroup Tasks + */ +void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * TASK CONTROL API + *----------------------------------------------------------*/ + +/** + * Delay a task for a given number of ticks. + * + * Delay a task for a given number of ticks. The actual time that the + * task remains blocked depends on the tick rate. The constant + * portTICK_PERIOD_MS can be used to calculate real time from the tick + * rate - with the resolution of one tick period. + * + * INCLUDE_vTaskDelay must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * vTaskDelay() specifies a time at which the task wishes to unblock relative to + * the time at which vTaskDelay() is called. For example, specifying a block + * period of 100 ticks will cause the task to unblock 100 ticks after + * vTaskDelay() is called. vTaskDelay() does not therefore provide a good method + * of controlling the frequency of a periodic task as the path taken through the + * code, as well as other task and interrupt activity, will effect the frequency + * at which vTaskDelay() gets called and therefore the time at which the task + * next executes. See vTaskDelayUntil() for an alternative API function designed + * to facilitate fixed frequency execution. It does this by specifying an + * absolute time (rather than a relative time) at which the calling task should + * unblock. + * + * @param xTicksToDelay The amount of time, in tick periods, that + * the calling task should block. + * + * Example usage: + * @code{c} + * void vTaskFunction( void * pvParameters ) + * { + * // Block for 500ms. + * const TickType_t xDelay = 500 / portTICK_PERIOD_MS; + * + * for( ;; ) + * { + * // Simply toggle the LED every 500ms, blocking between each toggle. + * vToggleLED(); + * vTaskDelay( xDelay ); + * } + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; + +/** + * Delay a task until a specified time. + * + * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Delay a task until a specified time. This function can be used by periodic + * tasks to ensure a constant execution frequency. + * + * This function differs from vTaskDelay () in one important aspect: vTaskDelay () will + * cause a task to block for the specified number of ticks from the time vTaskDelay () is + * called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed + * execution frequency as the time between a task starting to execute and that task + * calling vTaskDelay () may not be fixed [the task may take a different path though the + * code between calls, or may get interrupted or preempted a different number of times + * each time it executes]. + * + * Whereas vTaskDelay () specifies a wake time relative to the time at which the function + * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to + * unblock. + * + * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick + * rate - with the resolution of one tick period. + * + * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the + * task was last unblocked. The variable must be initialised with the current time + * prior to its first use (see the example below). Following this the variable is + * automatically updated within vTaskDelayUntil (). + * + * @param xTimeIncrement The cycle time period. The task will be unblocked at + * time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the + * same xTimeIncrement parameter value will cause the task to execute with + * a fixed interface period. + * + * Example usage: + * @code{c} + * // Perform an action every 10 ticks. + * void vTaskFunction( void * pvParameters ) + * { + * TickType_t xLastWakeTime; + * const TickType_t xFrequency = 10; + * + * // Initialise the xLastWakeTime variable with the current time. + * xLastWakeTime = xTaskGetTickCount (); + * for( ;; ) + * { + * // Wait for the next cycle. + * vTaskDelayUntil( &xLastWakeTime, xFrequency ); + * + * // Perform action here. + * } + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; + +/** + * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this + * function to be available. + * + * A task will enter the Blocked state when it is waiting for an event. The + * event it is waiting for can be a temporal event (waiting for a time), such + * as when vTaskDelay() is called, or an event on an object, such as when + * xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task + * that is in the Blocked state is used in a call to xTaskAbortDelay() then the + * task will leave the Blocked state, and return from whichever function call + * placed the task into the Blocked state. + * + * @param xTask The handle of the task to remove from the Blocked state. + * + * @return If the task referenced by xTask was not in the Blocked state then + * pdFAIL is returned. Otherwise pdPASS is returned. + * + * \defgroup xTaskAbortDelay xTaskAbortDelay + * \ingroup TaskCtrl + */ +BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * Obtain the priority of any task. + * + * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * @param xTask Handle of the task to be queried. Passing a NULL + * handle results in the priority of the calling task being returned. + * + * @return The priority of xTask. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to obtain the priority of the created task. + * // It was created with tskIDLE_PRIORITY, but may have changed + * // it itself. + * if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) + * { + * // The task has changed it's priority. + * } + * + * // ... + * + * // Is our priority higher than the created task? + * if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) + * { + * // Our priority (obtained using NULL handle) is higher. + * } + * } + * @endcode + * \ingroup TaskCtrl + */ +UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * A version of uxTaskPriorityGet() that can be used from an ISR. + */ +UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * Obtain the state of any task. + * + * States are encoded by the eTaskState enumerated type. + * + * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * @param xTask Handle of the task to be queried. + * + * @return The state of xTask at the time the function was called. Note the + * state of the task might change between the function being called, and the + * functions return value being tested by the calling task. + */ +eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * Populates a TaskStatus_t structure with information about a task. + * + * configUSE_TRACE_FACILITY must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * + * @param xTask Handle of the task being queried. If xTask is NULL then + * information will be returned about the calling task. + * + * @param pxTaskStatus A pointer to the TaskStatus_t structure that will be + * filled with information about the task referenced by the handle passed using + * the xTask parameter. + * + * @param xGetFreeStackSpace The TaskStatus_t structure contains a member to report + * the stack high water mark of the task being queried. Calculating the stack + * high water mark takes a relatively long time, and can make the system + * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to + * allow the high water mark checking to be skipped. The high watermark value + * will only be written to the TaskStatus_t structure if xGetFreeStackSpace is + * not set to pdFALSE; + * + * @param eState The TaskStatus_t structure contains a member to report the + * state of the task being queried. Obtaining the task state is not as fast as + * a simple assignment - so the eState parameter is provided to allow the state + * information to be omitted from the TaskStatus_t structure. To obtain state + * information then set eState to eInvalid - otherwise the value passed in + * eState will be reported as the task state in the TaskStatus_t structure. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * TaskStatus_t xTaskDetails; + * + * // Obtain the handle of a task from its name. + * xHandle = xTaskGetHandle( "Task_Name" ); + * + * // Check the handle is not NULL. + * configASSERT( xHandle ); + * + * // Use the handle to obtain further information about the task. + * vTaskGetInfo( xHandle, + * &xTaskDetails, + * pdTRUE, // Include the high water mark in xTaskDetails. + * eInvalid ); // Include the task state in xTaskDetails. + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) PRIVILEGED_FUNCTION; + +/** + * Set the priority of any task. + * + * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * A context switch will occur before the function returns if the priority + * being set is higher than the currently executing task. + * + * @param xTask Handle to the task for which the priority is being set. + * Passing a NULL handle results in the priority of the calling task being set. + * + * @param uxNewPriority The priority to which the task will be set. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to raise the priority of the created task. + * vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); + * + * // ... + * + * // Use a NULL handle to raise our priority to the same value. + * vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION; + +/** + * Suspend a task. + * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Suspend any task. When suspended a task will never get any microcontroller + * processing time, no matter what its priority. + * + * Calls to vTaskSuspend are not accumulative - + * i.e. calling vTaskSuspend () twice on the same task still only requires one + * call to vTaskResume () to ready the suspended task. + * + * @param xTaskToSuspend Handle to the task being suspended. Passing a NULL + * handle will cause the calling task to be suspended. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to suspend the created task. + * vTaskSuspend( xHandle ); + * + * // ... + * + * // The created task will not run during this period, unless + * // another task calls vTaskResume( xHandle ). + * + * //... + * + * + * // Suspend ourselves. + * vTaskSuspend( NULL ); + * + * // We cannot get here unless another task calls vTaskResume + * // with our handle as the parameter. + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; + +/** + * Resumes a suspended task. + * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * vTaskResume (). + * + * @param xTaskToResume Handle to the task being readied. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * TaskHandle_t xHandle; + * + * // Create a task, storing the handle. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + * + * // ... + * + * // Use the handle to suspend the created task. + * vTaskSuspend( xHandle ); + * + * // ... + * + * // The created task will not run during this period, unless + * // another task calls vTaskResume( xHandle ). + * + * //... + * + * + * // Resume the suspended task ourselves. + * vTaskResume( xHandle ); + * + * // The created task will once again get microcontroller processing + * // time in accordance with its priority within the system. + * } + * @endcode + * \ingroup TaskCtrl + */ +void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/** + * An implementation of vTaskResume() that can be called from within an ISR. + * + * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * xTaskResumeFromISR (). + * + * xTaskResumeFromISR() should not be used to synchronise a task with an + * interrupt if there is a chance that the interrupt could arrive prior to the + * task being suspended - as this can lead to interrupts being missed. Use of a + * semaphore as a synchronisation mechanism would avoid this eventuality. + * + * @param xTaskToResume Handle to the task being readied. + * + * @return pdTRUE if resuming the task should result in a context switch, + * otherwise pdFALSE. This is used by the ISR to determine if a context switch + * may be required following the ISR. + * + * \ingroup TaskCtrl + */ +BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * SCHEDULER CONTROL + *----------------------------------------------------------*/ +/** @cond */ +/** + * Starts the real time kernel tick processing. + * + * After calling the kernel has control over which tasks are executed and when. + * + * See the demo application file main.c for an example of creating + * tasks and starting the kernel. + * + * Example usage: + * @code{c} + * void vAFunction( void ) + * { + * // Create at least one task before starting the kernel. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + * + * // Start the real time kernel with preemption. + * vTaskStartScheduler (); + * + * // Will not get here unless a task calls vTaskEndScheduler () + * } + * @endcode + * + * \ingroup SchedulerControl + */ +void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; + +/** + * Stops the real time kernel tick. + * + * NOTE: At the time of writing only the x86 real mode port, which runs on a PC + * in place of DOS, implements this function. + * + * Stops the real time kernel tick. All created tasks will be automatically + * deleted and multitasking (either preemptive or cooperative) will + * stop. Execution then resumes from the point where vTaskStartScheduler () + * was called, as if vTaskStartScheduler () had just returned. + * + * See the demo application file main. c in the demo/PC directory for an + * example that uses vTaskEndScheduler (). + * + * vTaskEndScheduler () requires an exit function to be defined within the + * portable layer (see vPortEndScheduler () in port. c for the PC port). This + * performs hardware specific operations such as stopping the kernel tick. + * + * vTaskEndScheduler () will cause all of the resources allocated by the + * kernel to be freed - but will not free resources allocated by application + * tasks. + * + * Example usage: + * @code{c} + * void vTaskCode( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // At some point we want to end the real time kernel processing + * // so call ... + * vTaskEndScheduler (); + * } + * } + * + * void vAFunction( void ) + * { + * // Create at least one task before starting the kernel. + * xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + * + * // Start the real time kernel with preemption. + * vTaskStartScheduler (); + * + * // Will only get here when the vTaskCode () task has called + * // vTaskEndScheduler (). When we get here we are back to single task + * // execution. + * } + * @endcode + * \ingroup SchedulerControl + */ +void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; + +/** @endcond */ + +/** + * Suspends the scheduler without disabling interrupts. + * + * Context switches will not occur while the scheduler is suspended. + * + * After calling vTaskSuspendAll () the calling task will continue to execute + * without risk of being swapped out until a call to xTaskResumeAll () has been + * made. + * + * API functions that have the potential to cause a context switch (for example, + * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler + * is suspended. + * + * Example usage: + * @code{c} + * void vTask1( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // ... + * + * // At some point the task wants to perform a long operation during + * // which it does not want to get swapped out. It cannot use + * // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + * // operation may cause interrupts to be missed - including the + * // ticks. + * + * // Prevent the real time kernel swapping out the task. + * vTaskSuspendAll (); + * + * // Perform the operation here. There is no need to use critical + * // sections as we have all the microcontroller processing time. + * // During this time interrupts will still operate and the kernel + * // tick count will be maintained. + * + * // ... + * + * // The operation is complete. Restart the kernel. + * xTaskResumeAll (); + * } + * } + * @endcode + * \ingroup SchedulerControl + */ +void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; + +/** + * Resumes scheduler activity after it was suspended by a call to + * vTaskSuspendAll(). + * + * xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks + * that were previously suspended by a call to vTaskSuspend(). + * + * @return If resuming the scheduler caused a context switch then pdTRUE is + * returned, otherwise pdFALSE is returned. + * + * Example usage: + * @code{c} + * void vTask1( void * pvParameters ) + * { + * for( ;; ) + * { + * // Task code goes here. + * + * // ... + * + * // At some point the task wants to perform a long operation during + * // which it does not want to get swapped out. It cannot use + * // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + * // operation may cause interrupts to be missed - including the + * // ticks. + * + * // Prevent the real time kernel swapping out the task. + * vTaskSuspendAll (); + * + * // Perform the operation here. There is no need to use critical + * // sections as we have all the microcontroller processing time. + * // During this time interrupts will still operate and the real + * // time kernel tick count will be maintained. + * + * // ... + * + * // The operation is complete. Restart the kernel. We want to force + * // a context switch - but there is no point if resuming the scheduler + * // caused a context switch already. + * if( !xTaskResumeAll () ) + * { + * taskYIELD (); + * } + * } + * } + * @endcode + * \ingroup SchedulerControl + */ +BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * TASK UTILITIES + *----------------------------------------------------------*/ + +/** + * Get tick count + * + * @return The count of ticks since vTaskStartScheduler was called. + * + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION; + +/** + * Get tick count from ISR + * + * @return The count of ticks since vTaskStartScheduler was called. + * + * This is a version of xTaskGetTickCount() that is safe to be called from an + * ISR - provided that TickType_t is the natural word size of the + * microcontroller being used or interrupt nesting is either not supported or + * not being used. + * + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION; + +/** + * Get current number of tasks + * + * @return The number of tasks that the real time kernel is currently managing. + * This includes all ready, blocked and suspended tasks. A task that + * has been deleted but not yet freed by the idle task will also be + * included in the count. + * + * \ingroup TaskUtils + */ +UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; + +/** + * Get task name + * + * @return The text (human readable) name of the task referenced by the handle + * xTaskToQuery. A task can query its own name by either passing in its own + * handle, or by setting xTaskToQuery to NULL. + * + * \ingroup TaskUtils + */ +char *pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * @note This function takes a relatively long time to complete and should be + * used sparingly. + * + * @return The handle of the task that has the human readable name pcNameToQuery. + * NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle + * must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. + * + * \ingroup TaskUtils + */ +TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * Returns the high water mark of the stack associated with xTask. + * + * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in bytes not words, unlike vanilla + * FreeRTOS) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in bytes not words, + * unlike vanilla FreeRTOS) since the task referenced by + * xTask was created. + */ +UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * Returns the start of the stack associated with xTask. + * + * INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in words, so on a 32 bit machine + * a value of 1 means 4 bytes) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in words, so + * actual spaces on the stack rather than bytes) since the task referenced by + * xTask was created. + */ +configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * Returns the start of the stack associated with xTask. + * + * INCLUDE_pxTaskGetStackStart must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the lowest stack memory address, regardless of whether the stack grows up or down. + * + * @param xTask Handle of the task associated with the stack returned. + * Set xTask to NULL to return the stack of the calling task. + * + * @return A pointer to the start of the stack. + */ +uint8_t* pxTaskGetStackStart( TaskHandle_t xTask) PRIVILEGED_FUNCTION; + +/* When using trace macros it is sometimes necessary to include task.h before +FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, +so the following two prototypes will cause a compilation error. This can be +fixed by simply guarding against the inclusion of these two prototypes unless +they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration +constant. */ +#ifdef configUSE_APPLICATION_TASK_TAG + #if configUSE_APPLICATION_TASK_TAG == 1 + /** + * Sets pxHookFunction to be the task hook function used by the task xTask. + * @param xTask Handle of the task to set the hook function for + * Passing xTask as NULL has the effect of setting the calling + * tasks hook function. + * @param pxHookFunction Pointer to the hook function. + */ + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; + + /** + * + * Returns the pxHookFunction value assigned to the task xTask. Do not + * call from an interrupt service routine - call + * xTaskGetApplicationTaskTagFromISR() instead. + */ + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + + /** + * + * Returns the pxHookFunction value assigned to the task xTask. Can + * be called from an interrupt service routine. + */ + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ +#endif /* ifdef configUSE_APPLICATION_TASK_TAG */ + +#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + + /** + * Set local storage pointer specific to the given task. + * + * Each task contains an array of pointers that is dimensioned by the + * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. + * The kernel does not use the pointers itself, so the application writer + * can use the pointers for any purpose they wish. + * + * @param xTaskToSet Task to set thread local storage pointer for + * @param xIndex The index of the pointer to set, from 0 to + * configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. + * @param pvValue Pointer value to set. + */ + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; + + + /** + * Get local storage pointer specific to the given task. + * + * Each task contains an array of pointers that is dimensioned by the + * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. + * The kernel does not use the pointers itself, so the application writer + * can use the pointers for any purpose they wish. + * + * @param xTaskToQuery Task to get thread local storage pointer for + * @param xIndex The index of the pointer to get, from 0 to + * configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. + * @return Pointer value + */ + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; + + #if ( configTHREAD_LOCAL_STORAGE_DELETE_CALLBACKS ) + + /** + * Prototype of local storage pointer deletion callback. + */ + typedef void (*TlsDeleteCallbackFunction_t)( int, void * ); + + /** + * Set local storage pointer and deletion callback. + * + * Each task contains an array of pointers that is dimensioned by the + * configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. + * The kernel does not use the pointers itself, so the application writer + * can use the pointers for any purpose they wish. + * + * Local storage pointers set for a task can reference dynamically + * allocated resources. This function is similar to + * vTaskSetThreadLocalStoragePointer, but provides a way to release + * these resources when the task gets deleted. For each pointer, + * a callback function can be set. This function will be called + * when task is deleted, with the local storage pointer index + * and value as arguments. + * + * @param xTaskToSet Task to set thread local storage pointer for + * @param xIndex The index of the pointer to set, from 0 to + * configNUM_THREAD_LOCAL_STORAGE_POINTERS - 1. + * @param pvValue Pointer value to set. + * @param pvDelCallback Function to call to dispose of the local + * storage pointer when the task is deleted. + */ + void vTaskSetThreadLocalStoragePointerAndDelCallback( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue, TlsDeleteCallbackFunction_t pvDelCallback); + #endif + +#endif + +/** + * Calls the hook function associated with xTask. Passing xTask as NULL has + * the effect of calling the Running tasks (the calling task) hook function. + * + * @param xTask Handle of the task to call the hook for. + * @param pvParameter Parameter passed to the hook function for the task to interpret as it + * wants. The return value is the value returned by the task hook function + * registered by the user. + */ +BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION; + +/** + * xTaskGetIdleTaskHandle() is only available if + * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. + * + * Simply returns the handle of the idle task. It is not valid to call + * xTaskGetIdleTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for + * uxTaskGetSystemState() to be available. + * + * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in + * the system. TaskStatus_t structures contain, among other things, members + * for the task handle, task name, task priority, task state, and total amount + * of run time consumed by the task. See the TaskStatus_t structure + * definition in this file for the full member list. + * + * @note This function is intended for debugging use only as its use results in + * the scheduler remaining suspended for an extended period. + * + * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures. + * The array must contain at least one TaskStatus_t structure for each task + * that is under the control of the RTOS. The number of tasks under the control + * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. + * + * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray + * parameter. The size is specified as the number of indexes in the array, or + * the number of TaskStatus_t structures contained in the array, not by the + * number of bytes in the array. + * + * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in + * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the + * total run time (as defined by the run time stats clock, see + * http://www.freertos.org/rtos-run-time-stats.html) since the target booted. + * pulTotalRunTime can be set to NULL to omit the total run time information. + * + * @return The number of TaskStatus_t structures that were populated by + * uxTaskGetSystemState(). This should equal the number returned by the + * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed + * in the uxArraySize parameter was too small. + * + * Example usage: + * @code{c} + * // This example demonstrates how a human readable table of run time stats + * // information is generated from raw data provided by uxTaskGetSystemState(). + * // The human readable table is written to pcWriteBuffer + * void vTaskGetRunTimeStats( char *pcWriteBuffer ) + * { + * TaskStatus_t *pxTaskStatusArray; + * volatile UBaseType_t uxArraySize, x; + * uint32_t ulTotalRunTime, ulStatsAsPercentage; + * + * // Make sure the write buffer does not contain a string. + * *pcWriteBuffer = 0x00; + * + * // Take a snapshot of the number of tasks in case it changes while this + * // function is executing. + * uxArraySize = uxTaskGetNumberOfTasks(); + * + * // Allocate a TaskStatus_t structure for each task. An array could be + * // allocated statically at compile time. + * pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); + * + * if( pxTaskStatusArray != NULL ) + * { + * // Generate raw status information about each task. + * uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); + * + * // For percentage calculations. + * ulTotalRunTime /= 100UL; + * + * // Avoid divide by zero errors. + * if( ulTotalRunTime > 0 ) + * { + * // For each populated position in the pxTaskStatusArray array, + * // format the raw data as human readable ASCII data + * for( x = 0; x < uxArraySize; x++ ) + * { + * // What percentage of the total run time has the task used? + * // This will always be rounded down to the nearest integer. + * // ulTotalRunTimeDiv100 has already been divided by 100. + * ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; + * + * if( ulStatsAsPercentage > 0UL ) + * { + * sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + * } + * else + * { + * // If the percentage is zero here then the task has + * // consumed less than 1% of the total run time. + * sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); + * } + * + * pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); + * } + * } + * + * // The array is no longer needed, free the memory it consumes. + * vPortFree( pxTaskStatusArray ); + * } + * } + * @endcode + */ +UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; + +/** + * List all the current tasks. + * + * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must + * both be defined as 1 for this function to be available. See the + * configuration section of the FreeRTOS.org website for more information. + * + * @note This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Lists all the current tasks, along with their current state and stack + * usage high water mark. + * + * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or + * suspended ('S'). + * + * @note This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays task + * names, states and stack usage. + * + * vTaskList() has a dependency on the sprintf() C library function that might + * bloat the code size, use a lot of stack, and provide different results on + * different platforms. An alternative, tiny, third party, and limited + * functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly through a + * call to vTaskList(). + * + * @param pcWriteBuffer A buffer into which the above mentioned details + * will be written, in ASCII form. This buffer is assumed to be large + * enough to contain the generated report. Approximately 40 bytes per + * task should be sufficient. + * + * \ingroup TaskUtils + */ +void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * Get the state of running tasks as a string + * + * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS + * must both be defined as 1 for this function to be available. The application + * must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() + * to configure a peripheral timer/counter and return the timers current count + * value respectively. The counter should be at least 10 times the frequency of + * the tick count. + * + * @note This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * Calling vTaskGetRunTimeStats() writes the total execution time of each + * task into a buffer, both as an absolute count value and as a percentage + * of the total system execution time. + * + * @note This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays the + * amount of time each task has spent in the Running state in both absolute and + * percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function + * that might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, and + * limited functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() directly + * to get access to raw stats data, rather than indirectly through a call to + * vTaskGetRunTimeStats(). + * + * @param pcWriteBuffer A buffer into which the execution times will be + * written, in ASCII form. This buffer is assumed to be large enough to + * contain the generated report. Approximately 40 bytes per task should + * be sufficient. + * + * \ingroup TaskUtils + */ +void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** +* configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS +* must both be defined as 1 for this function to be available. The application +* must also then provide definitions for +* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() +* to configure a peripheral timer/counter and return the timers current count +* value respectively. The counter should be at least 10 times the frequency of +* the tick count. +* +* Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total +* accumulated execution time being stored for each task. The resolution +* of the accumulated time value depends on the frequency of the timer +* configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. +* While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total +* execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() +* returns the total execution time of just the idle task. +* +* @return The total run time of the idle task. This is the amount of time the +* idle task has actually been executing. The unit of time is dependent on the +* frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and +* portGET_RUN_TIME_COUNTER_VALUE() macros. +* +* \ingroup TaskUtils +*/ +uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; + +/** + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. xTaskNofify() + * always returns pdPASS in this case. + * + * eIncrement - + * The task's notification value is incremented. ulValue is not used and + * xTaskNotify() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The task's notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification (the + * task already had a notification pending). xTaskNotify() always returns + * pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending then + * the task's notification value is set to ulValue and xTaskNotify() will + * return pdPASS. If the task being notified already had a notification + * pending then no action is performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification without its notification value being + * updated. ulValue is not used and xTaskNotify() always returns pdPASS in + * this case. + * + * @param pulPreviousNotificationValue Can be used to pass out the subject + * task's notification value before any bits are modified by the notify + * function. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) PRIVILEGED_FUNCTION; +#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL ) +#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) + +/** + * Send task notification from an ISR. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * A version of xTaskNotify() that can be used from an interrupt service routine + * (ISR). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. xTaskNofify() + * always returns pdPASS in this case. + * + * eIncrement - + * The task's notification value is incremented. ulValue is not used and + * xTaskNotify() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The task's notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification (the + * task already had a notification pending). xTaskNotify() always returns + * pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending then + * the task's notification value is set to ulValue and xTaskNotify() will + * return pdPASS. If the task being notified already had a notification + * pending then no action is performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification without its notification value being + * updated. ulValue is not used and xTaskNotify() always returns pdPASS in + * this case. + * + * @param pulPreviousNotificationValue Can be used to pass out the subject task's + * notification value before any bits are modified by the notify function. + * + * @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should + * be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) + +/** + * Wait for task notification + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value + * will be cleared in the calling task's notification value before the task + * checks to see if any notifications are pending, and optionally blocks if no + * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if + * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have + * the effect of resetting the task's notification value to 0. Setting + * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. + * + * @param ulBitsToClearOnExit If a notification is pending or received before + * the calling task exits the xTaskNotifyWait() function then the task's + * notification value (see the xTaskNotify() API function) is passed out using + * the pulNotificationValue parameter. Then any bits that are set in + * ulBitsToClearOnExit will be cleared in the task's notification value (note + * *pulNotificationValue is set before any bits are cleared). Setting + * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL + * (if limits.h is not included) will have the effect of resetting the task's + * notification value to 0 before the function exits. Setting + * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged + * when the function exits (in which case the value passed out in + * pulNotificationValue will match the task's notification value). + * + * @param pulNotificationValue Used to pass the task's notification value out + * of the function. Note the value passed out will not be effected by the + * clearing of any bits caused by ulBitsToClearOnExit being non-zero. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for a notification to be received, should a notification + * not already be pending when xTaskNotifyWait() was called. The task + * will not consume any processing time while it is in the Blocked state. This + * is specified in kernel ticks, the macro pdMS_TO_TICKS( value_in_ms ) can be + * used to convert a time specified in milliseconds to a time specified in + * ticks. + * + * @return If a notification was received (including notifications that were + * already pending when xTaskNotifyWait was called) then pdPASS is + * returned. Otherwise pdFAIL is returned. + * + * \ingroup TaskNotifications + */ +BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * Simplified macro for sending task notification. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * xTaskNotifyGive() is a helper macro intended for use when task notifications + * are used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, + * the equivalent action that instead uses a task notification is + * xTaskNotifyGive(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTake() API function rather than the + * xTaskNotifyWait() API function. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the + * eAction parameter set to eIncrement - so pdPASS is always returned. + * + * \ingroup TaskNotifications + */ +#define xTaskNotifyGive( xTaskToNotify ) xTaskGenericNotify( ( xTaskToNotify ), ( 0 ), eIncrement, NULL ) + +/** + * Simplified macro for sending task notification from ISR. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * A version of xTaskNotifyGive() that can be called from an interrupt service + * routine (ISR). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * vTaskNotifyGiveFromISR() is intended for use when task notifications are + * used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given from an ISR using the + * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses + * a task notification is vTaskNotifyGiveFromISR(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTake() API function rather than the + * xTaskNotifyWait() API function. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param pxHigherPriorityTaskWoken vTaskNotifyGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch + * should be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * \ingroup TaskNotifications + */ +void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * Simplified macro for receiving task notification. + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * ulTaskNotifyTake() is intended for use when a task notification is used as a + * faster and lighter weight binary or counting semaphore alternative. Actual + * FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the + * equivalent action that instead uses a task notification is + * ulTaskNotifyTake(). + * + * When a task is using its notification value as a binary or counting semaphore + * other tasks should send notifications to it using the xTaskNotifyGive() + * macro, or xTaskNotify() function with the eAction parameter set to + * eIncrement. + * + * ulTaskNotifyTake() can either clear the task's notification value to + * zero on exit, in which case the notification value acts like a binary + * semaphore, or decrement the task's notification value on exit, in which case + * the notification value acts like a counting semaphore. + * + * A task can use ulTaskNotifyTake() to [optionally] block to wait for a + * the task's notification value to be non-zero. The task does not consume any + * CPU time while it is in the Blocked state. + * + * Where as xTaskNotifyWait() will return when a notification is pending, + * ulTaskNotifyTake() will return when the task's notification value is + * not zero. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's + * notification value is decremented when the function exits. In this way the + * notification value acts like a counting semaphore. If xClearCountOnExit is + * not pdFALSE then the task's notification value is cleared to zero when the + * function exits. In this way the notification value acts like a binary + * semaphore. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for the task's notification value to be greater than zero, + * should the count not already be greater than zero when + * ulTaskNotifyTake() was called. The task will not consume any processing + * time while it is in the Blocked state. This is specified in kernel ticks, + * the macro pdMS_TO_TICKS( value_in_ms ) can be used to convert a time + * specified in milliseconds to a time specified in ticks. + * + * @return The task's notification count before it is either cleared to zero or + * decremented (see the xClearCountOnExit parameter). + * + * \ingroup TaskNotifications + */ +uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * + * If the notification state of the task referenced by the handle xTask is + * eNotified, then set the task's notification state to eNotWaitingNotification. + * The task's notification value is not altered. Set xTask to NULL to clear the + * notification state of the calling task. + * + * @return pdTRUE if the task's notification state was set to + * eNotWaitingNotification, otherwise pdFALSE. + * + * \ingroup TaskNotifications + */ +BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ); + +/*----------------------------------------------------------- + * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES + *----------------------------------------------------------*/ +/** @cond */ +/* + * Return the handle of the task running on a certain CPU. Because of + * the nature of SMP processing, there is no guarantee that this + * value will still be valid on return and should only be used for + * debugging purposes. + */ +TaskHandle_t xTaskGetCurrentTaskHandleForCPU( BaseType_t cpuid ); + +/** + * Get the handle of idle task for the given CPU. + * + * xTaskGetIdleTaskHandleForCPU() is only available if + * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. + * + * @param cpuid The CPU to get the handle for + * + * @return Idle task handle of a given cpu. It is not valid to call + * xTaskGetIdleTaskHandleForCPU() before the scheduler has been started. + */ +TaskHandle_t xTaskGetIdleTaskHandleForCPU( UBaseType_t cpuid ); + + +/* + * Get the current core affinity of a task + */ +BaseType_t xTaskGetAffinity( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Called from the real time kernel tick (either preemptive or cooperative), + * this increments the tick count and checks if any tasks that are blocked + * for a finite period required removing from a blocked list and placing on + * a ready list. If a non-zero value is returned then a context switch is + * required because either: + * + A task was removed from a blocked list because its timeout had expired, + * or + * + Time slicing is in use and there is a task of equal priority to the + * currently running task. + */ +BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes the calling task from the ready list and places it both + * on the list of tasks waiting for a particular event, and the + * list of delayed tasks. The task will be removed from both lists + * and replaced on the ready list should either the event occur (and + * there be no higher priority tasks waiting on the same event) or + * the delay period expires. + * + * The 'unordered' version replaces the event list item value with the + * xItemValue value, and inserts the list item at the end of the list. + * + * The 'ordered' version uses the existing event list item value (which is the + * owning tasks priority) to insert the list item into the event list is task + * priority order. + * + * @param pxEventList The list containing tasks that are blocked waiting + * for the event to occur. + * + * @param xItemValue The item value to use for the event list item when the + * event list is not ordered by task priority. + * + * @param xTicksToWait The maximum amount of time that the task should wait + * for the event to occur. This is specified in kernel ticks,the constant + * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time + * period. + */ +void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * This function performs nearly the same function as vTaskPlaceOnEventList(). + * The difference being that this function does not permit tasks to block + * indefinitely, whereas vTaskPlaceOnEventList() does. + * + */ +void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes a task from both the specified event list and the list of blocked + * tasks, and places it on a ready queue. + * + * xTaskRemoveFromEventList()/vTaskRemoveFromUnorderedEventList() will be called + * if either an event occurs to unblock a task, or the block timeout period + * expires. + * + * xTaskRemoveFromEventList() is used when the event list is in task priority + * order. It removes the list item from the head of the event list as that will + * have the highest priority owning task of all the tasks on the event list. + * vTaskRemoveFromUnorderedEventList() is used when the event list is not + * ordered and the event list items hold something other than the owning tasks + * priority. In this case the event list item value is updated to the value + * passed in the xItemValue parameter. + * + * @return pdTRUE if the task being removed has a higher priority than the task + * making the call, otherwise pdFALSE. + */ +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION; +BaseType_t xTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Sets the pointer to the current TCB to the TCB of the highest priority task + * that is ready to run. + */ +void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; + +/* + * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY + * THE EVENT BITS MODULE. + */ +TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION; + +/* + * Return the handle of the calling task. + */ +TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION; + +/* + * Capture the current time status for future reference. + */ +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + +/* + * Compare the time status now with that previously captured to see if the + * timeout has expired. + */ +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * Shortcut used by the queue implementation to prevent unnecessary call to + * taskYIELD(); + */ +void vTaskMissedYield( void ) PRIVILEGED_FUNCTION; + +/* + * Returns the scheduler state as taskSCHEDULER_RUNNING, + * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED. + */ +BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION; + +/* + * Raises the priority of the mutex holder to that of the calling task should + * the mutex holder have a priority less than the calling task. + */ +BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * Set the priority of a task back to its proper priority in the case that it + * inherited a higher priority while it was holding a semaphore. + */ +BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * If a higher priority task attempting to obtain a mutex caused a lower + * priority task to inherit the higher priority task's priority - but the higher + * priority task then timed out without obtaining the mutex, then the lower + * priority task will disinherit the priority again - but only down as far as + * the highest priority task that is still waiting for the mutex (if there were + * more than one task waiting for the mutex). + */ +void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) PRIVILEGED_FUNCTION; + +/* + * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. + */ +UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* + * Get the current core affinity of a task + */ +BaseType_t xTaskGetAffinity( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* + * Set the uxTaskNumber of the task referenced by the xTask parameter to + * uxHandle. + */ +void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * If tickless mode is being used, or a low power mode is implemented, then + * the tick interrupt will not execute during idle periods. When this is the + * case, the tick count value maintained by the scheduler needs to be kept up + * to date with the actual execution time by being skipped forward by a time + * equal to the idle period. + */ +void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; + +/* Correct the tick count value after the application code has held +interrupts disabled for an extended period. xTicksToCatchUp is the number +of tick interrupts that have been missed due to interrupts being disabled. +Its value is not computed automatically, so must be computed by the +application writer. + +This function is similar to vTaskStepTick(), however, unlike +vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a +time at which a task should be removed from the blocked state. That means +tasks may have to be removed from the blocked state as the tick count is +moved. */ +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port + * specific sleep function to determine if it is ok to proceed with the sleep, + * and if it is ok to proceed, if it is ok to sleep indefinitely. + * + * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only + * called with the scheduler suspended, not from within a critical section. It + * is therefore possible for an interrupt to request a context switch between + * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being + * entered. eTaskConfirmSleepModeStatus() should be called from a short + * critical section between the timer being stopped and the sleep mode being + * entered to ensure it is ok to proceed into the sleep mode. + */ +eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Increment the mutex held count when a mutex is + * taken and return the handle of the task that has taken the mutex. + */ +TaskHandle_t pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Same as vTaskSetTimeOutState(), but without a critial + * section. + */ +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + +/* + * This function fills array with TaskSnapshot_t structures for every task in the system. + * Used by panic handling code to get snapshots of all tasks in the system. + * Only available when configENABLE_TASK_SNAPSHOT is set to 1. + * @param pxTaskSnapshotArray Pointer to array of TaskSnapshot_t structures to store tasks snapshot data. + * @param uxArraySize Size of tasks snapshots array. + * @param pxTcbSz Pointer to store size of TCB. + * @return Number of elements stored in array. + */ +UBaseType_t uxTaskGetSnapshotAll( TaskSnapshot_t * const pxTaskSnapshotArray, const UBaseType_t uxArraySize, UBaseType_t * const pxTcbSz ); + +/* + * This function iterates over all tasks in the system. + * Used by panic handling code to iterate over tasks in the system. + * Only available when configENABLE_TASK_SNAPSHOT is set to 1. + * @note This function should not be used while FreeRTOS is running (as it doesn't acquire any locks). + * @param pxTask task handle. + * @return Handle for the next task. If pxTask is NULL, returns hadnle for the first task. + */ +TaskHandle_t pxTaskGetNext( TaskHandle_t pxTask ); + +/* + * This function fills TaskSnapshot_t structure for specified task. + * Used by panic handling code to get snapshot of a task. + * Only available when configENABLE_TASK_SNAPSHOT is set to 1. + * @note This function should not be used while FreeRTOS is running (as it doesn't acquire any locks). + * @param pxTask task handle. + * @param pxTaskSnapshot address of TaskSnapshot_t structure to fill. + */ +void vTaskGetSnapshot( TaskHandle_t pxTask, TaskSnapshot_t *pxTaskSnapshot ); + +/** @endcond */ +#ifdef __cplusplus +} +#endif +#endif /* INC_TASK_H */ diff --git a/tools/sdk/esp32c3/include/freertos/include/freertos/timers.h b/tools/sdk/esp32c3/include/freertos/include/freertos/timers.h new file mode 100644 index 00000000..9a5e2338 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/include/freertos/timers.h @@ -0,0 +1,1249 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef TIMERS_H +#define TIMERS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include timers.h" +#endif + +/*lint -save -e537 This headers are only multiply included if the application code +happens to also be including task.h. */ +#include "task.h" +/*lint -restore */ + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * MACROS AND DEFINITIONS + *----------------------------------------------------------*/ + +/* IDs for commands that can be sent/received on the timer queue. These are to +be used solely through the macros that make up the public software timer API, +as defined below. The commands that are sent from interrupts must use the +highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task +or interrupt version of the queue send function should be used. */ +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) + +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) + + +/** + * Type by which software timers are referenced. For example, a call to + * xTimerCreate() returns an TimerHandle_t variable that can then be used to + * reference the subject timer in calls to other software timer API functions + * (for example, xTimerStart(), xTimerReset(), etc.). + */ +struct tmrTimerControl; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +//typedef struct tmrTimerControl * TimerHandle_t; +typedef void* TimerHandle_t; +/* + * Defines the prototype to which timer callback functions must conform. + */ +typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); + +/* + * Defines the prototype to which functions used with the + * xTimerPendFunctionCallFromISR() function must conform. + */ +typedef void (*PendedFunction_t)( void *, uint32_t ); + +/** + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * http://www.freertos.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @return If the timer is successfully created then a handle to the newly + * created timer is returned. If the timer cannot be created (because either + * there is insufficient FreeRTOS heap remaining to allocate the timer + * structures, or the timer period was set to 0) then NULL is returned. + * + * Example usage: + * @code{c} + * #define NUM_TIMERS 5 + * + * // An array to hold handles to the created timers. + * TimerHandle_t xTimers[ NUM_TIMERS ]; + * + * // An array to hold a count of the number of times each timer expires. + * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; + * + * // Define a callback function that will be used by multiple timer instances. + * // The callback function does nothing but count the number of times the + * // associated timer expires, and stop the timer once the timer has expired + * // 10 times. + * void vTimerCallback( TimerHandle_t pxTimer ) + * { + * int32_t lArrayIndex; + * const int32_t xMaxExpiryCountBeforeStopping = 10; + * + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); + * + * // Which timer expired? + * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); + * + * // Increment the number of times that pxTimer has expired. + * lExpireCounters[ lArrayIndex ] += 1; + * + * // If the timer has expired 10 times then stop it from running. + * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) + * { + * // Do not use a block time if calling a timer API function from a + * // timer callback function, as doing so could cause a deadlock! + * xTimerStop( pxTimer, 0 ); + * } + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start some timers. Starting the timers before the scheduler + * // has been started means the timers will start running immediately that + * // the scheduler starts. + * for( x = 0; x < NUM_TIMERS; x++ ) + * { + * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. + * ( 100 * x ), // The timer period in ticks. + * pdTRUE, // The timers will auto-reload themselves when they expire. + * ( void * ) x, // Assign each timer a unique id equal to its array index. + * vTimerCallback // Each timer calls the same callback when it expires. + * ); + * + * if( xTimers[ x ] == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endcode + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; +#endif + + /** + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * http://www.freertos.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which + * will be then be used to hold the software timer's data structures, removing + * the need for the memory to be allocated dynamically. + * + * @return If the timer is created then a handle to the created timer is + * returned. If pxTimerBuffer was NULL then NULL is returned. + * + * Example usage: + * @code{c} + * + * // The buffer used to hold the software timer's data structure. + * static StaticTimer_t xTimerBuffer; + * + * // A variable that will be incremented by the software timer's callback + * // function. + * UBaseType_t uxVariableToIncrement = 0; + * + * // A software timer callback function that increments a variable passed to + * // it when the software timer was created. After the 5th increment the + * // callback function stops the software timer. + * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) + * { + * UBaseType_t *puxVariableToIncrement; + * BaseType_t xReturned; + * + * // Obtain the address of the variable to increment from the timer ID. + * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); + * + * // Increment the variable to show the timer callback has executed. + * ( *puxVariableToIncrement )++; + * + * // If this callback has executed the required number of times, stop the + * // timer. + * if( *puxVariableToIncrement == 5 ) + * { + * // This is called from a timer callback so must not block. + * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); + * } + * } + * + * + * void main( void ) + * { + * // Create the software time. xTimerCreateStatic() has an extra parameter + * // than the normal xTimerCreate() API function. The parameter is a pointer + * // to the StaticTimer_t structure that will hold the software timer + * // structure. If the parameter is passed as NULL then the structure will be + * // allocated dynamically, just as if xTimerCreate() had been called. + * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. + * xTimerPeriod, // The period of the timer in ticks. + * pdTRUE, // This is an auto-reload timer. + * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function + * prvTimerCallback, // The function to execute when the timer expires. + * &xTimerBuffer ); // The buffer that will hold the software timer structure. + * + * // The scheduler has not started yet so a block time is not used. + * xReturned = xTimerStart( xTimer, 0 ); + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endcode + */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * void *pvTimerGetTimerID( TimerHandle_t xTimer ); + * + * Returns the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer, and by calling the + * vTimerSetTimerID() API function. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being queried. + * + * @return The ID assigned to the timer being queried. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void *pvTimerGetTimerID( const TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); + * + * Sets the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being updated. + * + * @param pvNewID The ID to assign to the timer. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); + * + * Queries a timer to see if it is active or dormant. + * + * A timer will be dormant if: + * 1) It has been created but not started, or + * 2) It is an expired one-shot timer that has not been restarted. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the + * active state. + * + * @param xTimer The timer being queried. + * + * @return pdFALSE will be returned if the timer is dormant. A value other than + * pdFALSE will be returned if the timer is active. + * + * Example usage: + * @code{c} + * // This function assumes xTimer has already been created. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is active, do something. + * } + * else + * { + * // xTimer is not active, do something else. + * } + * } + * @endcode + */ +BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * xTimerGetTimerDaemonTaskHandle() is only available if + * INCLUDE_xTimerGetTimerDaemonTaskHandle is set to 1 in FreeRTOSConfig.h. + * + * Simply returns the handle of the timer service/daemon task. It it not valid + * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStart() starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerStart() has equivalent functionality + * to the xTimerReset() API function. + * + * Starting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerStart() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerStart() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerStart() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() + * to be available. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the start command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStart( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStop() stops a timer that was previously started using either of the + * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), + * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. + * + * Stopping a timer ensures the timer is not in the active state. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() + * to be available. + * + * @param xTimer The handle of the timer being stopped. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the stop command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) + +/** + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerChangePeriod() changes the period of a timer that was previously + * created using the xTimerCreate() API function. + * + * xTimerChangePeriod() can be called to change the period of an active or + * dormant state timer. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerChangePeriod() to be available. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the change period command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerChangePeriod() was called. xTicksToWait is ignored if + * xTimerChangePeriod() is called before the scheduler is started. + * + * @return pdFAIL will be returned if the change period command could not be + * sent to the timer command queue even after xTicksToWait ticks had passed. + * pdPASS will be returned if the command was successfully sent to the timer + * command queue. When the command is actually processed will depend on the + * priority of the timer service/daemon task relative to other tasks in the + * system. The timer service/daemon task priority is set by the + * configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @code{c} + * // This function assumes xTimer has already been created. If the timer + * // referenced by xTimer is already active when it is called, then the timer + * // is deleted. If the timer referenced by xTimer is not active when it is + * // called, then the period of the timer is set to 500ms and the timer is + * // started. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is already active - delete it. + * xTimerDelete( xTimer ); + * } + * else + * { + * // xTimer is not active, change its period to 500ms. This will also + * // cause the timer to start. Block for a maximum of 100 ticks if the + * // change period command cannot immediately be sent to the timer + * // command queue. + * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) + * { + * // The command was successfully sent. + * } + * else + * { + * // The command could not be sent, even after waiting for 100 ticks + * // to pass. Take appropriate action here. + * } + * } + * } + * @endcode + */ + #define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) + +/** + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerDelete() deletes a timer that was previously created using the + * xTimerCreate() API function. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerDelete() to be available. + * + * @param xTimer The handle of the timer being deleted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the delete command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() + * is called before the scheduler is started. + * + * @return pdFAIL will be returned if the delete command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerChangePeriod() API function example usage scenario. + */ +#define xTimerDelete( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) + +/** + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerReset() re-starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerReset() will cause the timer to + * re-evaluate its expiry time so that it is relative to when xTimerReset() was + * called. If the timer was in the dormant state then xTimerReset() has + * equivalent functionality to the xTimerStart() API function. + * + * Resetting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerReset() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerReset() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerReset() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() + * to be available. + * + * @param xTimer The handle of the timer being reset/started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the reset command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @code{c} + * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer. + * + * TimerHandle_t xBacklightTimer = NULL; + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press event handler. + * void vKeyPressEventHandler( char cKey ) + * { + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. Wait 10 ticks for the command to be successfully sent + * // if it cannot be sent immediately. + * vSetBacklightState( BACKLIGHT_ON ); + * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start the one-shot timer that is responsible for turning + * // the back-light off if no keys are pressed within a 5 second period. + * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. + * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. + * pdFALSE, // The timer is a one-shot timer. + * 0, // The id is not used by the callback so can take any value. + * vBacklightTimerCallback // The callback function that switches the LCD back-light off. + * ); + * + * if( xBacklightTimer == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timer running as it has already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endcode + */ +#define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * A version of xTimerStart() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStartFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStartFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStartFromISR() function. If + * xTimerStartFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerStartFromISR() is actually called. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @code{c} + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then restart the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The start command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endcode + */ +#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * A version of xTimerStop() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being stopped. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStopFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStopFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStopFromISR() function. If + * xTimerStopFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @code{c} + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the timer should be simply stopped. + * + * // The interrupt service routine that stops the timer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - simply stop the timer. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The stop command was not executed successfully. Take appropriate + * // action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endcode + */ +#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * A version of xTimerChangePeriod() that can be called from an interrupt + * service routine. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerChangePeriodFromISR() writes a message to the + * timer command queue, so has the potential to transition the timer service/ + * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() + * causes the timer service/daemon task to leave the Blocked state, and the + * timer service/daemon task has a priority equal to or greater than the + * currently executing task (the task that was interrupted), then + * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the + * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets + * this value to pdTRUE then a context switch should be performed before the + * interrupt exits. + * + * @return pdFAIL will be returned if the command to change the timers period + * could not be sent to the timer command queue. pdPASS will be returned if the + * command was successfully sent to the timer command queue. When the command + * is actually processed will depend on the priority of the timer service/daemon + * task relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @code{c} + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the period of xTimer should be changed to 500ms. + * + * // The interrupt service routine that changes the period of xTimer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - change the period of xTimer to 500ms. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The command to change the timers period was not executed + * // successfully. Take appropriate action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endcode + */ +#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * A version of xTimerReset() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer that is to be started, reset, or + * restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerResetFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerResetFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerResetFromISR() function. If + * xTimerResetFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerResetFromISR() is actually called. The timer service/daemon + * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @code{c} + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endcode + */ +#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + + +/** + * Used from application interrupt service routines to defer the execution of a + * function to the RTOS daemon task (the timer service task, hence this function + * is implemented in timers.c and is prefixed with 'Timer'). + * + * Ideally an interrupt service routine (ISR) is kept as short as possible, but + * sometimes an ISR either has a lot of processing to do, or needs to perform + * processing that is not deterministic. In these cases + * xTimerPendFunctionCallFromISR() can be used to defer processing of a function + * to the RTOS daemon task. + * + * A mechanism is provided that allows the interrupt to return directly to the + * task that will subsequently execute the pended callback function. This + * allows the callback function to execute contiguously in time with the + * interrupt - just as if the callback had executed in the interrupt itself. + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task (which is set using + * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of + * the currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE within + * xTimerPendFunctionCallFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + * Example usage: + * @code{c} + * + * // The callback function that will execute in the context of the daemon task. + * // Note callback functions must all use this same prototype. + * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) + * { + * BaseType_t xInterfaceToService; + * + * // The interface that requires servicing is passed in the second + * // parameter. The first parameter is not used in this case. + * xInterfaceToService = ( BaseType_t ) ulParameter2; + * + * // ...Perform the processing here... + * } + * + * // An ISR that receives data packets from multiple interfaces + * void vAnISR( void ) + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); + * + * // The actual processing is to be deferred to a task. Request the + * // vProcessInterface() callback function is executed, passing in the + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * + * } + * @endcode + */ +BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + + /** + * Used to defer the execution of a function to the RTOS daemon task (the timer + * service task, hence this function is implemented in timers.c and is prefixed + * with 'Timer'). + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param xTicksToWait Calling this function will result in a message being + * sent to the timer daemon task on a queue. xTicksToWait is the amount of + * time the calling task should remain in the Blocked state (so not using any + * processing time) for space to become available on the timer queue if the + * queue is found to be full. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + */ +BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * const char * const pcTimerGetName( TimerHandle_t xTimer ); + * + * Returns the name that was assigned to a timer when the timer was created. + * + * @param xTimer The handle of the timer being queried. + * + * @return The name assigned to the timer specified by the xTimer parameter. + */ +const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); + * + * Updates a timer to be either an autoreload timer, in which case the timer + * automatically resets itself each time it expires, or a one shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being updated. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the timer's period (see the + * xTimerPeriodInTicks parameter of the xTimerCreate() API function). If + * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + */ +void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); + * + * Returns the period of a timer. + * + * @param xTimer The handle of the timer being queried. + * + * @return The period of the timer in ticks. + */ +TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** +* TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); +* +* Returns the time in ticks at which the timer will expire. If this is less +* than the current tick count then the expiry time has overflowed from the +* current time. +* +* @param xTimer The handle of the timer being queried. +* +* @return If the timer is running then the time in ticks at which the timer +* will next expire is returned. If the timer is not running then the return +* value is undefined. +*/ +TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** @cond */ + +/* + * Functions beyond this part are not part of the public API and are intended + * for use by the kernel only. + */ +BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; +BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +#if( configUSE_TRACE_FACILITY == 1 ) + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; +#endif + +/** @endcond */ + +#ifdef __cplusplus +} +#endif +#endif /* TIMERS_H */ diff --git a/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/FreeRTOSConfig.h b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/FreeRTOSConfig.h new file mode 100644 index 00000000..094f6f08 --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/FreeRTOSConfig.h @@ -0,0 +1,94 @@ +/* + FreeRTOS V10 - Copyright (C) 2021 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS 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. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +#ifndef FREERTOS_CONFIG_RISCV_H +#define FREERTOS_CONFIG_RISCV_H + +// This file is included in the common FreeRTOSConfig.h. + +#include "sdkconfig.h" + +#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0 + +#ifndef __ASSEMBLER__ +#if CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/ets_sys.h" +#endif +#endif // __ASSEMBLER__ + +/* The maximum interrupt priority from which FreeRTOS.org API functions can + be called. Only API functions that end in ...FromISR() can be used within + interrupts. */ +#define configMAX_SYSCALL_INTERRUPT_PRIORITY 0 + +#ifndef configISR_STACK_SIZE +#define configISR_STACK_SIZE (CONFIG_FREERTOS_ISR_STACKSIZE) +#endif + +#endif // FREERTOS_CONFIG_RISCV_H diff --git a/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portbenchmark.h b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portbenchmark.h new file mode 100644 index 00000000..4ce41d3d --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portbenchmark.h @@ -0,0 +1,46 @@ +/******************************************************************************* +// Copyright (c) 2003-2015 Cadence Design Systems, Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +-------------------------------------------------------------------------------- +*/ + +/* + * This utility helps benchmarking interrupt latency and context switches. + * In order to enable it, set configBENCHMARK to 1 in FreeRTOSConfig.h. + * You will also need to download the FreeRTOS_trace patch that contains + * portbenchmark.c and the complete version of portbenchmark.h + */ + +#ifndef PORTBENCHMARK_H +#define PORTBENCHMARK_H + +#if configBENCHMARK + #error "You need to download the FreeRTOS_trace patch that overwrites this file" +#endif + +#define portbenchmarkINTERRUPT_DISABLE() +#define portbenchmarkINTERRUPT_RESTORE(newstate) +#define portbenchmarkIntLatency() +#define portbenchmarkIntWait() +#define portbenchmarkReset() +#define portbenchmarkPrint() + +#endif /* PORTBENCHMARK */ diff --git a/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portmacro.h b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portmacro.h new file mode 100644 index 00000000..9ead3fea --- /dev/null +++ b/tools/sdk/esp32c3/include/freertos/port/riscv/include/freertos/portmacro.h @@ -0,0 +1,314 @@ +/* + * FreeRTOS Kernel V10.2.1 + * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ +#ifndef PORTMACRO_H +#define PORTMACRO_H + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef __ASSEMBLER__ + +#include +#include +#include +#include +#include +#include "esp_timer.h" /* required for FreeRTOS run time stats */ + +#include "sdkconfig.h" +#include "esp_attr.h" +#include "esp_heap_caps.h" +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/soc_memory_layout.h" +#endif +#include "soc/spinlock.h" +#include "soc/interrupt_core0_reg.h" +#include "esp_rom_sys.h" +#include "soc/cpu.h" +#include "esp_system.h" +#include "esp_newlib.h" + +/*----------------------------------------------------------- + * Port specific definitions. + * + * The settings in this file configure FreeRTOS correctly for the + * given hardware and compiler. + * + * These settings should not be altered. + *----------------------------------------------------------- + */ + +/* Type definitions. */ +#define portCHAR uint8_t +#define portFLOAT float +#define portDOUBLE double +#define portLONG int32_t +#define portSHORT int16_t +#define portSTACK_TYPE uint8_t +#define portBASE_TYPE int +// interrupt module will mask interrupt with priority less than threshold +#define RVHAL_EXCM_LEVEL 4 + +typedef portSTACK_TYPE StackType_t; +typedef portBASE_TYPE BaseType_t; +typedef unsigned portBASE_TYPE UBaseType_t; + +#if( configUSE_16_BIT_TICKS == 1 ) + typedef uint16_t TickType_t; + #define portMAX_DELAY ( TickType_t ) 0xffff +#else + typedef uint32_t TickType_t; + #define portMAX_DELAY ( TickType_t ) 0xffffffffUL +#endif +/*------------------------------------------------------*/ + +/* Architecture specifics. */ +#define portSTACK_GROWTH ( -1 ) +#define portTICK_PERIOD_MS ( ( TickType_t ) (1000 / configTICK_RATE_HZ) ) +#define portBYTE_ALIGNMENT 16 +/*-----------------------------------------------------------*/ +#include "portbenchmark.h" + +static inline BaseType_t IRAM_ATTR xPortGetCoreID(void) { + return cpu_hal_get_core_id(); +} + + +static inline bool IRAM_ATTR xPortCanYield(void) +{ + uint32_t threshold = REG_READ(INTERRUPT_CORE0_CPU_INT_THRESH_REG); + /* when enter critical code, freertos will mask threshold to RVHAL_EXCM_LEVEL + * and exit critical code, will recover threshold value (1). so threshold <= 1 + * means not in critical code + */ + return (threshold <= 1); +} + +static inline void uxPortCompareSetExtram(volatile uint32_t *addr, uint32_t compare, uint32_t *set) +{ +#if defined(CONFIG_SPIRAM) + compare_and_set_extram(addr, compare, set); +#endif +} + +static inline void __attribute__((always_inline)) uxPortCompareSet(volatile uint32_t *addr, uint32_t compare, uint32_t *set) { + compare_and_set_native(addr, compare, set); +} + +#define portCRITICAL_NESTING_IN_TCB 0 + +/* + * Send an interrupt to another core in order to make the task running + * on it yield for a higher-priority task. + */ +void vPortYieldOtherCore( BaseType_t coreid); + +/* + Callback to set a watchpoint on the end of the stack. Called every context switch to change the stack + watchpoint around. + */ +void vPortSetStackWatchpoint( void* pxStackStart ); + +/* + * Returns true if the current core is in ISR context; low prio ISR, med prio ISR or timer tick ISR. High prio ISRs + * aren't detected here, but they normally cannot call C code, so that should not be an issue anyway. + */ +BaseType_t xPortInIsrContext(void); + +/* + * This function will be called in High prio ISRs. Returns true if the current core was in ISR context + * before calling into high prio ISR context. + */ +BaseType_t xPortInterruptedFromISRContext(void); + +/* "mux" data structure (spinlock) */ +typedef struct { + /* owner field values: + * 0 - Uninitialized (invalid) + * portMUX_FREE_VAL - Mux is free, can be locked by either CPU + * CORE_ID_REGVAL_PRO / CORE_ID_REGVAL_APP - Mux is locked to the particular core + * + * + * Any value other than portMUX_FREE_VAL, CORE_ID_REGVAL_PRO, CORE_ID_REGVAL_APP indicates corruption + */ + uint32_t owner; + /* count field: + * If mux is unlocked, count should be zero. + * If mux is locked, count is non-zero & represents the number of recursive locks on the mux. + */ + uint32_t count; +#ifdef CONFIG_FREERTOS_PORTMUX_DEBUG + const char *lastLockedFn; + int lastLockedLine; +#endif +} portMUX_TYPE; + +#define portMUX_FREE_VAL SPINLOCK_FREE + +/* Special constants for vPortCPUAcquireMutexTimeout() */ +#define portMUX_NO_TIMEOUT SPINLOCK_WAIT_FOREVER /* When passed for 'timeout_cycles', spin forever if necessary */ +#define portMUX_TRY_LOCK SPINLOCK_NO_WAIT /* Try to acquire the spinlock a single time only */ + +// Keep this in sync with the portMUX_TYPE struct definition please. +#ifndef CONFIG_FREERTOS_PORTMUX_DEBUG +#define portMUX_INITIALIZER_UNLOCKED { \ + .owner = portMUX_FREE_VAL, \ + .count = 0, \ + } +#else +#define portMUX_INITIALIZER_UNLOCKED { \ + .owner = portMUX_FREE_VAL, \ + .count = 0, \ + .lastLockedFn = "(never locked)", \ + .lastLockedLine = -1 \ + } +#endif + +/* Scheduler utilities. */ +extern void vPortYield( void ); +extern void vPortYieldFromISR( void ); + +#define portYIELD() vPortYield() +#define portYIELD_FROM_ISR() vPortYieldFromISR() + +/* Yielding within an API call (when interrupts are off), means the yield should be delayed + until interrupts are re-enabled. + To do this, we use the "cross-core" interrupt as a trigger to yield on this core when interrupts are re-enabled.This + is the same interrupt & code path which is used to trigger a yield between CPUs, although in this case the yield is + happening on the same CPU. +*/ +#define portYIELD_WITHIN_API() portYIELD() +/*-----------------------------------------------------------*/ + +/* Critical section management. */ +extern int vPortSetInterruptMask(void); +extern void vPortClearInterruptMask( int ); + +void vPortCPUInitializeMutex(portMUX_TYPE *mux); +void vPortCPUAcquireMutex(portMUX_TYPE *mux); +bool vPortCPUAcquireMutexTimeout(portMUX_TYPE *mux, int timeout_cycles); +void vPortCPUReleaseMutex(portMUX_TYPE *mux); + +extern void vPortEnterCritical( void ); +extern void vPortExitCritical( void ); + +#define portDISABLE_INTERRUPTS() portSET_INTERRUPT_MASK_FROM_ISR() +#define portENABLE_INTERRUPTS() portCLEAR_INTERRUPT_MASK_FROM_ISR(1) + +#define portENTER_CRITICAL(mux) {(void)mux; vPortEnterCritical();} +#define portEXIT_CRITICAL(mux) {(void)mux; vPortExitCritical();} + +#define portENTER_CRITICAL_ISR(mux) portENTER_CRITICAL(mux) +#define portEXIT_CRITICAL_ISR(mux) portEXIT_CRITICAL(mux) + +#define portENTER_CRITICAL_SAFE(mux) do { \ + if (xPortInIsrContext()) { \ + portENTER_CRITICAL_ISR(mux); \ + } else { \ + portENTER_CRITICAL(mux); \ + } \ + } while(0) + +#define portEXIT_CRITICAL_SAFE(mux) do { \ + if (xPortInIsrContext()) { \ + portEXIT_CRITICAL_ISR(mux); \ + } else { \ + portEXIT_CRITICAL(mux); \ + } \ + } while(0) + +/*------------------------------------------------------------*/ +#define portSET_INTERRUPT_MASK_FROM_ISR() vPortSetInterruptMask() +#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) vPortClearInterruptMask( uxSavedStatusValue ) +#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) vPortYield() + +// Cleaner solution allows nested interrupts disabling and restoring via local registers or stack. +// They can be called from interrupts too. +static inline unsigned portENTER_CRITICAL_NESTED(void) { + unsigned state = portSET_INTERRUPT_MASK_FROM_ISR(); + return state; +} + +#define portEXIT_CRITICAL_NESTED(state) do { portCLEAR_INTERRUPT_MASK_FROM_ISR( state );} while(0); +/*-----------------------------------------------------------*/ + +//Because the ROM routines don't necessarily handle a stack in external RAM correctly, we force +//the stack memory to always be internal. +#define portTcbMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) +#define portStackMemoryCaps (MALLOC_CAP_INTERNAL|MALLOC_CAP_8BIT) + +#define pvPortMallocTcbMem(size) pvPortMalloc(size) +#define pvPortMallocStackMem(size) pvPortMalloc(size) + +/* Fine resolution time */ +#define portGET_RUN_TIME_COUNTER_VALUE() 0 +#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() + +#ifdef CONFIG_FREERTOS_RUN_TIME_STATS_USING_ESP_TIMER +/* Coarse resolution time (us) */ +#define portALT_GET_RUN_TIME_COUNTER_VALUE(x) do {x = (uint32_t)esp_timer_get_time();} while(0) +#endif + +extern void esp_vApplicationIdleHook( void ); +extern void esp_vApplicationTickHook( void ); + +#ifndef CONFIG_FREERTOS_LEGACY_HOOKS +#define vApplicationIdleHook esp_vApplicationIdleHook +#define vApplicationTickHook esp_vApplicationTickHook +#endif /* !CONFIG_FREERTOS_LEGACY_HOOKS */ + +/* Task function macros as described on the FreeRTOS.org WEB site. */ +#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) +#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) + +void vApplicationSleep( TickType_t xExpectedIdleTime ); +#define portSUPPRESS_TICKS_AND_SLEEP( idleTime ) vApplicationSleep( idleTime ) + +#define portNOP() __asm volatile ( " nop " ) + +#define portVALID_TCB_MEM(ptr) esp_ptr_byte_accessible(ptr) +#define portVALID_STACK_MEM(ptr) esp_ptr_byte_accessible(ptr) + +/* Get tick rate per second */ +uint32_t xPortGetTickRateHz(void); + +// configASSERT_2 if requested +#if configASSERT_2 +#include +void exit(int); +#define configASSERT( x ) if (!(x)) { porttracePrint(-1); printf("\nAssertion failed in %s:%d\n", __FILE__, __LINE__); exit(-1); } +#endif + + +#endif //__ASSEMBLER__ + +#ifdef __cplusplus +} +#endif + +#endif /* PORTMACRO_H */ diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal.h new file mode 100644 index 00000000..9993f9e8 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal.h @@ -0,0 +1,119 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for ADC (esp32s2 specific part) + +#pragma once + +#include "hal/adc_ll.h" +#include "hal/adc_types.h" + +#include_next "hal/adc_hal.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*--------------------------------------------------------------- + Digital controller setting +---------------------------------------------------------------*/ +/** + * Digital controller deinitialization. + */ +void adc_hal_digi_deinit(void); + +/** + * Setting the digital controller. + * + * @param cfg Pointer to digital controller paramter. + */ +void adc_hal_digi_controller_config(const adc_digi_config_t *cfg); + +/** + * Reset adc digital controller filter. + * + * @param filter_idx ADC filter unit. + */ +#define adc_hal_digi_filter_reset(filter_idx) adc_ll_digi_filter_reset(filter_idx) + +/** + * Set adc digital controller filter factor. + * + * @param filter_idx ADC filter unit. + * @param filter Filter config. Expression: filter_data = (k-1)/k * last_data + new_data / k. Set values: (2, 4, 8, 16, 64). + */ +void adc_hal_digi_filter_set_factor(adc_digi_filter_idx_t filter_idx, adc_digi_filter_t *filter); + +/** + * Get adc digital controller filter factor. + * + * @param filter_idx ADC filter unit. + * @param factor Expression: filter_data = (k-1)/k * last_data + new_data / k. Set values: (2, 4, 8, 16, 64). + */ +void adc_hal_digi_filter_get_factor(adc_digi_filter_idx_t filter_idx, adc_digi_filter_t *filter); + +/** + * Enable/disable adc digital controller filter. + * Filtering the ADC data to obtain smooth data at higher sampling rates. + * + * @note The filter will filter all the enabled channel data of the each ADC unit at the same time. + * @param filter_idx ADC filter unit. + * @param enable True to enable the filter, otherwise disable. + */ +void adc_hal_digi_filter_enable(adc_digi_filter_idx_t filter_idx, bool enable); + +/** + * Config monitor of adc digital controller. + * + * @note If the channel info is not supported, the monitor function will not be enabled. + * @param mon_idx ADC monitor index. + * @param config Refer to `adc_digi_monitor_t`. + */ +void adc_hal_digi_monitor_config(adc_digi_monitor_idx_t mon_idx, adc_digi_monitor_t *config); + +/** + * Enable/disable monitor of adc digital controller. + * + * @note The monitor will monitor all the enabled channel data of the each ADC unit at the same time. + * @param mon_idx ADC monitor index. + * @param enable True to enable the monitor, otherwise disable. + */ +void adc_hal_digi_monitor_enable(adc_digi_monitor_idx_t mon_idx, bool enable); + +/*--------------------------------------------------------------- + Common setting +---------------------------------------------------------------*/ + +/** + * Config ADC2 module arbiter. + * The arbiter is to improve the use efficiency of ADC2. After the control right is robbed by the high priority, + * the low priority controller will read the invalid ADC2 data, and the validity of the data can be judged by the flag bit in the data. + * + * @note Only ADC2 support arbiter. + * @note The arbiter's working clock is APB_CLK. When the APB_CLK clock drops below 8 MHz, the arbiter must be in shield mode. + * @note Default priority: Wi-Fi > RTC > Digital; + * + * @param config Refer to `adc_arbiter_t`. + */ +void adc_hal_arbiter_config(adc_arbiter_t *config); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal_conf.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal_conf.h new file mode 100644 index 00000000..02e43632 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_hal_conf.h @@ -0,0 +1,31 @@ +// Copyright 2020 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. + +#pragma once + +#define SOC_ADC1_DATA_INVERT_DEFAULT (0) +#define SOC_ADC2_DATA_INVERT_DEFAULT (0) + +#define SOC_ADC_DIGI_DATA_INVERT_DEFAULT(PERIPH_NUM) (0) + +#define SOC_ADC_FSM_RSTB_WAIT_DEFAULT (8) +#define SOC_ADC_FSM_START_WAIT_DEFAULT (5) +#define SOC_ADC_FSM_STANDBY_WAIT_DEFAULT (100) +#define ADC_FSM_SAMPLE_CYCLE_DEFAULT (2) + +#define SOC_ADC_PWDET_CCT_DEFAULT (4) + +#define SOC_ADC_SAR_CLK_DIV_DEFAULT(PERIPH_NUM) ((PERIPH_NUM==0)? 2 : 1) + +#define SOC_ADC_DIGI_SAR_CLK_DIV_DEFAULT (1) diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_ll.h new file mode 100644 index 00000000..a2fd21f2 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/adc_ll.h @@ -0,0 +1,801 @@ +// Copyright 2015-2020 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. +#pragma once + +#include +#include +#include "regi2c_ctrl.h" +#include "esp_attr.h" + +#include "soc/adc_periph.h" +#include "hal/adc_types.h" +#include "soc/apb_saradc_struct.h" +#include "soc/apb_saradc_reg.h" +#include "soc/rtc_cntl_struct.h" +#include "soc/rtc_cntl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ADC_LL_CLKM_DIV_NUM_DEFAULT 15 +#define ADC_LL_CLKM_DIV_B_DEFAULT 1 +#define ADC_LL_CLKM_DIV_A_DEFAULT 0 + +typedef enum { + ADC_NUM_1 = 0, /*!< SAR ADC 1 */ + ADC_NUM_2 = 1, /*!< SAR ADC 2 */ + ADC_NUM_MAX, +} adc_ll_num_t; + +typedef enum { + ADC_POWER_BY_FSM, /*!< ADC XPD controled by FSM. Used for polling mode */ + ADC_POWER_SW_ON, /*!< ADC XPD controled by SW. power on. Used for DMA mode */ + ADC_POWER_SW_OFF, /*!< ADC XPD controled by SW. power off. */ + ADC_POWER_MAX, /*!< For parameter check. */ +} adc_ll_power_t; + +typedef enum { + ADC_RTC_DATA_OK = 0, + ADC_RTC_CTRL_UNSELECTED = 1, + ADC_RTC_CTRL_BREAK = 2, + ADC_RTC_DATA_FAIL = -1, +} adc_ll_rtc_raw_data_t; + +//These values should be set according to the HW +typedef enum { + ADC_LL_INTR_THRES1_LOW = BIT(26), + ADC_LL_INTR_THRES0_LOW = BIT(27), + ADC_LL_INTR_THRES1_HIGH = BIT(28), + ADC_LL_INTR_THRES0_HIGH = BIT(29), + ADC_LL_INTR_ADC2_DONE = BIT(30), + ADC_LL_INTR_ADC1_DONE = BIT(31), +} adc_ll_intr_t; +FLAG_ATTR(adc_ll_intr_t) + +/** + * @brief ADC controller type selection. + * + * @note For ADC2, use the force option with care. The system power consumption detection will use ADC2. + * If it is forced to switch to another controller, it may cause the system to obtain incorrect values. + * @note Normally, there is no need to switch the controller manually. + */ +typedef enum { + ADC_CTRL_RTC = 0, /*!> offset)); // Clear old data + tab |= ((uint32_t)(pattern.val & 0x3F) << 18) >> offset; // Fill in the new data + APB_SARADC.sar_patt_tab[index].sar_patt_tab1 = tab; // Write back +} + +/** + * Reset the pattern table pointer, then take the measurement rule from table header in next measurement. + * + * @param adc_n ADC unit. + */ +static inline void adc_ll_digi_clear_pattern_table(adc_ll_num_t adc_n) +{ + APB_SARADC.ctrl.sar_patt_p_clear = 1; + APB_SARADC.ctrl.sar_patt_p_clear = 0; +} + +/** + * Sets the number of cycles required for the conversion to complete and wait for the arbiter to stabilize. + * + * @note Only ADC2 have arbiter function. + * @param cycle range: 0 ~ 4. + */ +static inline void adc_ll_digi_set_arbiter_stable_cycle(uint32_t cycle) +{ + APB_SARADC.ctrl.wait_arb_cycle = cycle; +} + +/** + * ADC Digital controller output data invert or not. + * + * @param adc_n ADC unit. + * @param inv_en data invert or not. + */ +static inline void adc_ll_digi_output_invert(adc_ll_num_t adc_n, bool inv_en) +{ + if (adc_n == ADC_NUM_1) { + APB_SARADC.ctrl2.sar1_inv = inv_en; // Enable / Disable ADC data invert + } else { // adc_n == ADC_NUM_2 + APB_SARADC.ctrl2.sar2_inv = inv_en; // Enable / Disable ADC data invert + } +} + +/** + * Set the interval clock cycle for the digital controller to trigger the measurement. + * Expression: `trigger_meas_freq` = `controller_clk` / 2 / interval. + * + * @note The trigger interval should not be smaller than the sampling time of the SAR ADC. + * @param cycle The clock cycle (trigger interval) of the measurement. Range: 30 ~ 4095. + */ +static inline void adc_ll_digi_set_trigger_interval(uint32_t cycle) +{ + APB_SARADC.ctrl2.timer_target = cycle; +} + +/** + * Enable digital controller timer to trigger the measurement. + */ +static inline void adc_ll_digi_trigger_enable(void) +{ + APB_SARADC.ctrl2.timer_en = 1; +} + +/** + * Disable digital controller timer to trigger the measurement. + */ +static inline void adc_ll_digi_trigger_disable(void) +{ + APB_SARADC.ctrl2.timer_en = 0; +} + +/** + * Set ADC digital controller clock division factor. The clock divided from `APLL` or `APB` clock. + * Expression: controller_clk = APLL/APB * (div_num + div_b / div_a). + * + * @param div_num Division factor. Range: 1 ~ 255. + * @param div_b Division factor. Range: 1 ~ 63. + * @param div_a Division factor. Range: 0 ~ 63. + */ +static inline void adc_ll_digi_controller_clk_div(uint32_t div_num, uint32_t div_b, uint32_t div_a) +{ + APB_SARADC.apb_adc_clkm_conf.clkm_div_num = div_num; + APB_SARADC.apb_adc_clkm_conf.clkm_div_b = div_b; + APB_SARADC.apb_adc_clkm_conf.clkm_div_a = div_a; +} + +/** + * Enable clock and select clock source for ADC digital controller. + * + * @param use_apll true: use APLL clock; false: use APB clock. + */ +static inline void adc_ll_digi_controller_clk_enable(bool use_apll) +{ + if (use_apll) { + APB_SARADC.apb_adc_clkm_conf.clk_sel = 1; // APLL clock + } else { + APB_SARADC.apb_adc_clkm_conf.clk_sel = 2; // APB clock + } + APB_SARADC.ctrl.sar_clk_gated = 1; +} + +/** + * Disable clock for ADC digital controller. + */ +static inline void adc_ll_digi_controller_clk_disable(void) +{ + APB_SARADC.ctrl.sar_clk_gated = 0; +} + +/** + * Reset adc digital controller filter. + * + * @param adc_n ADC unit. + */ +static inline void adc_ll_digi_filter_reset(adc_ll_num_t adc_n) +{ + APB_SARADC.filter_ctrl0.filter_reset = 1; +} + +/** + * Set adc digital controller filter factor. + * + * @note If the channel info is not supported, the filter function will not be enabled. + * @param idx ADC filter unit. + * @param filter Filter config. Expression: filter_data = (k-1)/k * last_data + new_data / k. Set values: (2, 4, 8, 16, 64). + */ +static inline void adc_ll_digi_filter_set_factor(adc_digi_filter_idx_t idx, adc_digi_filter_t *filter) +{ + if (idx == ADC_DIGI_FILTER_IDX0) { + APB_SARADC.filter_ctrl0.filter_channel0 = (filter->adc_unit << 3) | (filter->channel & 0x7); + APB_SARADC.filter_ctrl1.filter_factor0 = filter->mode; + } else if (idx == ADC_DIGI_FILTER_IDX1) { + APB_SARADC.filter_ctrl0.filter_channel1 = (filter->adc_unit << 3) | (filter->channel & 0x7); + APB_SARADC.filter_ctrl1.filter_factor1 = filter->mode; + } +} + +/** + * Get adc digital controller filter factor. + * + * @param adc_n ADC unit. + * @param factor Expression: filter_data = (k-1)/k * last_data + new_data / k. Set values: (2, 4, 8, 16, 64). + */ +static inline void adc_ll_digi_filter_get_factor(adc_digi_filter_idx_t idx, adc_digi_filter_t *filter) +{ + if (idx == ADC_DIGI_FILTER_IDX0) { + filter->adc_unit = (APB_SARADC.filter_ctrl0.filter_channel0 >> 3) & 0x1; + filter->channel = APB_SARADC.filter_ctrl0.filter_channel0 & 0x7; + filter->mode = APB_SARADC.filter_ctrl1.filter_factor0; + } else if (idx == ADC_DIGI_FILTER_IDX1) { + filter->adc_unit = (APB_SARADC.filter_ctrl0.filter_channel1 >> 3) & 0x1; + filter->channel = APB_SARADC.filter_ctrl0.filter_channel1 & 0x7; + filter->mode = APB_SARADC.filter_ctrl1.filter_factor1; + } +} + +/** + * Disable adc digital controller filter. + * Filtering the ADC data to obtain smooth data at higher sampling rates. + * + * @note If the channel info is not supported, the filter function will not be enabled. + * @param adc_n ADC unit. + */ +static inline void adc_ll_digi_filter_disable(adc_digi_filter_idx_t idx) +{ + if (idx == ADC_DIGI_FILTER_IDX0) { + APB_SARADC.filter_ctrl0.filter_channel0 = 0xF; + APB_SARADC.filter_ctrl1.filter_factor0 = 0; + } else if (idx == ADC_DIGI_FILTER_IDX1) { + APB_SARADC.filter_ctrl0.filter_channel1 = 0xF; + APB_SARADC.filter_ctrl1.filter_factor1 = 0; + } +} + +/** + * Set monitor mode of adc digital controller. + * + * @note If the channel info is not supported, the monitor function will not be enabled. + * @param adc_n ADC unit. + * @param is_larger true: If ADC_OUT > threshold, Generates monitor interrupt. + * false: If ADC_OUT < threshold, Generates monitor interrupt. + */ +static inline void adc_ll_digi_monitor_set_mode(adc_digi_monitor_idx_t idx, adc_digi_monitor_t *cfg) +{ + if (idx == ADC_DIGI_MONITOR_IDX0) { + APB_SARADC.thres0_ctrl.thres0_channel = (cfg->adc_unit << 3) | (cfg->channel & 0x7); + APB_SARADC.thres0_ctrl.thres0_high = cfg->h_threshold; + APB_SARADC.thres0_ctrl.thres0_low = cfg->l_threshold; + } else { // ADC_DIGI_MONITOR_IDX1 + APB_SARADC.thres1_ctrl.thres1_channel = (cfg->adc_unit << 3) | (cfg->channel & 0x7); + APB_SARADC.thres1_ctrl.thres1_high = cfg->h_threshold; + APB_SARADC.thres1_ctrl.thres1_low = cfg->l_threshold; + } +} + +/** + * Enable/disable monitor of adc digital controller. + * + * @note If the channel info is not supported, the monitor function will not be enabled. + * @param adc_n ADC unit. + */ +static inline void adc_ll_digi_monitor_disable(adc_digi_monitor_idx_t idx) +{ + if (idx == ADC_DIGI_MONITOR_IDX0) { + APB_SARADC.thres0_ctrl.thres0_channel = 0xF; + } else { // ADC_DIGI_MONITOR_IDX1 + APB_SARADC.thres1_ctrl.thres1_channel = 0xF; + } +} + +/** + * Set DMA eof num of adc digital controller. + * If the number of measurements reaches `dma_eof_num`, then `dma_in_suc_eof` signal is generated. + * + * @param num eof num of DMA. + */ +static inline void adc_ll_digi_dma_set_eof_num(uint32_t num) +{ + APB_SARADC.dma_conf.apb_adc_eof_num = num; +} + +/** + * Enable output data to DMA from adc digital controller. + */ +static inline void adc_ll_digi_dma_enable(void) +{ + APB_SARADC.dma_conf.apb_adc_trans = 1; +} + +/** + * Disable output data to DMA from adc digital controller. + */ +static inline void adc_ll_digi_dma_disable(void) +{ + APB_SARADC.dma_conf.apb_adc_trans = 0; +} + +/** + * Reset adc digital controller. + */ +static inline void adc_ll_digi_reset(void) +{ + APB_SARADC.dma_conf.apb_adc_reset_fsm = 1; + APB_SARADC.dma_conf.apb_adc_reset_fsm = 0; +} + +/*--------------------------------------------------------------- + PWDET(Power detect) controller setting +---------------------------------------------------------------*/ +/** + * Set adc cct for PWDET controller. + * + * @note Capacitor tuning of the PA power monitor. cct set to the same value with PHY. + * @param cct Range: 0 ~ 7. + */ +static inline void adc_ll_pwdet_set_cct(uint32_t cct) +{ + /* Capacitor tuning of the PA power monitor. cct set to the same value with PHY. */ + RTCCNTL.sensor_ctrl.sar2_pwdet_cct = cct; +} + +/** + * Get adc cct for PWDET controller. + * + * @note Capacitor tuning of the PA power monitor. cct set to the same value with PHY. + * @return cct Range: 0 ~ 7. + */ +static inline uint32_t adc_ll_pwdet_get_cct(void) +{ + /* Capacitor tuning of the PA power monitor. cct set to the same value with PHY. */ + return RTCCNTL.sensor_ctrl.sar2_pwdet_cct; +} + +/** + * Analyze whether the obtained raw data is correct. + * ADC2 can use arbiter. The arbitration result is stored in the channel information of the returned data. + * + * @param adc_n ADC unit. + * @param raw_data ADC raw data input (convert value). + * @return + * - 0: The data is correct to use. + * - -1: The data is invalid. + */ +static inline adc_ll_rtc_raw_data_t adc_ll_analysis_raw_data(adc_ll_num_t adc_n, int raw_data) +{ + if (adc_n == ADC_NUM_1) { + return ADC_RTC_DATA_OK; + } + + //The raw data API returns value without channel information. Read value directly from the register + if (((APB_SARADC.apb_saradc2_data_status.adc2_data >> 13) & 0xF) > 9) { + return ADC_RTC_DATA_FAIL; + } + + return ADC_RTC_DATA_OK; +} + +/*--------------------------------------------------------------- + Common setting +---------------------------------------------------------------*/ +/** + * Set ADC module power management. + * + * @param manage Set ADC power status. + */ +static inline void adc_ll_set_power_manage(adc_ll_power_t manage) +{ + // /* Bit1 0:Fsm 1: SW mode + // Bit0 0:SW mode power down 1: SW mode power on */ + if (manage == ADC_POWER_SW_ON) { + APB_SARADC.ctrl.sar_clk_gated = 1; + APB_SARADC.ctrl.xpd_sar_force = 3; + } else if (manage == ADC_POWER_BY_FSM) { + APB_SARADC.ctrl.sar_clk_gated = 1; + APB_SARADC.ctrl.xpd_sar_force = 0; + } else if (manage == ADC_POWER_SW_OFF) { + APB_SARADC.ctrl.xpd_sar_force = 2; + APB_SARADC.ctrl.sar_clk_gated = 0; + } +} + +/** + * Get ADC module power management. + * + * @return + * - ADC power status. + */ +static inline adc_ll_power_t adc_ll_get_power_manage(void) +{ + /* Bit1 0:Fsm 1: SW mode + Bit0 0:SW mode power down 1: SW mode power on */ + adc_ll_power_t manage; + if (APB_SARADC.ctrl.xpd_sar_force == 3) { + manage = ADC_POWER_SW_ON; + } else if (APB_SARADC.ctrl.xpd_sar_force == 2) { + manage = ADC_POWER_SW_OFF; + } else { + manage = ADC_POWER_BY_FSM; + } + return manage; +} + +/** + * Set ADC2 module arbiter work mode. + * The arbiter is to improve the use efficiency of ADC2. After the control right is robbed by the high priority, + * the low priority controller will read the invalid ADC data, and the validity of the data can be judged by the flag bit in the data. + * + * @note Only ADC2 support arbiter. + * @note The arbiter's working clock is APB_CLK. When the APB_CLK clock drops below 8 MHz, the arbiter must be in shield mode. + * + * @param mode Refer to `adc_arbiter_mode_t`. + */ +static inline void adc_ll_set_arbiter_work_mode(adc_arbiter_mode_t mode) +{ + if (mode == ADC_ARB_MODE_FIX) { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_grant_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_fix_priority = 1; + } else if (mode == ADC_ARB_MODE_LOOP) { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_grant_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_fix_priority = 0; + } else { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_grant_force = 1; // Shield arbiter. + } +} + +/** + * Set ADC2 module controller priority in arbiter. + * The arbiter is to improve the use efficiency of ADC2. After the control right is robbed by the high priority, + * the low priority controller will read the invalid ADC data, and the validity of the data can be judged by the flag bit in the data. + * + * @note Only ADC2 support arbiter. + * @note The arbiter's working clock is APB_CLK. When the APB_CLK clock drops below 8 MHz, the arbiter must be in shield mode. + * @note Default priority: Wi-Fi(2) > RTC(1) > Digital(0); + * + * @param pri_rtc RTC controller priority. Range: 0 ~ 2. + * @param pri_dig Digital controller priority. Range: 0 ~ 2. + * @param pri_pwdet Wi-Fi controller priority. Range: 0 ~ 2. + */ +static inline void adc_ll_set_arbiter_priority(uint8_t pri_rtc, uint8_t pri_dig, uint8_t pri_pwdet) +{ + if (pri_rtc != pri_dig && pri_rtc != pri_pwdet && pri_dig != pri_pwdet) { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_rtc_priority = pri_rtc; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_apb_priority = pri_dig; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_wifi_priority = pri_pwdet; + } + /* Should select highest priority controller. */ + if (pri_rtc > pri_dig) { + if (pri_rtc > pri_pwdet) { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_apb_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_rtc_force = 1; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_wifi_force = 0; + } else { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_apb_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_rtc_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_wifi_force = 1; + } + } else { + if (pri_dig > pri_pwdet) { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_apb_force = 1; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_rtc_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_wifi_force = 0; + } else { + APB_SARADC.apb_adc_arb_ctrl.adc_arb_apb_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_rtc_force = 0; + APB_SARADC.apb_adc_arb_ctrl.adc_arb_wifi_force = 1; + } + } +} + +/* ADC calibration code. */ +/** + * @brief Set common calibration configuration. Should be shared with other parts (PWDET). + */ +static inline void adc_ll_calibration_init(adc_ll_num_t adc_n) +{ + if (adc_n == ADC_NUM_1) { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_DREF_ADDR, 1); + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_DREF_ADDR, 1); + } +} + +/** + * Configure the registers for ADC calibration. You need to call the ``adc_ll_calibration_finish`` interface to resume after calibration. + * + * @note Different ADC units and different attenuation options use different calibration data (initial data). + * + * @param adc_n ADC index number. + * @param channel adc channel number. + * @param internal_gnd true: Disconnect from the IO port and use the internal GND as the calibration voltage. + * false: Use IO external voltage as calibration voltage. + */ +static inline void adc_ll_calibration_prepare(adc_ll_num_t adc_n, adc_channel_t channel, bool internal_gnd) +{ + /* Enable/disable internal connect GND (for calibration). */ + if (adc_n == ADC_NUM_1) { + if (internal_gnd) { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_ENCAL_GND_ADDR, 1); + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_ENCAL_GND_ADDR, 0); + } + } else { + if (internal_gnd) { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_ENCAL_GND_ADDR, 1); + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_ENCAL_GND_ADDR, 0); + } + } +} + +/** + * Resume register status after calibration. + * + * @param adc_n ADC index number. + */ +static inline void adc_ll_calibration_finish(adc_ll_num_t adc_n) +{ + if (adc_n == ADC_NUM_1) { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_ENCAL_GND_ADDR, 0); + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_ENCAL_GND_ADDR, 0); + } +} + +/** + * Set the calibration result to ADC. + * + * @note Different ADC units and different attenuation options use different calibration data (initial data). + * + * @param adc_n ADC index number. + */ +static inline void adc_ll_set_calibration_param(adc_ll_num_t adc_n, uint32_t param) +{ + uint8_t msb = param >> 8; + uint8_t lsb = param & 0xFF; + if (adc_n == ADC_NUM_1) { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_INITIAL_CODE_HIGH_ADDR, msb); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR1_INITIAL_CODE_LOW_ADDR, lsb); + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_INITIAL_CODE_HIGH_ADDR, msb); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SAR2_INITIAL_CODE_LOW_ADDR, lsb); + } +} +/* Temp code end. */ + +/** + * Output ADCn inter reference voltage to ADC2 channels. + * + * This function routes the internal reference voltage of ADCn to one of + * ADC1's channels. This reference voltage can then be manually measured + * for calibration purposes. + * + * @param[in] adc ADC unit select + * @param[in] channel ADC1 channel number + * @param[in] en Enable/disable the reference voltage output + */ +static inline void adc_ll_vref_output(adc_ll_num_t adc, adc_channel_t channel, bool en) +{ + if (en) { + REG_SET_FIELD(RTC_CNTL_SENSOR_CTRL_REG, RTC_CNTL_FORCE_XPD_SAR, 3); + SET_PERI_REG_MASK(RTC_CNTL_REG, RTC_CNTL_REGULATOR_FORCE_PU); + + REG_SET_FIELD(APB_SARADC_APB_ADC_CLKM_CONF_REG, APB_SARADC_CLK_SEL, 2); + SET_PERI_REG_MASK(APB_SARADC_APB_ADC_CLKM_CONF_REG, APB_SARADC_CLK_EN); + SET_PERI_REG_MASK(APB_SARADC_APB_ADC_ARB_CTRL_REG, APB_SARADC_ADC_ARB_GRANT_FORCE); + SET_PERI_REG_MASK(APB_SARADC_APB_ADC_ARB_CTRL_REG, APB_SARADC_ADC_ARB_APB_FORCE); + APB_SARADC.sar_patt_tab[0].sar_patt_tab1 = 0xFFFFFF; + APB_SARADC.sar_patt_tab[1].sar_patt_tab1 = 0xFFFFFF; + APB_SARADC.onetime_sample.adc1_onetime_sample = 1; + APB_SARADC.onetime_sample.onetime_channel = channel; + SET_PERI_REG_MASK(RTC_CNTL_ANA_CONF_REG, RTC_CNTL_SAR_I2C_PU); + if (adc == ADC_NUM_1) { + /* Config test mux to route v_ref to ADC1 Channels */ + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC1_ENCAL_REF_ADDR, 1); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_DTEST_RTC_ADDR, 1); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_ENT_TSENS_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_ENT_RTC_ADDR, 1); + } else { + /* Config test mux to route v_ref to ADC2 Channels */ + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC2_ENCAL_REF_ADDR, 1); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_DTEST_RTC_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_ENT_TSENS_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_ENT_RTC_ADDR, 0); + } + } else { + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC2_ENCAL_REF_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC1_ENCAL_REF_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_DTEST_RTC_ADDR, 0); + REGI2C_WRITE_MASK(I2C_SAR_ADC, ADC_SARADC_ENT_RTC_ADDR, 0); + APB_SARADC.onetime_sample.adc1_onetime_sample = 0; + APB_SARADC.onetime_sample.onetime_channel = 0xf; + REG_SET_FIELD(RTC_CNTL_SENSOR_CTRL_REG, RTC_CNTL_FORCE_XPD_SAR, 0); + REG_SET_FIELD(APB_SARADC_APB_ADC_CLKM_CONF_REG, APB_SARADC_CLK_SEL, 0); + CLEAR_PERI_REG_MASK(APB_SARADC_APB_ADC_CLKM_CONF_REG, APB_SARADC_CLK_EN); + CLEAR_PERI_REG_MASK(APB_SARADC_APB_ADC_ARB_CTRL_REG, APB_SARADC_ADC_ARB_GRANT_FORCE); + CLEAR_PERI_REG_MASK(APB_SARADC_APB_ADC_ARB_CTRL_REG, APB_SARADC_ADC_ARB_APB_FORCE); + } +} + +/*--------------------------------------------------------------- + Single Read +---------------------------------------------------------------*/ +/** + * Trigger single read + * + * @param val Usage: set to 1 to start the ADC conversion. The step signal should at least keep 3 ADC digital controller clock cycle, + * otherwise the step signal may not be captured by the ADC digital controller when its frequency is slow. + * This hardware limitation will be removed in future versions. + */ +static inline void adc_ll_onetime_start(bool val) +{ + APB_SARADC.onetime_sample.onetime_start = val; +} + +static inline void adc_ll_onetime_set_channel(adc_ll_num_t unit, adc_channel_t channel) +{ + APB_SARADC.onetime_sample.onetime_channel = ((unit << 3) | channel); +} + +static inline void adc_ll_onetime_set_atten(adc_atten_t atten) +{ + APB_SARADC.onetime_sample.onetime_atten = atten; +} + +static inline void adc_ll_intr_enable(adc_ll_intr_t mask) +{ + APB_SARADC.int_ena.val |= mask; +} + +static inline void adc_ll_intr_disable(adc_ll_intr_t mask) +{ + APB_SARADC.int_ena.val &= ~mask; +} + +static inline void adc_ll_intr_clear(adc_ll_intr_t mask) +{ + APB_SARADC.int_clr.val |= mask; +} + +static inline bool adc_ll_intr_get_raw(adc_ll_intr_t mask) +{ + return (APB_SARADC.int_raw.val & mask); +} + +static inline bool adc_ll_intr_get_status(adc_ll_intr_t mask) +{ + return (APB_SARADC.int_st.val & mask); +} + +static inline void adc_ll_onetime_sample_enable(adc_ll_num_t adc_n, bool enable) +{ + if (adc_n == ADC_NUM_1) { + APB_SARADC.onetime_sample.adc1_onetime_sample = enable; + } else { + APB_SARADC.onetime_sample.adc2_onetime_sample = enable; + } +} + +static inline uint32_t adc_ll_adc1_read(void) +{ + //On ESP32C3, valid data width is 12-bit + return (APB_SARADC.apb_saradc1_data_status.adc1_data & 0xfff); +} + +static inline uint32_t adc_ll_adc2_read(void) +{ + //On ESP32C3, valid data width is 12-bit + return (APB_SARADC.apb_saradc2_data_status.adc2_data & 0xfff); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/aes_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/aes_ll.h new file mode 100644 index 00000000..0eb7fabc --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/aes_ll.h @@ -0,0 +1,235 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include "soc/hwcrypto_reg.h" +#include "hal/aes_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief State of AES accelerator, busy, idle or done + * + */ +typedef enum { + ESP_AES_STATE_IDLE = 0, /* AES accelerator is idle */ + ESP_AES_STATE_BUSY, /* Transform in progress */ + ESP_AES_STATE_DONE, /* Transform completed */ +} esp_aes_state_t; + + +/** + * @brief Write the encryption/decryption key to hardware + * + * @param key Key to be written to the AES hardware + * @param key_word_len Number of words in the key + * + * @return volatile number of bytes written to hardware, used for fault injection check + */ +static inline uint8_t aes_ll_write_key(const uint8_t *key, size_t key_word_len) +{ + /* This variable is used for fault injection checks, so marked volatile to avoid optimisation */ + volatile uint8_t key_in_hardware = 0; + uint32_t *key_words = (uint32_t *)key; + + for (int i = 0; i < key_word_len; i++) { + REG_WRITE(AES_KEY_BASE + i * 4, *(key_words + i)); + key_in_hardware += 4; + } + return key_in_hardware; +} + +/** + * @brief Sets the mode + * + * @param mode ESP_AES_ENCRYPT = 1, or ESP_AES_DECRYPT = 0 + * @param key_bytes Number of bytes in the key + */ +static inline void aes_ll_set_mode(int mode, uint8_t key_bytes) +{ + const uint32_t MODE_DECRYPT_BIT = 4; + unsigned mode_reg_base = (mode == ESP_AES_ENCRYPT) ? 0 : MODE_DECRYPT_BIT; + + /* See TRM for the mapping between keylength and mode bit */ + REG_WRITE(AES_MODE_REG, mode_reg_base + ((key_bytes / 8) - 2)); +} + +/** + * @brief Writes message block to AES hardware + * + * @param input Block to be written + */ +static inline void aes_ll_write_block(const void *input) +{ + const uint32_t *input_words = (const uint32_t *)input; + uint32_t i0, i1, i2, i3; + + /* Storing i0,i1,i2,i3 in registers, not in an array + helps a lot with optimisations at -Os level */ + i0 = input_words[0]; + REG_WRITE(AES_TEXT_IN_BASE, i0); + + i1 = input_words[1]; + REG_WRITE(AES_TEXT_IN_BASE + 4, i1); + + i2 = input_words[2]; + REG_WRITE(AES_TEXT_IN_BASE + 8, i2); + + i3 = input_words[3]; + REG_WRITE(AES_TEXT_IN_BASE + 12, i3); +} + +/** + * @brief Read the AES block + * + * @param output the output of the transform, length = AES_BLOCK_BYTES + */ +static inline void aes_ll_read_block(void *output) +{ + uint32_t *output_words = (uint32_t *)output; + const size_t REG_WIDTH = sizeof(uint32_t); + + for (size_t i = 0; i < AES_BLOCK_WORDS; i++) { + output_words[i] = REG_READ(AES_TEXT_OUT_BASE + (i * REG_WIDTH)); + } +} + +/** + * @brief Starts block transform + * + */ +static inline void aes_ll_start_transform(void) +{ + REG_WRITE(AES_TRIGGER_REG, 1); +} + + +/** + * @brief Read state of AES accelerator + * + * @return esp_aes_state_t + */ +static inline esp_aes_state_t aes_ll_get_state(void) +{ + return REG_READ(AES_STATE_REG); +} + + +/** + * @brief Set mode of operation + * + * @note Only used for DMA transforms + * + * @param mode + */ +static inline void aes_ll_set_block_mode(esp_aes_mode_t mode) +{ + REG_WRITE(AES_BLOCK_MODE_REG, mode); +} + +/** + * @brief Set AES-CTR counter to INC32 + * + * @note Only affects AES-CTR mode + * + */ +static inline void aes_ll_set_inc(void) +{ + REG_WRITE(AES_INC_SEL_REG, 0); +} + +/** + * @brief Release the DMA + * + */ +static inline void aes_ll_dma_exit(void) +{ + REG_WRITE(AES_DMA_EXIT_REG, 0); +} + +/** + * @brief Sets the number of blocks to be transformed + * + * @note Only used for DMA transforms + * + * @param num_blocks Number of blocks to transform + */ +static inline void aes_ll_set_num_blocks(size_t num_blocks) +{ + REG_WRITE(AES_BLOCK_NUM_REG, num_blocks); +} + +/* + * Write IV to hardware iv registers + */ +static inline void aes_ll_set_iv(const uint8_t *iv) +{ + uint32_t *iv_words = (uint32_t *)iv; + uint32_t *reg_addr_buf = (uint32_t *)(AES_IV_BASE); + + for (int i = 0; i < IV_WORDS; i++ ) { + REG_WRITE(®_addr_buf[i], iv_words[i]); + } +} + +/* + * Read IV from hardware iv registers + */ +static inline void aes_ll_read_iv(uint8_t *iv) +{ + uint32_t *iv_words = (uint32_t *)iv; + const size_t REG_WIDTH = sizeof(uint32_t); + + for (size_t i = 0; i < IV_WORDS; i++) { + iv_words[i] = REG_READ(AES_IV_BASE + (i * REG_WIDTH)); + } +} + +/** + * @brief Enable or disable DMA mode + * + * @param enable true to enable, false to disable. + */ +static inline void aes_ll_dma_enable(bool enable) +{ + REG_WRITE(AES_DMA_ENABLE_REG, enable); +} + +/** + * @brief Enable or disable transform completed interrupt + * + * @param enable true to enable, false to disable. + */ +static inline void aes_ll_interrupt_enable(bool enable) +{ + REG_WRITE(AES_INT_ENA_REG, enable); +} + +/** + * @brief Clears the interrupt + * + */ +static inline void aes_ll_interrupt_clear(void) +{ + REG_WRITE(AES_INT_CLR_REG, 1); +} + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/clk_gate_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/clk_gate_ll.h new file mode 100644 index 00000000..f7382650 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/clk_gate_ll.h @@ -0,0 +1,252 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/periph_defs.h" +#include "soc/system_reg.h" +#include "soc/syscon_reg.h" +#include "soc/dport_access.h" + +static inline uint32_t periph_ll_get_clk_en_mask(periph_module_t periph) +{ + switch (periph) { + case PERIPH_SARADC_MODULE: + return SYSTEM_APB_SARADC_CLK_EN; + case PERIPH_RMT_MODULE: + return SYSTEM_RMT_CLK_EN; + case PERIPH_LEDC_MODULE: + return SYSTEM_LEDC_CLK_EN; + case PERIPH_UART0_MODULE: + return SYSTEM_UART_CLK_EN; + case PERIPH_UART1_MODULE: + return SYSTEM_UART1_CLK_EN; + case PERIPH_I2C0_MODULE: + return SYSTEM_I2C_EXT0_CLK_EN; + case PERIPH_I2S1_MODULE: + return SYSTEM_I2S1_CLK_EN; + case PERIPH_TIMG0_MODULE: + return SYSTEM_TIMERGROUP_CLK_EN; + case PERIPH_TIMG1_MODULE: + return SYSTEM_TIMERGROUP1_CLK_EN; + case PERIPH_UHCI0_MODULE: + return SYSTEM_UHCI0_CLK_EN; + case PERIPH_SYSTIMER_MODULE: + return SYSTEM_SYSTIMER_CLK_EN; + case PERIPH_SPI_MODULE: + return SYSTEM_SPI01_CLK_EN; + case PERIPH_SPI2_MODULE: + return SYSTEM_SPI2_CLK_EN; + case PERIPH_TWAI_MODULE: + return SYSTEM_TWAI_CLK_EN; + case PERIPH_GDMA_MODULE: + return SYSTEM_DMA_CLK_EN; + case PERIPH_AES_MODULE: + return SYSTEM_CRYPTO_AES_CLK_EN; + case PERIPH_SHA_MODULE: + return SYSTEM_CRYPTO_SHA_CLK_EN; + case PERIPH_RSA_MODULE: + return SYSTEM_CRYPTO_RSA_CLK_EN; + case PERIPH_HMAC_MODULE: + return SYSTEM_CRYPTO_HMAC_CLK_EN; + case PERIPH_DS_MODULE: + return SYSTEM_CRYPTO_DS_CLK_EN; + case PERIPH_RNG_MODULE: + return SYSTEM_WIFI_CLK_RNG_EN; + case PERIPH_WIFI_MODULE: + return SYSTEM_WIFI_CLK_WIFI_EN_M; + case PERIPH_BT_MODULE: + return SYSTEM_WIFI_CLK_BT_EN_M; + case PERIPH_WIFI_BT_COMMON_MODULE: + return SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M; + case PERIPH_BT_BASEBAND_MODULE: + return SYSTEM_BT_BASEBAND_EN; + case PERIPH_BT_LC_MODULE: + return SYSTEM_BT_LC_EN; + default: + return 0; + } +} + +static inline uint32_t periph_ll_get_rst_en_mask(periph_module_t periph, bool enable) +{ + + (void)enable; // unused + + switch (periph) { + case PERIPH_SARADC_MODULE: + return SYSTEM_APB_SARADC_RST; + case PERIPH_RMT_MODULE: + return SYSTEM_RMT_RST; + case PERIPH_LEDC_MODULE: + return SYSTEM_LEDC_RST; + case PERIPH_UART0_MODULE: + return SYSTEM_UART_RST; + case PERIPH_UART1_MODULE: + return SYSTEM_UART1_RST; + case PERIPH_I2C0_MODULE: + return SYSTEM_I2C_EXT0_RST; + case PERIPH_I2S1_MODULE: + return SYSTEM_I2S1_RST; + case PERIPH_TIMG0_MODULE: + return SYSTEM_TIMERGROUP_RST; + case PERIPH_TIMG1_MODULE: + return SYSTEM_TIMERGROUP1_RST; + case PERIPH_UHCI0_MODULE: + return SYSTEM_UHCI0_RST; + case PERIPH_SYSTIMER_MODULE: + return SYSTEM_SYSTIMER_RST; + case PERIPH_GDMA_MODULE: + return SYSTEM_DMA_RST; + case PERIPH_SPI_MODULE: + return SYSTEM_SPI01_RST; + case PERIPH_SPI2_MODULE: + return SYSTEM_SPI2_RST; + case PERIPH_TWAI_MODULE: + return SYSTEM_TWAI_RST; + case PERIPH_HMAC_MODULE: + return SYSTEM_CRYPTO_HMAC_RST; + case PERIPH_AES_MODULE: + if (enable == true) { + // Clear reset on digital signature, otherwise AES unit is held in reset also. + return (SYSTEM_CRYPTO_AES_RST | SYSTEM_CRYPTO_DS_RST); + } else { + //Don't return other units to reset, as this pulls reset on RSA & SHA units, respectively. + return SYSTEM_CRYPTO_AES_RST; + } + case PERIPH_SHA_MODULE: + if (enable == true) { + // Clear reset on digital signature and HMAC, otherwise SHA is held in reset + return (SYSTEM_CRYPTO_SHA_RST | SYSTEM_CRYPTO_DS_RST | SYSTEM_CRYPTO_HMAC_RST); + } else { + // Don't assert reset on secure boot, otherwise AES is held in reset + return SYSTEM_CRYPTO_SHA_RST; + } + case PERIPH_RSA_MODULE: + if (enable == true) { + /* also clear reset on digital signature, otherwise RSA is held in reset */ + return (SYSTEM_CRYPTO_RSA_RST | SYSTEM_CRYPTO_DS_RST); + } else { + /* don't reset digital signature unit, as this resets AES also */ + return SYSTEM_CRYPTO_RSA_RST; + } + case PERIPH_DS_MODULE: + return SYSTEM_CRYPTO_DS_RST; + default: + return 0; + } +} + +static uint32_t periph_ll_get_clk_en_reg(periph_module_t periph) +{ + switch (periph) { + case PERIPH_RNG_MODULE: + case PERIPH_WIFI_MODULE: + case PERIPH_BT_MODULE: + case PERIPH_WIFI_BT_COMMON_MODULE: + case PERIPH_BT_BASEBAND_MODULE: + case PERIPH_BT_LC_MODULE: + return SYSTEM_WIFI_CLK_EN_REG; + + case PERIPH_HMAC_MODULE: + case PERIPH_DS_MODULE: + case PERIPH_AES_MODULE: + case PERIPH_RSA_MODULE: + case PERIPH_SHA_MODULE: + case PERIPH_GDMA_MODULE: + return SYSTEM_PERIP_CLK_EN1_REG; + default: + return SYSTEM_PERIP_CLK_EN0_REG; + } +} + +static uint32_t periph_ll_get_rst_en_reg(periph_module_t periph) +{ + switch (periph) { + case PERIPH_RNG_MODULE: + case PERIPH_WIFI_MODULE: + case PERIPH_BT_MODULE: + case PERIPH_WIFI_BT_COMMON_MODULE: + case PERIPH_BT_BASEBAND_MODULE: + case PERIPH_BT_LC_MODULE: + return SYSTEM_WIFI_RST_EN_REG; + + case PERIPH_HMAC_MODULE: + case PERIPH_DS_MODULE: + case PERIPH_AES_MODULE: + case PERIPH_RSA_MODULE: + case PERIPH_SHA_MODULE: + case PERIPH_GDMA_MODULE: + return SYSTEM_PERIP_RST_EN1_REG; + default: + return SYSTEM_PERIP_RST_EN0_REG; + } +} + +static inline void periph_ll_enable_clk_clear_rst(periph_module_t periph) +{ + DPORT_SET_PERI_REG_MASK(periph_ll_get_clk_en_reg(periph), periph_ll_get_clk_en_mask(periph)); + DPORT_CLEAR_PERI_REG_MASK(periph_ll_get_rst_en_reg(periph), periph_ll_get_rst_en_mask(periph, true)); +} + +static inline void periph_ll_disable_clk_set_rst(periph_module_t periph) +{ + DPORT_CLEAR_PERI_REG_MASK(periph_ll_get_clk_en_reg(periph), periph_ll_get_clk_en_mask(periph)); + DPORT_SET_PERI_REG_MASK(periph_ll_get_rst_en_reg(periph), periph_ll_get_rst_en_mask(periph, false)); +} + +static inline void IRAM_ATTR periph_ll_wifi_bt_module_enable_clk_clear_rst(void) +{ + DPORT_SET_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M); + DPORT_CLEAR_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, 0); +} + +static inline void IRAM_ATTR periph_ll_wifi_bt_module_disable_clk_set_rst(void) +{ + DPORT_CLEAR_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_WIFI_BT_COMMON_M); + DPORT_SET_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, 0); +} + +static inline void periph_ll_reset(periph_module_t periph) +{ + DPORT_SET_PERI_REG_MASK(periph_ll_get_rst_en_reg(periph), periph_ll_get_rst_en_mask(periph, false)); + DPORT_CLEAR_PERI_REG_MASK(periph_ll_get_rst_en_reg(periph), periph_ll_get_rst_en_mask(periph, false)); +} + +static inline bool IRAM_ATTR periph_ll_periph_enabled(periph_module_t periph) +{ + return DPORT_REG_GET_BIT(periph_ll_get_rst_en_reg(periph), periph_ll_get_rst_en_mask(periph, false)) == 0 && + DPORT_REG_GET_BIT(periph_ll_get_clk_en_reg(periph), periph_ll_get_clk_en_mask(periph)) != 0; +} + +static inline void periph_ll_wifi_module_enable_clk_clear_rst(void) +{ + DPORT_SET_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_WIFI_EN_M); + DPORT_CLEAR_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, 0); +} + +static inline void periph_ll_wifi_module_disable_clk_set_rst(void) +{ + DPORT_CLEAR_PERI_REG_MASK(SYSTEM_WIFI_CLK_EN_REG, SYSTEM_WIFI_CLK_WIFI_EN_M); + DPORT_SET_PERI_REG_MASK(SYSTEM_CORE_RST_EN_REG, 0); +} +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/cpu_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/cpu_ll.h new file mode 100644 index 00000000..1ac07fda --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/cpu_ll.h @@ -0,0 +1,161 @@ +// Copyright 2020 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. +#pragma once + +#include + +#include "soc/cpu_caps.h" +#include "esp_bit_defs.h" +#include "soc/assist_debug_reg.h" +#include "esp_attr.h" +#include "riscv/csr.h" + +/*performance counter*/ +#define CSR_PCER_MACHINE 0x7e0 +#define CSR_PCMR_MACHINE 0x7e1 +#define CSR_PCCR_MACHINE 0x7e2 + +#ifdef __cplusplus +extern "C" { +#endif + +static inline int IRAM_ATTR cpu_ll_get_core_id(void) +{ +#if SOC_CPU_CORES_NUM == 1 + return 0; // No need to check core ID on single core hardware +#else + int cpuid; + cpuid = RV_READ_CSR(mhartid); + return cpuid; +#endif +} + +static inline void cpu_ll_enable_cycle_count(void) +{ + RV_WRITE_CSR(CSR_PCER_MACHINE,1); + RV_WRITE_CSR(CSR_PCMR_MACHINE,1); + return; +} + +static inline uint32_t IRAM_ATTR cpu_ll_get_cycle_count(void) +{ + uint32_t result; + result = RV_READ_CSR(CSR_PCCR_MACHINE); + return result; +} + +static inline void IRAM_ATTR cpu_ll_set_cycle_count(uint32_t val) +{ + RV_WRITE_CSR(CSR_PCCR_MACHINE, val); +} + +static inline void* cpu_ll_get_sp(void) +{ + void *sp; + asm volatile ("mv %0, sp;" : "=r" (sp)); + return sp; +} + +static inline void cpu_ll_init_hwloop(void) +{ + // Nothing needed here for ESP32-C3 +} + +static inline void cpu_ll_set_breakpoint(int id, uint32_t pc) +{ + RV_WRITE_CSR(tselect,id); + RV_SET_CSR(CSR_TCONTROL,TCONTROL_MTE); + RV_SET_CSR(CSR_TDATA1, TDATA1_USER|TDATA1_MACHINE|TDATA1_EXECUTE); + RV_WRITE_CSR(tdata2,pc); + return; +} + +static inline void cpu_ll_clear_breakpoint(int id) +{ + RV_WRITE_CSR(tselect,id); + RV_CLEAR_CSR(CSR_TCONTROL,TCONTROL_MTE); + RV_CLEAR_CSR(CSR_TDATA1, TDATA1_USER|TDATA1_MACHINE|TDATA1_EXECUTE); + return; +} + +static inline uint32_t cpu_ll_ptr_to_pc(const void* addr) +{ + return ((uint32_t) addr); +} + +static inline void* cpu_ll_pc_to_ptr(uint32_t pc) +{ + return (void*) ((pc & 0x3fffffff) | 0x40000000); +} + +static inline void cpu_ll_set_watchpoint(int id, + const void* addr, + size_t size, + bool on_read, + bool on_write) +{ + uint32_t addr_napot; + RV_WRITE_CSR(tselect,id); + RV_SET_CSR(CSR_TCONTROL, TCONTROL_MPTE | TCONTROL_MTE); + RV_SET_CSR(CSR_TDATA1, TDATA1_USER|TDATA1_MACHINE); + RV_SET_CSR_FIELD(CSR_TDATA1, TDATA1_MATCH, 1); + // add 0 in napot encoding + addr_napot = ((uint32_t) addr) | ((size >> 1) - 1); + if (on_read) { + RV_SET_CSR(CSR_TDATA1, TDATA1_LOAD); + } + if (on_write) { + RV_SET_CSR(CSR_TDATA1, TDATA1_STORE); + } + RV_WRITE_CSR(tdata2,addr_napot); + return; +} + +static inline void cpu_ll_clear_watchpoint(int id) +{ + RV_WRITE_CSR(tselect,id); + RV_CLEAR_CSR(CSR_TCONTROL,TCONTROL_MTE); + RV_CLEAR_CSR(CSR_TDATA1, TDATA1_USER|TDATA1_MACHINE); + RV_CLEAR_CSR_FIELD(CSR_TDATA1,TDATA1_MATCH); + RV_CLEAR_CSR(CSR_TDATA1, TDATA1_MACHINE); + RV_CLEAR_CSR(CSR_TDATA1, TDATA1_LOAD|TDATA1_STORE|TDATA1_EXECUTE); + return; +} + +FORCE_INLINE_ATTR bool cpu_ll_is_debugger_attached(void) +{ + return REG_GET_BIT(ASSIST_DEBUG_C0RE_0_DEBUG_MODE_REG, ASSIST_DEBUG_CORE_0_DEBUG_MODULE_ACTIVE); +} + +static inline void cpu_ll_break(void) +{ + asm volatile("ebreak\n"); + return; +} + +static inline void cpu_ll_set_vecbase(const void* vecbase) +{ + uintptr_t vecbase_int = (uintptr_t)vecbase; + vecbase_int |= 1; // Set MODE field to treat MTVEC as a vector base address + RV_WRITE_CSR(mtvec, vecbase_int); +} + +static inline void cpu_ll_waiti(void) +{ + asm volatile ("wfi\n"); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ds_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ds_ll.h new file mode 100644 index 00000000..933c1573 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ds_ll.h @@ -0,0 +1,175 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use it in application code. + ******************************************************************************/ + +#pragma once + +#include +#include +#include + +#include "soc/hwcrypto_reg.h" +#include "soc/ds_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +static inline void ds_ll_start(void) +{ + REG_WRITE(DS_SET_START_REG, 1); +} + +/** + * @brief Wait until DS peripheral has finished any outstanding operation. + */ +static inline bool ds_ll_busy(void) +{ + return (REG_READ(DS_QUERY_BUSY_REG) > 0) ? true : false; +} + +/** + * @brief Busy wait until the hardware is ready. + */ +static inline void ds_ll_wait_busy(void) +{ + while (ds_ll_busy()); +} + +/** + * @brief In case of a key error, check what caused it. + */ +static inline ds_key_check_t ds_ll_key_error_source(void) +{ + uint32_t key_error = REG_READ(DS_QUERY_KEY_WRONG_REG); + if (key_error == 0) { + return DS_NO_KEY_INPUT; + } else { + return DS_OTHER_WRONG; + } +} + +/** + * @brief Write the initialization vector to the corresponding register field. + */ +static inline void ds_ll_configure_iv(const uint32_t *iv) +{ + for (size_t i = 0; i < (DS_KEY_PARAM_MD_IV_LENGTH / sizeof(uint32_t)); i++) { + REG_WRITE(DS_IV_BASE + (i * 4) , iv[i]); + } +} + +/** + * @brief Write the message which should be signed. + * + * @param msg Pointer to the message. + * @param size Length of msg in bytes. It is the RSA signature length in bytes. + */ +static inline void ds_ll_write_message(const uint8_t *msg, size_t size) +{ + memcpy((uint8_t*) DS_X_BASE, msg, size); + asm volatile ("fence"); +} + +/** + * @brief Write the encrypted private key parameters. + */ +static inline void ds_ll_write_private_key_params(const uint8_t *encrypted_key_params) +{ + /* Note: as the internal peripheral still has RSA 4096 structure, + but C is encrypted based on the actual max RSA length (ETS_DS_MAX_BITS), need to fragment it + when copying to hardware... + + (note if ETS_DS_MAX_BITS == 4096, this should be the same as copying data->c to hardware in one fragment) + */ + typedef struct { uint32_t addr; size_t len; } frag_t; + const frag_t frags[] = { + {DS_C_Y_BASE, DS_SIGNATURE_MAX_BIT_LEN / 8}, + {DS_C_M_BASE, DS_SIGNATURE_MAX_BIT_LEN / 8}, + {DS_C_RB_BASE, DS_SIGNATURE_MAX_BIT_LEN / 8}, + {DS_C_BOX_BASE, DS_IV_BASE - DS_C_BOX_BASE}, + }; + const size_t NUM_FRAGS = sizeof(frags)/sizeof(frag_t); + const uint8_t *from = encrypted_key_params; + + for (int i = 0; i < NUM_FRAGS; i++) { + memcpy((uint8_t *)frags[i].addr, from, frags[i].len); + asm volatile ("fence"); + from += frags[i].len; + } +} + +/** + * @brief Begin signing procedure. + */ +static inline void ds_ll_start_sign(void) +{ + REG_WRITE(DS_SET_ME_REG, 1); +} + +/** + * @brief check the calculated signature. + * + * @return + * - DS_SIGNATURE_OK if no issue is detected with the signature. + * - DS_SIGNATURE_PADDING_FAIL if the padding of the private key parameters is wrong. + * - DS_SIGNATURE_MD_FAIL if the message digest check failed. This means that the message digest calculated using + * the private key parameters fails, i.e., the integrity of the private key parameters is not protected. + * - DS_SIGNATURE_PADDING_AND_MD_FAIL if both padding and message digest check fail. + */ +static inline ds_signature_check_t ds_ll_check_signature(void) +{ + uint32_t result = REG_READ(DS_QUERY_CHECK_REG); + switch(result) { + case 0: + return DS_SIGNATURE_OK; + case 1: + return DS_SIGNATURE_MD_FAIL; + case 2: + return DS_SIGNATURE_PADDING_FAIL; + default: + return DS_SIGNATURE_PADDING_AND_MD_FAIL; + } +} + +/** + * @brief Read the signature from the hardware. + * + * @param result The signature result. + * @param size Length of signature result in bytes. It is the RSA signature length in bytes. + */ +static inline void ds_ll_read_result(uint8_t *result, size_t size) +{ + memcpy(result, (uint8_t*) DS_Z_BASE, size); + asm volatile ("fence"); +} + +/** + * @brief Exit the signature operation. + * + * @note This does not deactivate the module. Corresponding clock/reset bits have to be triggered for deactivation. + */ +static inline void ds_ll_finish(void) +{ + REG_WRITE(DS_SET_FINISH_REG, 1); + ds_ll_wait_busy(); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gdma_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gdma_ll.h new file mode 100644 index 00000000..22410d3b --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gdma_ll.h @@ -0,0 +1,410 @@ +// Copyright 2020 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. +#pragma once + +#include +#include +#include "soc/gdma_struct.h" +#include "soc/gdma_reg.h" +#include "soc/gdma_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define GDMA_LL_GET_HW(id) (((id) == 0) ? (&GDMA) : NULL) + +#define GDMA_LL_EVENT_TX_FIFO_UDF (1<<12) +#define GDMA_LL_EVENT_TX_FIFO_OVF (1<<11) +#define GDMA_LL_EVENT_RX_FIFO_UDF (1<<10) +#define GDMA_LL_EVENT_RX_FIFO_OVF (1<<9) +#define GDMA_LL_EVENT_TX_TOTAL_EOF (1<<8) +#define GDMA_LL_EVENT_RX_DESC_EMPTY (1<<7) +#define GDMA_LL_EVENT_TX_DESC_ERROR (1<<6) +#define GDMA_LL_EVENT_RX_DESC_ERROR (1<<5) +#define GDMA_LL_EVENT_TX_EOF (1<<4) +#define GDMA_LL_EVENT_TX_DONE (1<<3) +#define GDMA_LL_EVENT_RX_ERR_EOF (1<<2) +#define GDMA_LL_EVENT_RX_SUC_EOF (1<<1) +#define GDMA_LL_EVENT_RX_DONE (1<<0) + +///////////////////////////////////// Common ///////////////////////////////////////// +/** + * @brief Enable DMA channel M2M mode (TX channel n forward data to RX channel n), disabled by default + */ +static inline void gdma_ll_enable_m2m_mode(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].in.in_conf0.mem_trans_en = enable; + if (enable) { + // only have to give it a valid value + dev->channel[channel].in.in_peri_sel.sel = 0; + dev->channel[channel].out.out_peri_sel.sel = 0; + } +} + +/** + * @brief Get DMA interrupt status word + */ +static inline uint32_t gdma_ll_get_interrupt_status(gdma_dev_t *dev, uint32_t channel) +{ + return dev->intr[channel].st.val; +} + +/** + * @brief Enable DMA interrupt + */ +static inline void gdma_ll_enable_interrupt(gdma_dev_t *dev, uint32_t channel, uint32_t mask, bool enable) +{ + if (enable) { + dev->intr[channel].ena.val |= mask; + } else { + dev->intr[channel].ena.val &= ~mask; + } +} + +/** + * @brief Clear DMA interrupt + */ +static inline void gdma_ll_clear_interrupt_status(gdma_dev_t *dev, uint32_t channel, uint32_t mask) +{ + dev->intr[channel].clr.val = mask; +} + +/** + * @brief Enable DMA clock gating + */ +static inline void gdma_ll_enable_clock(gdma_dev_t *dev, bool enable) +{ + dev->misc_conf.clk_en = enable; +} + +///////////////////////////////////// RX ///////////////////////////////////////// +/** + * @brief Enable DMA RX channel to check the owner bit in the descriptor, disabled by default + */ +static inline void gdma_ll_rx_enable_owner_check(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].in.in_conf1.in_check_owner = enable; +} + +/** + * @brief Enable DMA RX channel burst reading data, disabled by default + */ +static inline void gdma_ll_rx_enable_data_burst(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].in.in_conf0.in_data_burst_en = enable; +} + +/** + * @brief Enable DMA RX channel burst reading descriptor link, disabled by default + */ +static inline void gdma_ll_rx_enable_descriptor_burst(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].in.in_conf0.indscr_burst_en = enable; +} + +/** + * @brief Reset DMA RX channel FSM and FIFO pointer + */ +static inline void gdma_ll_rx_reset_channel(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].in.in_conf0.in_rst = 1; + dev->channel[channel].in.in_conf0.in_rst = 0; +} + +/** + * @brief Check if DMA RX FIFO is full + * @param fifo_level only supports level 1 + */ +static inline bool gdma_ll_rx_is_fifo_full(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].in.infifo_status.val & 0x01; +} + +/** + * @brief Check if DMA RX FIFO is empty + * @param fifo_level only supports level 1 + */ +static inline bool gdma_ll_rx_is_fifo_empty(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].in.infifo_status.val & 0x02; +} + +/** + * @brief Get number of bytes in RX FIFO + * @param fifo_level only supports level 1 + */ +static inline uint32_t gdma_ll_rx_get_fifo_bytes(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].in.infifo_status.infifo_cnt; +} + +/** + * @brief Pop data from DMA RX FIFO + */ +static inline uint32_t gdma_ll_rx_pop_data(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].in.in_pop.infifo_pop = 1; + return dev->channel[channel].in.in_pop.infifo_rdata; +} + +/** + * @brief Set the descriptor link base address for RX channel + */ +static inline void gdma_ll_rx_set_desc_addr(gdma_dev_t *dev, uint32_t channel, uint32_t addr) +{ + dev->channel[channel].in.in_link.addr = addr; +} + +/** + * @brief Start dealing with RX descriptors + */ +static inline void gdma_ll_rx_start(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].in.in_link.start = 1; +} + +/** + * @brief Stop dealing with RX descriptors + */ +static inline void gdma_ll_rx_stop(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].in.in_link.stop = 1; +} + +/** + * @brief Restart a new inlink right after the last descriptor + */ +static inline void gdma_ll_rx_restart(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].in.in_link.restart = 1; +} + +/** + * @brief Enable DMA RX to return the address of current descriptor when receives error + */ +static inline void gdma_ll_rx_enable_auto_return(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].in.in_link.auto_ret = enable; +} + +/** + * @brief Check if DMA RX FSM is in IDLE state + */ +static inline bool gdma_ll_rx_is_fsm_idle(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].in.in_link.park; +} + +/** + * @brief Get RX success EOF descriptor's address + */ +static inline uint32_t gdma_ll_rx_get_success_eof_desc_addr(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].in.in_suc_eof_des_addr; +} + +/** + * @brief Get RX error EOF descriptor's address + */ +static inline uint32_t gdma_ll_rx_get_error_eof_desc_addr(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].in.in_err_eof_des_addr; +} + +/** + * @brief Get current RX descriptor's address + */ +static inline uint32_t gdma_ll_rx_get_current_desc_addr(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].in.in_dscr; +} + +/** + * @brief Set priority for DMA RX channel + */ +static inline void gdma_ll_rx_set_priority(gdma_dev_t *dev, uint32_t channel, uint32_t prio) +{ + dev->channel[channel].in.in_pri.rx_pri = prio; +} + +/** + * @brief Connect DMA RX channel to a given peripheral + */ +static inline void gdma_ll_rx_connect_to_periph(gdma_dev_t *dev, uint32_t channel, int periph_id) +{ + dev->channel[channel].in.in_peri_sel.sel = periph_id; +} + +///////////////////////////////////// TX ///////////////////////////////////////// +/** + * @brief Enable DMA TX channel to check the owner bit in the descriptor, disabled by default + */ +static inline void gdma_ll_tx_enable_owner_check(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].out.out_conf1.out_check_owner = enable; +} + +/** + * @brief Enable DMA TX channel burst sending data, disabled by default + */ +static inline void gdma_ll_tx_enable_data_burst(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].out.out_conf0.out_data_burst_en = enable; +} + +/** + * @brief Enable DMA TX channel burst reading descriptor link, disabled by default + */ +static inline void gdma_ll_tx_enable_descriptor_burst(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].out.out_conf0.outdscr_burst_en = enable; +} + +/** + * @brief Set TX channel EOF mode + */ +static inline void gdma_ll_tx_set_eof_mode(gdma_dev_t *dev, uint32_t channel, uint32_t mode) +{ + dev->channel[channel].out.out_conf0.out_eof_mode = mode; +} + +/** + * @brief Enable DMA TX channel automatic write results back to descriptor after all data has been sent out, disabled by default + */ +static inline void gdma_ll_tx_enable_auto_write_back(gdma_dev_t *dev, uint32_t channel, bool enable) +{ + dev->channel[channel].out.out_conf0.out_auto_wrback = enable; +} + +/** + * @brief Reset DMA TX channel FSM and FIFO pointer + */ +static inline void gdma_ll_tx_reset_channel(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].out.out_conf0.out_rst = 1; + dev->channel[channel].out.out_conf0.out_rst = 0; +} + +/** + * @brief Check if DMA TX FIFO is full + * @param fifo_level only supports level 1 + */ +static inline bool gdma_ll_tx_is_fifo_full(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].out.outfifo_status.val & 0x01; +} + +/** + * @brief Check if DMA TX FIFO is empty + * @param fifo_level only supports level 1 + */ +static inline bool gdma_ll_tx_is_fifo_empty(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].out.outfifo_status.val & 0x02; +} + +/** + * @brief Get number of bytes in TX FIFO + * @param fifo_level only supports level 1 + */ +static inline uint32_t gdma_ll_tx_get_fifo_bytes(gdma_dev_t *dev, uint32_t channel, uint32_t fifo_level) +{ + return dev->channel[channel].out.outfifo_status.outfifo_cnt; +} + +/** + * @brief Push data into DMA TX FIFO + */ +static inline void gdma_ll_tx_push_data(gdma_dev_t *dev, uint32_t channel, uint32_t data) +{ + dev->channel[channel].out.out_push.outfifo_wdata = data; + dev->channel[channel].out.out_push.outfifo_push = 1; +} + +/** + * @brief Set the descriptor link base address for TX channel + */ +static inline void gdma_ll_tx_set_desc_addr(gdma_dev_t *dev, uint32_t channel, uint32_t addr) +{ + dev->channel[channel].out.out_link.addr = addr; +} + +/** + * @brief Start dealing with TX descriptors + */ +static inline void gdma_ll_tx_start(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].out.out_link.start = 1; +} + +/** + * @brief Stop dealing with TX descriptors + */ +static inline void gdma_ll_tx_stop(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].out.out_link.stop = 1; +} + +/** + * @brief Restart a new outlink right after the last descriptor + */ +static inline void gdma_ll_tx_restart(gdma_dev_t *dev, uint32_t channel) +{ + dev->channel[channel].out.out_link.restart = 1; +} + +/** + * @brief Check if DMA TX FSM is in IDLE state + */ +static inline bool gdma_ll_tx_is_fsm_idle(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].out.out_link.park; +} + +/** + * @brief Get TX EOF descriptor's address + */ +static inline uint32_t gdma_ll_tx_get_eof_desc_addr(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].out.out_eof_des_addr; +} + +/** + * @brief Get current TX descriptor's address + */ +static inline uint32_t gdma_ll_tx_get_current_desc_addr(gdma_dev_t *dev, uint32_t channel) +{ + return dev->channel[channel].out.out_dscr; +} + +/** + * @brief Set priority for DMA TX channel + */ +static inline void gdma_ll_tx_set_priority(gdma_dev_t *dev, uint32_t channel, uint32_t prio) +{ + dev->channel[channel].out.out_pri.tx_pri = prio; +} + +/** + * @brief Connect DMA TX channel to a given peripheral + */ +static inline void gdma_ll_tx_connect_to_periph(gdma_dev_t *dev, uint32_t channel, int periph_id) +{ + dev->channel[channel].out.out_peri_sel.sel = periph_id; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpio_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpio_ll.h new file mode 100644 index 00000000..5fdd8f38 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpio_ll.h @@ -0,0 +1,561 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The LL layer for ESP32-C3 GPIO register operations + +#pragma once + +#include "soc/soc.h" +#include "soc/gpio_periph.h" +#include "soc/rtc_cntl_reg.h" +#include "hal/gpio_types.h" +#include "stdlib.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Get GPIO hardware instance with giving gpio num +#define GPIO_LL_GET_HW(num) (((num) == 0) ? (&GPIO) : NULL) + +#define GPIO_LL_PRO_CPU_INTR_ENA (BIT(0)) +#define GPIO_LL_PRO_CPU_NMI_INTR_ENA (BIT(1)) +/** + * @brief Enable pull-up on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_pullup_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + REG_SET_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PU); +} + +/** + * @brief Disable pull-up on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_pullup_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + REG_CLR_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PU); +} + +/** + * @brief Enable pull-down on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_pulldown_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + REG_SET_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PD); +} + +/** + * @brief Disable pull-down on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_pulldown_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + REG_CLR_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PD); +} + +/** + * @brief GPIO set interrupt trigger type + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param intr_type Interrupt type, select from gpio_int_type_t + */ +static inline void gpio_ll_set_intr_type(gpio_dev_t *hw, gpio_num_t gpio_num, gpio_int_type_t intr_type) +{ + hw->pin[gpio_num].int_type = intr_type; +} + +/** + * @brief Get GPIO interrupt status + * + * @param hw Peripheral GPIO hardware instance address. + * @param core_id interrupt core id + * @param status interrupt status + */ +static inline void gpio_ll_get_intr_status(gpio_dev_t *hw, uint32_t core_id, uint32_t *status) +{ + *status = hw->pcpu_int.intr; +} + +/** + * @brief Get GPIO interrupt status high + * + * @param hw Peripheral GPIO hardware instance address. + * @param core_id interrupt core id + * @param status interrupt status high + */ +static inline void gpio_ll_get_intr_status_high(gpio_dev_t *hw, uint32_t core_id, uint32_t *status) +{ + *status = 0; // Less than 32 GPIOs in ESP32-C3 +} + +/** + * @brief Clear GPIO interrupt status + * + * @param hw Peripheral GPIO hardware instance address. + * @param mask interrupt status clear mask + */ +static inline void gpio_ll_clear_intr_status(gpio_dev_t *hw, uint32_t mask) +{ + hw->status_w1tc.status_w1tc = mask; +} + +/** + * @brief Clear GPIO interrupt status high + * + * @param hw Peripheral GPIO hardware instance address. + * @param mask interrupt status high clear mask + */ +static inline void gpio_ll_clear_intr_status_high(gpio_dev_t *hw, uint32_t mask) +{ + // Not supported on C3 +} + +/** + * @brief Enable GPIO module interrupt signal + * + * @param hw Peripheral GPIO hardware instance address. + * @param core_id Interrupt enabled CPU to corresponding ID + * @param gpio_num GPIO number. If you want to enable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + */ +static inline void gpio_ll_intr_enable_on_core(gpio_dev_t *hw, uint32_t core_id, gpio_num_t gpio_num) +{ + if (core_id == 0) { + GPIO.pin[gpio_num].int_ena = GPIO_LL_PRO_CPU_INTR_ENA; //enable pro cpu intr + } else { + // GPIO.pin[gpio_num].int_ena = GPIO_APP_CPU_INTR_ENA; //enable pro cpu intr + } +} + +/** + * @brief Disable GPIO module interrupt signal + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + */ +static inline void gpio_ll_intr_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->pin[gpio_num].int_ena = 0; //disable GPIO intr +} + +/** + * @brief Disable input mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_input_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_INPUT_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable input mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_input_enable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_INPUT_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable output mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_output_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->enable_w1tc.enable_w1tc = (0x1 << gpio_num); + // Ensure no other output signal is routed via GPIO matrix to this pin + REG_WRITE(GPIO_FUNC0_OUT_SEL_CFG_REG + (gpio_num * 4), + SIG_GPIO_OUT_IDX); +} + +/** + * @brief Enable output mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_output_enable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->enable_w1ts.enable_w1ts = (0x1 << gpio_num); +} + +/** + * @brief Disable open-drain mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_od_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->pin[gpio_num].pad_driver = 0; +} + +/** + * @brief Enable open-drain mode on GPIO. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_od_enable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->pin[gpio_num].pad_driver = 1; +} + +/** + * @brief GPIO set output level + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param level Output level. 0: low ; 1: high + */ +static inline void gpio_ll_set_level(gpio_dev_t *hw, gpio_num_t gpio_num, uint32_t level) +{ + if (level) { + hw->out_w1ts.out_w1ts = (1 << gpio_num); + } else { + hw->out_w1tc.out_w1tc = (1 << gpio_num); + } +} + +/** + * @brief GPIO get input level + * + * @warning If the pad is not configured for input (or input and output) the returned value is always 0. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); + * + * @return + * - 0 the GPIO input level is 0 + * - 1 the GPIO input level is 1 + */ +static inline int gpio_ll_get_level(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + return (hw->in.data >> gpio_num) & 0x1; +} + +/** + * @brief Enable GPIO wake-up function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + */ +static inline void gpio_ll_wakeup_enable(gpio_dev_t *hw, gpio_num_t gpio_num, gpio_int_type_t intr_type) +{ + hw->pin[gpio_num].int_type = intr_type; + hw->pin[gpio_num].wakeup_enable = 0x1; +} + +/** + * @brief Disable GPIO wake-up function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_wakeup_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + hw->pin[gpio_num].wakeup_enable = 0; +} + +/** + * @brief Set GPIO pad drive capability + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Drive capability of the pad + */ +static inline void gpio_ll_set_drive_capability(gpio_dev_t *hw, gpio_num_t gpio_num, gpio_drive_cap_t strength) +{ + SET_PERI_REG_BITS(GPIO_PIN_MUX_REG[gpio_num], FUN_DRV_V, strength, FUN_DRV_S); +} + +/** + * @brief Get GPIO pad drive capability + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Pointer to accept drive capability of the pad + */ +static inline void gpio_ll_get_drive_capability(gpio_dev_t *hw, gpio_num_t gpio_num, gpio_drive_cap_t *strength) +{ + *strength = GET_PERI_REG_BITS2(GPIO_PIN_MUX_REG[gpio_num], FUN_DRV_V, FUN_DRV_S); +} + +/** + * @brief Enable all digital gpio pad hold function during Deep-sleep. + * + * @param hw Peripheral GPIO hardware instance address. + */ +static inline void gpio_ll_deep_sleep_hold_en(gpio_dev_t *hw) +{ + SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_DG_PAD_AUTOHOLD_EN_M); +} + +/** + * @brief Disable all digital gpio pad hold function during Deep-sleep. + * + * @param hw Peripheral GPIO hardware instance address. + */ +static inline void gpio_ll_deep_sleep_hold_dis(gpio_dev_t *hw) +{ + SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_CLR_DG_PAD_AUTOHOLD); +} + +/** + * @brief Enable gpio pad hold function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number, only support output GPIOs + */ +static inline void gpio_ll_hold_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + if (gpio_num <= GPIO_NUM_5) { + REG_SET_BIT(RTC_CNTL_PAD_HOLD_REG, BIT(gpio_num)); + } else { + SET_PERI_REG_MASK(RTC_CNTL_DIG_PAD_HOLD_REG, GPIO_HOLD_MASK[gpio_num]); + } +} + +/** + * @brief Disable gpio pad hold function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number, only support output GPIOs + */ +static inline void gpio_ll_hold_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + if (gpio_num <= GPIO_NUM_5) { + REG_CLR_BIT(RTC_CNTL_PAD_HOLD_REG, BIT(gpio_num)); + } else { + CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_PAD_HOLD_REG, GPIO_HOLD_MASK[gpio_num]); + } +} + +/** + * @brief Set pad input to a peripheral signal through the IOMUX. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number of the pad. + * @param signal_idx Peripheral signal id to input. One of the ``*_IN_IDX`` signals in ``soc/gpio_sig_map.h``. + */ +static inline void gpio_ll_iomux_in(gpio_dev_t *hw, uint32_t gpio, uint32_t signal_idx) +{ + hw->func_in_sel_cfg[signal_idx].sig_in_sel = 0; + PIN_INPUT_ENABLE(GPIO_PIN_MUX_REG[gpio]); +} + +/** + * @brief Set peripheral output to an GPIO pad through the IOMUX. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num gpio_num GPIO number of the pad. + * @param func The function number of the peripheral pin to output pin. + * One of the ``FUNC_X_*`` of specified pin (X) in ``soc/io_mux_reg.h``. + * @param oen_inv True if the output enable needs to be inverted, otherwise False. + */ +static inline void gpio_ll_iomux_out(gpio_dev_t *hw, uint8_t gpio_num, int func, uint32_t oen_inv) +{ + hw->func_out_sel_cfg[gpio_num].oen_sel = 0; + hw->func_out_sel_cfg[gpio_num].oen_inv_sel = oen_inv; + PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[gpio_num], func); +} + +static inline void gpio_ll_force_hold_all(gpio_dev_t *hw) +{ + CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_DG_PAD_FORCE_UNHOLD); + SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_DG_PAD_FORCE_HOLD); + SET_PERI_REG_MASK(RTC_CNTL_PWC_REG, RTC_CNTL_PAD_FORCE_HOLD_M); +} + +static inline void gpio_ll_force_unhold_all(void) +{ + CLEAR_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_DG_PAD_FORCE_HOLD); + CLEAR_PERI_REG_MASK(RTC_CNTL_PWC_REG, RTC_CNTL_PAD_FORCE_HOLD_M); + SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_DG_PAD_FORCE_UNHOLD); + SET_PERI_REG_MASK(RTC_CNTL_DIG_ISO_REG, RTC_CNTL_CLR_DG_PAD_AUTOHOLD); +} + +/** + * @brief Enable GPIO pin used for wakeup from sleep. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_sel_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_SEL_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable GPIO pin used for wakeup from sleep. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_sel_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_SEL_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable GPIO pull-up in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_pullup_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_PULLUP_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable GPIO pull-up in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_pullup_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_PULLUP_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable GPIO pull-down in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_pulldown_en(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_PULLDOWN_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable GPIO pull-down in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_pulldown_dis(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_PULLDOWN_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable GPIO input in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_input_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_INPUT_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable GPIO input in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_input_enable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_INPUT_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Disable GPIO output in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_output_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_OUTPUT_DISABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable GPIO output in sleep mode. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_sleep_output_enable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + PIN_SLP_OUTPUT_ENABLE(GPIO_PIN_MUX_REG[gpio_num]); +} + +/** + * @brief Enable GPIO deep-sleep wake-up function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number. + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + */ +static inline void gpio_ll_deepsleep_wakeup_enable(gpio_dev_t *hw, gpio_num_t gpio_num, gpio_int_type_t intr_type) +{ + if (gpio_num > GPIO_NUM_5) { + abort(); // gpio lager than 5 doesn't support. + } + REG_SET_BIT(RTC_CNTL_GPIO_WAKEUP_REG, RTC_CNTL_GPIO_PIN_CLK_GATE); + REG_SET_BIT(RTC_CNTL_EXT_WAKEUP_CONF_REG, RTC_CNTL_GPIO_WAKEUP_FILTER); + SET_PERI_REG_MASK(RTC_CNTL_GPIO_WAKEUP_REG, 1 << (RTC_CNTL_GPIO_PIN0_WAKEUP_ENABLE_S - gpio_num)); + uint32_t reg = REG_READ(RTC_CNTL_GPIO_WAKEUP_REG); + reg &= (~(RTC_CNTL_GPIO_PIN0_INT_TYPE_V << (RTC_CNTL_GPIO_PIN0_INT_TYPE_S - gpio_num * 3))); + reg |= (intr_type << (RTC_CNTL_GPIO_PIN0_INT_TYPE_S - gpio_num * 3)); + REG_WRITE(RTC_CNTL_GPIO_WAKEUP_REG, reg); +} + +/** + * @brief Disable GPIO deep-sleep wake-up function. + * + * @param hw Peripheral GPIO hardware instance address. + * @param gpio_num GPIO number + */ +static inline void gpio_ll_deepsleep_wakeup_disable(gpio_dev_t *hw, gpio_num_t gpio_num) +{ + if (gpio_num > GPIO_NUM_5) { + abort(); // gpio lager than 5 doesn't support. + } + CLEAR_PERI_REG_MASK(RTC_CNTL_GPIO_WAKEUP_REG, 1 << (RTC_CNTL_GPIO_PIN0_WAKEUP_ENABLE_S - gpio_num)); + CLEAR_PERI_REG_MASK(RTC_CNTL_GPIO_WAKEUP_REG, RTC_CNTL_GPIO_PIN0_INT_TYPE_S - gpio_num * 3); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpspi_flash_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpspi_flash_ll.h new file mode 100644 index 00000000..d1911c4a --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/gpspi_flash_ll.h @@ -0,0 +1,388 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The ll is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The Lowlevel layer for SPI Flash + +#pragma once + +#include +#include "soc/spi_periph.h" +#include "hal/spi_types.h" +#include "hal/spi_flash_types.h" +#include // For MIN/MAX +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +//NOTE: These macros are changed on c3 for build. MODIFY these when bringup flash. +#define gpspi_flash_ll_get_hw(host_id) ( ((host_id)==SPI2_HOST) ? &GPSPI2 : ({abort();(spi_dev_t*)0;}) ) +#define gpspi_flash_ll_hw_get_id(dev) ( ((dev) == (void*)&GPSPI2) ? SPI2_HOST : -1 ) + +typedef typeof(GPSPI2.clock) gpspi_flash_ll_clock_reg_t; + +//Supported clock register values +#define GPSPI_FLASH_LL_CLKREG_VAL_5MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x0000F1CF}) ///< Clock set to 5 MHz +#define GPSPI_FLASH_LL_CLKREG_VAL_10MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x000070C7}) ///< Clock set to 10 MHz +#define GPSPI_FLASH_LL_CLKREG_VAL_20MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x00003043}) ///< Clock set to 20 MHz +#define GPSPI_FLASH_LL_CLKREG_VAL_26MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x00002002}) ///< Clock set to 26 MHz +#define GPSPI_FLASH_LL_CLKREG_VAL_40MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x00001001}) ///< Clock set to 40 MHz +#define GPSPI_FLASH_LL_CLKREG_VAL_80MHZ ((gpspi_flash_ll_clock_reg_t){.val=0x80000000}) ///< Clock set to 80 MHz + +/*------------------------------------------------------------------------------ + * Control + *----------------------------------------------------------------------------*/ +/** + * Reset peripheral registers before configuration and starting control + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void gpspi_flash_ll_reset(spi_dev_t *dev) +{ + dev->user.val = 0; + dev->ctrl.val = 0; + + dev->clk_gate.clk_en = 1; + dev->clk_gate.mst_clk_active = 1; + dev->clk_gate.mst_clk_sel = 1; + + dev->dma_conf.val = 0; + dev->dma_conf.tx_seg_trans_clr_en = 1; + dev->dma_conf.rx_seg_trans_clr_en = 1; + dev->dma_conf.dma_seg_trans_en = 0; +} + +/** + * Check whether the previous operation is done. + * + * @param dev Beginning address of the peripheral registers. + * + * @return true if last command is done, otherwise false. + */ +static inline bool gpspi_flash_ll_cmd_is_done(const spi_dev_t *dev) +{ + return (dev->cmd.usr == 0); +} + +/** + * Get the read data from the buffer after ``gpspi_flash_ll_read`` is done. + * + * @param dev Beginning address of the peripheral registers. + * @param buffer Buffer to hold the output data + * @param read_len Length to get out of the buffer + */ +static inline void gpspi_flash_ll_get_buffer_data(spi_dev_t *dev, void *buffer, uint32_t read_len) +{ + if (((intptr_t)buffer % 4 == 0) && (read_len % 4 == 0)) { + // If everything is word-aligned, do a faster memcpy + memcpy(buffer, (void *)dev->data_buf, read_len); + } else { + // Otherwise, slow(er) path copies word by word + int copy_len = read_len; + for (int i = 0; i < (read_len + 3) / 4; i++) { + int word_len = MIN(sizeof(uint32_t), copy_len); + uint32_t word = dev->data_buf[i]; + memcpy(buffer, &word, word_len); + buffer = (void *)((intptr_t)buffer + word_len); + copy_len -= word_len; + } + } +} + +/** + * Write a word to the data buffer. + * + * @param dev Beginning address of the peripheral registers. + * @param word Data to write at address 0. + */ +static inline void gpspi_flash_ll_write_word(spi_dev_t *dev, uint32_t word) +{ + dev->data_buf[0] = word; +} + +/** + * Set the data to be written in the data buffer. + * + * @param dev Beginning address of the peripheral registers. + * @param buffer Buffer holding the data + * @param length Length of data in bytes. + */ +static inline void gpspi_flash_ll_set_buffer_data(spi_dev_t *dev, const void *buffer, uint32_t length) +{ + // Load data registers, word at a time + int num_words = (length + 3) / 4; + for (int i = 0; i < num_words; i++) { + uint32_t word = 0; + uint32_t word_len = MIN(length, sizeof(word)); + memcpy(&word, buffer, word_len); + dev->data_buf[i] = word; + length -= word_len; + buffer = (void *)((intptr_t)buffer + word_len); + } +} + +/** + * Trigger a user defined transaction. All phases, including command, address, dummy, and the data phases, + * should be configured before this is called. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void gpspi_flash_ll_user_start(spi_dev_t *dev) +{ + dev->ctrl.hold_pol = 1; + dev->cmd.update = 1; + while (dev->cmd.update); + dev->cmd.usr = 1; +} + +/** + * Check whether the host is idle to perform new commands. + * + * @param dev Beginning address of the peripheral registers. + * + * @return true if the host is idle, otherwise false + */ +static inline bool gpspi_flash_ll_host_idle(const spi_dev_t *dev) +{ + return dev->cmd.usr == 0; +} + +/** + * Set phases for user-defined transaction to read + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void gpspi_flash_ll_read_phase(spi_dev_t *dev) +{ + typeof (dev->user) user = { + .usr_command = 1, + .usr_mosi = 0, + .usr_miso = 1, + .usr_addr = 1, + }; + dev->user = user; +} +/*------------------------------------------------------------------------------ + * Configs + *----------------------------------------------------------------------------*/ +/** + * Select which pin to use for the flash + * + * @param dev Beginning address of the peripheral registers. + * @param pin Pin ID to use, 0-2. Set to other values to disable all the CS pins. + */ +static inline void gpspi_flash_ll_set_cs_pin(spi_dev_t *dev, int pin) +{ + dev->misc.cs0_dis = (pin == 0) ? 0 : 1; + dev->misc.cs1_dis = (pin == 1) ? 0 : 1; +} + +/** + * Set the read io mode. + * + * @param dev Beginning address of the peripheral registers. + * @param read_mode I/O mode to use in the following transactions. + */ +static inline void gpspi_flash_ll_set_read_mode(spi_dev_t *dev, esp_flash_io_mode_t read_mode) +{ + typeof (dev->ctrl) ctrl = dev->ctrl; + typeof (dev->user) user = dev->user; + + ctrl.val &= ~(SPI_FCMD_QUAD_M | SPI_FADDR_QUAD_M | SPI_FREAD_QUAD_M | SPI_FCMD_DUAL_M | SPI_FADDR_DUAL_M | SPI_FREAD_DUAL_M); + user.val &= ~(SPI_FWRITE_QUAD_M | SPI_FWRITE_DUAL_M); + + switch (read_mode) { + case SPI_FLASH_FASTRD: + //the default option + case SPI_FLASH_SLOWRD: + break; + case SPI_FLASH_QIO: + ctrl.fread_quad = 1; + ctrl.faddr_quad = 1; + user.fwrite_quad = 1; + break; + case SPI_FLASH_QOUT: + ctrl.fread_quad = 1; + user.fwrite_quad = 1; + break; + case SPI_FLASH_DIO: + ctrl.fread_dual = 1; + ctrl.faddr_dual = 1; + user.fwrite_dual = 1; + break; + case SPI_FLASH_DOUT: + ctrl.fread_dual = 1; + user.fwrite_dual = 1; + break; + default: + abort(); + } + + dev->ctrl = ctrl; + dev->user = user; +} + +/** + * Set clock frequency to work at. + * + * @param dev Beginning address of the peripheral registers. + * @param clock_val pointer to the clock value to set + */ +static inline void gpspi_flash_ll_set_clock(spi_dev_t *dev, gpspi_flash_ll_clock_reg_t *clock_val) +{ + dev->clock = *clock_val; +} + +/** + * Set the input length, in bits. + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of input, in bits. + */ +static inline void gpspi_flash_ll_set_miso_bitlen(spi_dev_t *dev, uint32_t bitlen) +{ + dev->user.usr_miso = bitlen > 0; + if (bitlen) { + dev->ms_dlen.ms_data_bitlen = bitlen - 1; + } +} + +/** + * Set the output length, in bits (not including command, address and dummy + * phases) + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of output, in bits. + */ +static inline void gpspi_flash_ll_set_mosi_bitlen(spi_dev_t *dev, uint32_t bitlen) +{ + dev->user.usr_mosi = bitlen > 0; + if (bitlen) { + dev->ms_dlen.ms_data_bitlen = bitlen - 1; + } +} + +/** + * Set the command. + * + * @param dev Beginning address of the peripheral registers. + * @param command Command to send + * @param bitlen Length of the command + */ +static inline void gpspi_flash_ll_set_command(spi_dev_t *dev, uint8_t command, uint32_t bitlen) +{ + dev->user.usr_command = 1; + typeof(dev->user2) user2 = { + .usr_command_value = command, + .usr_command_bitlen = (bitlen - 1), + }; + dev->user2 = user2; +} + +/** + * Get the address length that is set in register, in bits. + * + * @param dev Beginning address of the peripheral registers. + * + */ +static inline int gpspi_flash_ll_get_addr_bitlen(spi_dev_t *dev) +{ + return dev->user.usr_addr ? dev->user1.usr_addr_bitlen + 1 : 0; +} + +/** + * Set the address length to send, in bits. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of the address, in bits + */ +static inline void gpspi_flash_ll_set_addr_bitlen(spi_dev_t *dev, uint32_t bitlen) +{ + dev->user1.usr_addr_bitlen = (bitlen - 1); + dev->user.usr_addr = bitlen ? 1 : 0; +} + +/** + * Set the address to send in user mode. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param addr Address to send + */ +static inline void gpspi_flash_ll_set_usr_address(spi_dev_t *dev, uint32_t addr, uint32_t bitlen) +{ + // The blank region should be all ones + uint32_t padding_ones = (bitlen == 32? 0 : UINT32_MAX >> bitlen); + dev->addr = (addr << (32 - bitlen)) | padding_ones; +} + +/** + * Set the address to send. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param addr Address to send + */ +static inline void gpspi_flash_ll_set_address(spi_dev_t *dev, uint32_t addr) +{ + dev->addr = addr; +} + +/** + * Set the length of dummy cycles. + * + * @param dev Beginning address of the peripheral registers. + * @param dummy_n Cycles of dummy phases + */ +static inline void gpspi_flash_ll_set_dummy(spi_dev_t *dev, uint32_t dummy_n) +{ + dev->user.usr_dummy = dummy_n ? 1 : 0; + dev->user1.usr_dummy_cyclelen = dummy_n - 1; +} + +/** + * Set D/Q output level during dummy phase + * + * @param dev Beginning address of the peripheral registers. + * @param out_en whether to enable IO output for dummy phase + * @param out_level dummy output level + */ +static inline void gpspi_flash_ll_set_dummy_out(spi_dev_t *dev, uint32_t out_en, uint32_t out_lev) +{ + dev->ctrl.dummy_out = out_en; + dev->ctrl.q_pol = out_lev; + dev->ctrl.d_pol = out_lev; +} + +/** + * Set extra hold time of CS after the clocks. + * + * @param dev Beginning address of the peripheral registers. + * @param hold_n Cycles of clocks before CS is inactive + */ +static inline void gpspi_flash_ll_set_hold(spi_dev_t *dev, uint32_t hold_n) +{ + dev->user1.cs_hold_time = hold_n - 1; + dev->user.cs_hold = (hold_n > 0? 1: 0); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_hal.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_hal.h new file mode 100644 index 00000000..e8e29d07 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_hal.h @@ -0,0 +1,109 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use it in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The HMAC peripheral can be configured to deliver its output to the user directly, or to deliver + * the output directly to another peripheral instead, e.g. the Digital Signature peripheral. + */ +typedef enum { + HMAC_OUTPUT_USER = 0, /**< Let user provide a message and read the HMAC result */ + HMAC_OUTPUT_DS = 1, /**< HMAC is provided to the DS peripheral to decrypt DS private key parameters */ + HMAC_OUTPUT_JTAG_ENABLE = 2, /**< HMAC is used to enable JTAG after soft-disabling it */ + HMAC_OUTPUT_ALL = 3 /**< HMAC is used for both as DS input for or enabling JTAG */ +} hmac_hal_output_t; + +/** + * @brief Make the peripheral ready for use. + * + * This triggers any further steps necessary after enabling the device + */ +void hmac_hal_start(void); + +/** + * @brief Configure which hardware key slot should be used and configure the target of the HMAC output. + * + * @note Writing out-of-range values is undefined behavior. The user has to ensure that the parameters are in range. + * + * @param config The target of the HMAC. Possible targets are described in \c hmac_hal_output_t. + * See the ESP32C3 TRM for more details. + * @param key_id The ID of the hardware key slot to be used. + * + * @return 0 if the configuration was successful, non-zero if not. + * An unsuccessful configuration means that the purpose value in the eFuse of the corresponding key slot + * doesn't match to supplied value of \c config. + */ +uint32_t hmac_hal_configure(hmac_hal_output_t config, uint32_t key_id); + +/** + * @brief Write a padded single-block message of 512 bits to the HMAC peripheral. + * + * The message must not be longer than one block (512 bits) and the padding has to be applied by software before + * writing. The padding has to be able to fit into the block after the message. + * For more information on HMAC padding, see the ESP32C3 TRM. + */ +void hmac_hal_write_one_block_512(const void *block); + +/** + * @brief Write a message block of 512 bits to the HMAC peripheral. + * + * This function must be used incombination with \c hmac_hal_next_block_normal() or \c hmac_hal_next_block_padding(). + * The first message block is written without any prerequisite. + * All message blocks which are not the last one, need a call to \c hmac_hal_next_block_normal() before, indicating + * to the hardware that a "normal", i.e. non-padded block will follow. This is even the case for a block which begins + * padding already but where the padding doesn't fit in (remaining message size > (block size - padding size)). + * Before writing the last block which contains the padding, a call to \c hmac_hal_next_block_padding() is necessary + * to indicate to the hardware that a block with padding will be written. + * + * For more information on HMAC padding, see the ESP32C3 TRM. + */ +void hmac_hal_write_block_512(const void *block); + +/** + * @brief Indicate to the hardware that a normal block will be written. + */ +void hmac_hal_next_block_normal(void); + +/** + * @brief Indicate to the hardware that a block with padding will be written. + */ +void hmac_hal_next_block_padding(void); + +/** + * @brief Read the 256 bit HMAC result from the hardware. + */ +void hmac_hal_read_result_256(void *result); + +/** + * @brief Clear (invalidate) the HMAC result provided to other hardware. + */ +void hmac_hal_clean(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_ll.h new file mode 100644 index 00000000..8e257a7d --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/hmac_ll.h @@ -0,0 +1,199 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use it in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#include + +#include "soc/system_reg.h" +#include "soc/hwcrypto_reg.h" +#include "hal/hmac_hal.h" + +#define SHA256_BLOCK_SZ 64 +#define SHA256_DIGEST_SZ 32 + +#define EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG 6 +#define EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE 7 +#define EFUSE_KEY_PURPOSE_HMAC_UP 8 +#define EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL 5 + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Makes the peripheral ready for use, after enabling it. + */ +static inline void hmac_ll_start(void) +{ + REG_WRITE(HMAC_SET_START_REG, 1); +} + +/** + * @brief Determine where the HMAC output should go. + * + * The HMAC peripheral can be configured to deliver its output to the user directly, or to deliver + * the output directly to another peripheral instead, e.g. the Digital Signature peripheral. + */ +static inline void hmac_ll_config_output(hmac_hal_output_t config) +{ + switch(config) { + case HMAC_OUTPUT_USER: + REG_WRITE(HMAC_SET_PARA_PURPOSE_REG, EFUSE_KEY_PURPOSE_HMAC_UP); + break; + case HMAC_OUTPUT_DS: + REG_WRITE(HMAC_SET_PARA_PURPOSE_REG, EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE); + break; + case HMAC_OUTPUT_JTAG_ENABLE: + REG_WRITE(HMAC_SET_PARA_PURPOSE_REG, EFUSE_KEY_PURPOSE_HMAC_DOWN_JTAG); + break; + case HMAC_OUTPUT_ALL: + REG_WRITE(HMAC_SET_PARA_PURPOSE_REG, EFUSE_KEY_PURPOSE_HMAC_DOWN_ALL); + break; + default: + ; // do nothing, error will be indicated by hmac_hal_config_error() + } +} + +/** + * @brief Selects which hardware key should be used. + */ +static inline void hmac_ll_config_hw_key_id(uint32_t key_id) +{ + REG_WRITE(HMAC_SET_PARA_KEY_REG, key_id); +} + +/** + * @brief Apply and check configuration. + * + * Afterwards, the configuration can be checked for errors with hmac_hal_config_error(). + */ +static inline void hmac_ll_config_finish(void) +{ + REG_WRITE(HMAC_SET_PARA_FINISH_REG, 1); +} + +/** + * + * @brief Query HMAC error state after configuration actions. + * + * @return + * - 1 or greater on error + * - 0 on success + */ +static inline uint32_t hmac_ll_config_error(void) +{ + return REG_READ(HMAC_QUERY_ERROR_REG); +} + +/** + * Wait until the HAL is ready for the next interaction. + */ +static inline void hmac_ll_wait_idle(void) +{ + uint32_t query; + do { + query = REG_READ(HMAC_QUERY_BUSY_REG); + } while(query != 0); +} + +/** + * @brief Write a message block of 512 bits to the HMAC peripheral. + */ +static inline void hmac_ll_write_block_512(const uint32_t *block) +{ + const size_t REG_WIDTH = sizeof(uint32_t); + for (size_t i = 0; i < SHA256_BLOCK_SZ / REG_WIDTH; i++) { + REG_WRITE(HMAC_WDATA_BASE + (i * REG_WIDTH), block[i]); + } + + REG_WRITE(HMAC_SET_MESSAGE_ONE_REG, 1); +} + +/** + * @brief Read the 256 bit HMAC. + */ +static inline void hmac_ll_read_result_256(uint32_t *result) +{ + const size_t REG_WIDTH = sizeof(uint32_t); + for (size_t i = 0; i < SHA256_DIGEST_SZ / REG_WIDTH; i++) { + result[i] = REG_READ(HMAC_RDATA_BASE + (i * REG_WIDTH)); + } +} + +/** + * @brief Clean the HMAC result provided to other hardware. + */ +static inline void hmac_ll_clean(void) +{ + REG_WRITE(HMAC_SET_INVALIDATE_DS_REG, 1); + REG_WRITE(HMAC_SET_INVALIDATE_JTAG_REG, 1); +} + +/** + * @brief Signals that the following block will be the padded last block. + */ +static inline void hmac_ll_msg_padding(void) +{ + REG_WRITE(HMAC_SET_MESSAGE_PAD_REG, 1); +} + +/** + * @brief Signals that all blocks have been written and a padding block will automatically be applied by hardware. + * + * Only applies if the message length is a multiple of 512 bits. + * See ESP32C3 TRM HMAC chapter for more details. + */ +static inline void hmac_ll_msg_end(void) +{ + REG_WRITE(HMAC_SET_MESSAGE_END_REG, 1); +} + +/** + * @brief The message including padding fits into one block, so no further action needs to be taken. + * + * This is called after the one-block-message has been written. + */ +static inline void hmac_ll_msg_one_block(void) +{ + REG_WRITE(HMAC_ONE_BLOCK_REG, 1); +} + +/** + * @brief Indicate that more blocks will be written after the last block. + */ +static inline void hmac_ll_msg_continue(void) +{ + REG_WRITE(HMAC_SET_MESSAGE_ING_REG, 1); +} + +/** + * @brief Clear the HMAC result. + * + * Use this after reading the HMAC result or if aborting after any of the other steps above. + */ +static inline void hmac_ll_calc_finish(void) +{ + REG_WRITE(HMAC_SET_RESULT_FINISH_REG, 2); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2c_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2c_ll.h new file mode 100644 index 00000000..eb23135e --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2c_ll.h @@ -0,0 +1,913 @@ +// Copyright 2020 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. + +// The LL layer for I2C register operations + +#pragma once +#include "soc/i2c_periph.h" +#include "soc/soc_caps.h" +#include "hal/i2c_types.h" +#include "soc/rtc_cntl_reg.h" +#include "esp_rom_sys.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define I2C_LL_INTR_MASK (0x3fff) /*!< I2C all interrupt bitmap */ + +/** + * @brief I2C hardware cmd register filed. + */ +typedef union { + struct { + uint32_t byte_num: 8, + ack_en: 1, + ack_exp: 1, + ack_val: 1, + op_code: 3, + reserved14: 17, + done: 1; + }; + uint32_t val; +} i2c_hw_cmd_t; + +/** + * @brief I2C interrupt event + */ +typedef enum { + I2C_INTR_EVENT_ERR, + I2C_INTR_EVENT_ARBIT_LOST, /*!< I2C arbition lost event */ + I2C_INTR_EVENT_NACK, /*!< I2C NACK event */ + I2C_INTR_EVENT_TOUT, /*!< I2C time out event */ + I2C_INTR_EVENT_END_DET, /*!< I2C end detected event */ + I2C_INTR_EVENT_TRANS_DONE, /*!< I2C trans done event */ + I2C_INTR_EVENT_RXFIFO_FULL, /*!< I2C rxfifo full event */ + I2C_INTR_EVENT_TXFIFO_EMPTY, /*!< I2C txfifo empty event */ +} i2c_intr_event_t; + +/** + * @brief Data structure for calculating I2C bus timing. + */ +typedef struct { + uint16_t clkm_div; /*!< I2C core clock devider */ + uint16_t scl_low; /*!< I2C scl low period */ + uint16_t scl_high; /*!< I2C scl hight period */ + uint16_t scl_wait_high; /*!< I2C scl wait_high period */ + uint16_t sda_hold; /*!< I2C scl low period */ + uint16_t sda_sample; /*!< I2C sda sample time */ + uint16_t setup; /*!< I2C start and stop condition setup period */ + uint16_t hold; /*!< I2C start and stop condition hold period */ + uint16_t tout; /*!< I2C bus timeout period */ +} i2c_clk_cal_t; + +// I2C operation mode command +#define I2C_LL_CMD_RESTART 6 /*!clkm_div = clkm_div; + clk_cal->scl_low = half_cycle; + // default, scl_wait_high < scl_high + int scl_wait_high = (bus_freq <= 50000) ? 0 : (half_cycle / 8); // compensate the time when freq > 50K + clk_cal->scl_wait_high = scl_wait_high; + clk_cal->scl_high = half_cycle - scl_wait_high; + clk_cal->sda_hold = half_cycle / 4; + // scl_wait_high < sda_sample <= scl_high + clk_cal->sda_sample = half_cycle / 2; + clk_cal->setup = half_cycle; + clk_cal->hold = half_cycle; + //default we set the timeout value to about 10 bus cycles + // log(20*half_cycle)/log(2) = log(half_cycle)/log(2) + log(20)/log(2) + clk_cal->tout = (int)(sizeof(half_cycle) * 8 - __builtin_clz(5 * half_cycle)) + 2; +} + +/** + * @brief Update I2C configuration + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_update(i2c_dev_t *hw) +{ + hw->ctr.conf_upgate = 1; +} + +/** + * @brief Configure the I2C bus timing related register. + * + * @param hw Beginning address of the peripheral registers + * @param bus_cfg Pointer to the data structure holding the register configuration. + * + * @return None + */ +static inline void i2c_ll_set_bus_timing(i2c_dev_t *hw, i2c_clk_cal_t *bus_cfg) +{ + hw->clk_conf.sclk_div_num = bus_cfg->clkm_div - 1; + //scl period + hw->scl_low_period.period = bus_cfg->scl_low - 1; + hw->scl_high_period.period = bus_cfg->scl_high; + //sda sample + hw->sda_hold.time = bus_cfg->sda_hold; + hw->sda_sample.time = bus_cfg->sda_sample; + //setup + hw->scl_rstart_setup.time = bus_cfg->setup; + hw->scl_stop_setup.time = bus_cfg->setup; + //hold + hw->scl_start_hold.time = bus_cfg->hold - 1; + hw->scl_stop_hold.time = bus_cfg->hold; + hw->timeout.time_out_value = bus_cfg->tout; + hw->timeout.time_out_en = 1; +} + +/** + * @brief Reset I2C txFIFO + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_txfifo_rst(i2c_dev_t *hw) +{ + hw->fifo_conf.tx_fifo_rst = 1; + hw->fifo_conf.tx_fifo_rst = 0; +} + +/** + * @brief Reset I2C rxFIFO + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_rxfifo_rst(i2c_dev_t *hw) +{ + hw->fifo_conf.rx_fifo_rst = 1; + hw->fifo_conf.rx_fifo_rst = 0; +} + +/** + * @brief Configure I2C SCL timing + * + * @param hw Beginning address of the peripheral registers + * @param hight_period The I2C SCL hight period (in core clock cycle, hight_period > 2) + * @param low_period The I2C SCL low period (in core clock cycle, low_period > 1) + * + * @return None. + */ +static inline void i2c_ll_set_scl_timing(i2c_dev_t *hw, int hight_period, int low_period) +{ + hw->scl_low_period.period = low_period - 1; + hw->scl_high_period.period = hight_period - 10; + hw->scl_high_period.scl_wait_high_period = hight_period - hw->scl_high_period.period; +} + +/** + * @brief Clear I2C interrupt status + * + * @param hw Beginning address of the peripheral registers + * @param mask Interrupt mask needs to be cleared + * + * @return None + */ +static inline void i2c_ll_clr_intsts_mask(i2c_dev_t *hw, uint32_t mask) +{ + hw->int_clr.val = mask; +} + +/** + * @brief Enable I2C interrupt + * + * @param hw Beginning address of the peripheral registers + * @param mask Interrupt mask needs to be enabled + * + * @return None + */ +static inline void i2c_ll_enable_intr_mask(i2c_dev_t *hw, uint32_t mask) +{ + hw->int_ena.val |= mask; +} + +/** + * @brief Disable I2C interrupt + * + * @param hw Beginning address of the peripheral registers + * @param mask Interrupt mask needs to be disabled + * + * @return None + */ +static inline void i2c_ll_disable_intr_mask(i2c_dev_t *hw, uint32_t mask) +{ + hw->int_ena.val &= (~mask); +} + +/** + * @brief Get I2C interrupt status + * + * @param hw Beginning address of the peripheral registers + * + * @return I2C interrupt status + */ +static inline uint32_t i2c_ll_get_intsts_mask(i2c_dev_t *hw) +{ + return hw->int_status.val; +} + +/** + * @brief Configure I2C memory access mode, FIFO mode or non-FIFO mode + * + * @param hw Beginning address of the peripheral registers + * @param fifo_mode_en Set true to enable FIFO access mode, else, set it false + * + * @return None + */ +static inline void i2c_ll_set_fifo_mode(i2c_dev_t *hw, bool fifo_mode_en) +{ + hw->fifo_conf.nonfifo_en = fifo_mode_en ? 0 : 1; +} + +/** + * @brief Configure I2C timeout + * + * @param hw Beginning address of the peripheral registers + * @param tout_num The I2C timeout value needs to be set (2^tout in core clock cycle) + * + * @return None + */ +static inline void i2c_ll_set_tout(i2c_dev_t *hw, int tout) +{ + hw->timeout.time_out_value = tout; +} + +/** + * @brief Configure I2C slave address + * + * @param hw Beginning address of the peripheral registers + * @param slave_addr I2C slave address needs to be set + * @param addr_10bit_en Set true to enable 10-bit slave address mode, set false to enable 7-bit address mode + * + * @return None + */ +static inline void i2c_ll_set_slave_addr(i2c_dev_t *hw, uint16_t slave_addr, bool addr_10bit_en) +{ + hw->slave_addr.addr = slave_addr; + hw->slave_addr.en_10bit = addr_10bit_en; +} + +/** + * @brief Write I2C hardware command register + * + * @param hw Beginning address of the peripheral registers + * @param cmd I2C hardware command + * @param cmd_idx The index of the command register, should be less than 16 + * + * @return None + */ +static inline void i2c_ll_write_cmd_reg(i2c_dev_t *hw, i2c_hw_cmd_t cmd, int cmd_idx) +{ + hw->command[cmd_idx].val = cmd.val; +} + +/** + * @brief Configure I2C start timing + * + * @param hw Beginning address of the peripheral registers + * @param start_setup The start condition setup period (in core clock cycle) + * @param start_hold The start condition hold period (in core clock cycle) + * + * @return None + */ +static inline void i2c_ll_set_start_timing(i2c_dev_t *hw, int start_setup, int start_hold) +{ + hw->scl_rstart_setup.time = start_setup; + hw->scl_start_hold.time = start_hold - 1; +} + +/** + * @brief Configure I2C stop timing + * + * @param hw Beginning address of the peripheral registers + * @param stop_setup The stop condition setup period (in core clock cycle) + * @param stop_hold The stop condition hold period (in core clock cycle) + * + * @return None + */ +static inline void i2c_ll_set_stop_timing(i2c_dev_t *hw, int stop_setup, int stop_hold) +{ + hw->scl_stop_setup.time = stop_setup; + hw->scl_stop_hold.time = stop_hold; +} + +/** + * @brief Configure I2C stop timing + * + * @param hw Beginning address of the peripheral registers + * @param sda_sample The SDA sample time (in core clock cycle) + * @param sda_hold The SDA hold time (in core clock cycle) + * + * @return None + */ +static inline void i2c_ll_set_sda_timing(i2c_dev_t *hw, int sda_sample, int sda_hold) +{ + hw->sda_hold.time = sda_hold; + hw->sda_sample.time = sda_sample; +} + +/** + * @brief Set I2C txFIFO empty threshold + * + * @param hw Beginning address of the peripheral registers + * @param empty_thr The txFIFO empty threshold + * + * @return None + */ +static inline void i2c_ll_set_txfifo_empty_thr(i2c_dev_t *hw, uint8_t empty_thr) +{ + hw->fifo_conf.tx_fifo_wm_thrhd = empty_thr; +} + +/** + * @brief Set I2C rxFIFO full threshold + * + * @param hw Beginning address of the peripheral registers + * @param full_thr The rxFIFO full threshold + * + * @return None + */ +static inline void i2c_ll_set_rxfifo_full_thr(i2c_dev_t *hw, uint8_t full_thr) +{ + hw->fifo_conf.rx_fifo_wm_thrhd = full_thr; +} + +/** + * @brief Set the I2C data mode, LSB or MSB + * + * @param hw Beginning address of the peripheral registers + * @param tx_mode Tx data bit mode + * @param rx_mode Rx data bit mode + * + * @return None + */ +static inline void i2c_ll_set_data_mode(i2c_dev_t *hw, i2c_trans_mode_t tx_mode, i2c_trans_mode_t rx_mode) +{ + hw->ctr.tx_lsb_first = tx_mode; + hw->ctr.rx_lsb_first = rx_mode; +} + +/** + * @brief Get the I2C data mode + * + * @param hw Beginning address of the peripheral registers + * @param tx_mode Pointer to accept the received bytes mode + * @param rx_mode Pointer to accept the sended bytes mode + * + * @return None + */ +static inline void i2c_ll_get_data_mode(i2c_dev_t *hw, i2c_trans_mode_t *tx_mode, i2c_trans_mode_t *rx_mode) +{ + *tx_mode = hw->ctr.tx_lsb_first; + *rx_mode = hw->ctr.rx_lsb_first; +} + +/** + * @brief Get I2C sda timing configuration + * + * @param hw Beginning address of the peripheral registers + * @param sda_sample Pointer to accept the SDA sample timing configuration + * @param sda_hold Pointer to accept the SDA hold timing configuration + * + * @return None + */ +static inline void i2c_ll_get_sda_timing(i2c_dev_t *hw, int *sda_sample, int *sda_hold) +{ + *sda_hold = hw->sda_hold.time; + *sda_sample = hw->sda_sample.time; +} + +/** + * @brief Get the I2C hardware version + * + * @param hw Beginning address of the peripheral registers + * + * @return The I2C hardware version + */ +static inline uint32_t i2c_ll_get_hw_version(i2c_dev_t *hw) +{ + return hw->date; +} + +/** + * @brief Check if the I2C bus is busy + * + * @param hw Beginning address of the peripheral registers + * + * @return True if I2C state machine is busy, else false will be returned + */ +static inline bool i2c_ll_is_bus_busy(i2c_dev_t *hw) +{ + return hw->sr.bus_busy; +} + +/** + * @brief Check if I2C is master mode + * + * @param hw Beginning address of the peripheral registers + * + * @return True if I2C is master mode, else false will be returned + */ +static inline bool i2c_ll_is_master_mode(i2c_dev_t *hw) +{ + return hw->ctr.ms_mode; +} + +/** + * @brief Get the rxFIFO readable length + * + * @param hw Beginning address of the peripheral registers + * + * @return RxFIFO readable length + */ +static inline uint32_t i2c_ll_get_rxfifo_cnt(i2c_dev_t *hw) +{ + return hw->sr.rx_fifo_cnt; +} + +/** + * @brief Get I2C txFIFO writable length + * + * @param hw Beginning address of the peripheral registers + * + * @return TxFIFO writable length + */ +static inline uint32_t i2c_ll_get_txfifo_len(i2c_dev_t *hw) +{ + return SOC_I2C_FIFO_LEN - hw->sr.tx_fifo_cnt; +} + +/** + * @brief Get I2C timeout configuration + * + * @param hw Beginning address of the peripheral registers + * + * @return The I2C timeout value + */ +static inline uint32_t i2c_ll_get_tout(i2c_dev_t *hw) +{ + return hw->timeout.time_out_value; +} + +/** + * @brief Start I2C transfer + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_trans_start(i2c_dev_t *hw) +{ + hw->ctr.trans_start = 1; +} + +/** + * @brief Get I2C start timing configuration + * + * @param hw Beginning address of the peripheral registers + * @param setup_time Pointer to accept the start condition setup period + * @param hold_time Pointer to accept the start condition hold period + * + * @return None + */ +static inline void i2c_ll_get_start_timing(i2c_dev_t *hw, int *setup_time, int *hold_time) +{ + *setup_time = hw->scl_rstart_setup.time; + *hold_time = hw->scl_start_hold.time + 1; +} + +/** + * @brief Get I2C stop timing configuration + * + * @param hw Beginning address of the peripheral registers + * @param setup_time Pointer to accept the stop condition setup period + * @param hold_time Pointer to accept the stop condition hold period + * + * @return None + */ +static inline void i2c_ll_get_stop_timing(i2c_dev_t *hw, int *setup_time, int *hold_time) +{ + *setup_time = hw->scl_stop_setup.time; + *hold_time = hw->scl_stop_hold.time; +} + +/** + * @brief Get I2C SCL timing configuration + * + * @param hw Beginning address of the peripheral registers + * @param high_period Pointer to accept the SCL high period + * @param low_period Pointer to accept the SCL low period + * + * @return None + */ +static inline void i2c_ll_get_scl_timing(i2c_dev_t *hw, int *high_period, int *low_period) +{ + *high_period = hw->scl_high_period.period + hw->scl_high_period.scl_wait_high_period; + *low_period = hw->scl_low_period.period + 1; +} + +/** + * @brief Write the I2C hardware txFIFO + * + * @param hw Beginning address of the peripheral registers + * @param ptr Pointer to data buffer + * @param len Amount of data needs to be writen + * + * @return None. + */ +static inline void i2c_ll_write_txfifo(i2c_dev_t *hw, uint8_t *ptr, uint8_t len) +{ + for (int i = 0; i< len; i++) { + hw->fifo_data.data = ptr[i]; + } +} + +/** + * @brief Read the I2C hardware rxFIFO + * + * @param hw Beginning address of the peripheral registers + * @param ptr Pointer to data buffer + * @param len Amount of data needs read + * + * @return None + */ +static inline void i2c_ll_read_rxfifo(i2c_dev_t *hw, uint8_t *ptr, uint8_t len) +{ + for(int i = 0; i < len; i++) { + ptr[i] = hw->fifo_data.data; + } +} + +/** + * @brief Configure I2C hardware filter + * + * @param hw Beginning address of the peripheral registers + * @param filter_num If the glitch period on the line is less than this value, it can be filtered out + * If `filter_num == 0`, the filter will be disabled + * + * @return None + */ +static inline void i2c_ll_set_filter(i2c_dev_t *hw, uint8_t filter_num) +{ + if (filter_num > 0) { + hw->filter_cfg.scl_thres = filter_num; + hw->filter_cfg.sda_thres = filter_num; + hw->filter_cfg.scl_en = 1; + hw->filter_cfg.sda_en = 1; + } else { + hw->filter_cfg.scl_en = 0; + hw->filter_cfg.sda_en = 0; + } +} + +/** + * @brief Get I2C hardware filter configuration + * + * @param hw Beginning address of the peripheral registers + * + * @return The hardware filter configuration + */ +static inline uint8_t i2c_ll_get_filter(i2c_dev_t *hw) +{ + return hw->filter_cfg.scl_thres; +} + +/** + * @brief Enable I2C master TX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_enable_tx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = ~0; + hw->int_ena.val = I2C_LL_MASTER_TX_INT; +} + +/** + * @brief Enable I2C master RX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_enable_rx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = ~0; + hw->int_ena.val = I2C_LL_MASTER_RX_INT; +} + +/** + * @brief Disable I2C master TX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_disable_tx_it(i2c_dev_t *hw) +{ + hw->int_ena.val &= (~I2C_LL_MASTER_TX_INT); +} + +/** + * @brief Disable I2C master RX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_disable_rx_it(i2c_dev_t *hw) +{ + hw->int_ena.val &= (~I2C_LL_MASTER_RX_INT); +} + +/** + * @brief Clear I2C master TX interrupt status register + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_clr_tx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = I2C_LL_MASTER_TX_INT; +} + +/** + * @brief Clear I2C master RX interrupt status register + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_clr_rx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = I2C_LL_MASTER_RX_INT; +} + +/** + * @brief + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_enable_tx_it(i2c_dev_t *hw) +{ + hw->int_ena.val |= I2C_LL_SLAVE_TX_INT; +} + +/** + * @brief Enable I2C slave RX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_enable_rx_it(i2c_dev_t *hw) +{ + hw->int_ena.val |= I2C_LL_SLAVE_RX_INT; +} + +/** + * @brief Disable I2C slave TX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_disable_tx_it(i2c_dev_t *hw) +{ + hw->int_ena.val &= (~I2C_LL_SLAVE_TX_INT); +} + +/** + * @brief Disable I2C slave RX interrupt + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_disable_rx_it(i2c_dev_t *hw) +{ + hw->int_ena.val &= (~I2C_LL_SLAVE_RX_INT); +} + +/** + * @brief Clear I2C slave TX interrupt status register + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_clr_tx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = I2C_LL_SLAVE_TX_INT; +} + +/** + * @brief Clear I2C slave RX interrupt status register. + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_clr_rx_it(i2c_dev_t *hw) +{ + hw->int_clr.val = I2C_LL_SLAVE_RX_INT; +} + +/** + * @brief Reste I2C master FSM. When the master FSM is stuck, call this function to reset the FSM + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_fsm_rst(i2c_dev_t *hw) +{ + hw->ctr.fsm_rst = 1; +} + +/** + * @brief Clear I2C bus, when the slave is stuck in a deadlock and keeps pulling the bus low, + * master can controls the SCL bus to generate 9 CLKs. + * + * Note: The master cannot detect if deadlock happens, but when the scl_st_to interrupt is generated, a deadlock may occur. + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_clr_bus(i2c_dev_t *hw) +{ + hw->scl_sp_conf.scl_rst_slv_num = 9; + hw->scl_sp_conf.scl_rst_slv_en = 0; + hw->ctr.conf_upgate = 1; + hw->scl_sp_conf.scl_rst_slv_en = 1; +} + +/** + * @brief Set I2C source clock + * + * @param hw Beginning address of the peripheral registers + * @param src_clk Source clock of the I2C + * + * @return None + */ +static inline void i2c_ll_set_source_clk(i2c_dev_t *hw, i2c_sclk_t src_clk) +{ + // rtc_clk needs to switch on. + if (src_clk == I2C_SCLK_RTC) { + SET_PERI_REG_MASK(RTC_CNTL_CLK_CONF_REG, RTC_CNTL_DIG_CLK8M_EN_M); + esp_rom_delay_us(DELAY_RTC_CLK_SWITCH); + } + // src_clk : (1) for RTC_CLK, (0) for XTAL + hw->clk_conf.sclk_sel = (src_clk == I2C_SCLK_RTC) ? 1 : 0; +} + +/** + * @brief Get I2C master interrupt event + * + * @param hw Beginning address of the peripheral registers + * @param event Pointer to accept the interrupt event + * + * @return None + */ +static inline void i2c_ll_master_get_event(i2c_dev_t *hw, i2c_intr_event_t *event) +{ + typeof(hw->int_status) int_sts = hw->int_status; + if (int_sts.arbitration_lost) { + *event = I2C_INTR_EVENT_ARBIT_LOST; + } else if (int_sts.nack) { + *event = I2C_INTR_EVENT_NACK; + } else if (int_sts.time_out) { + *event = I2C_INTR_EVENT_TOUT; + } else if (int_sts.end_detect) { + *event = I2C_INTR_EVENT_END_DET; + } else if (int_sts.trans_complete) { + *event = I2C_INTR_EVENT_TRANS_DONE; + } else { + *event = I2C_INTR_EVENT_ERR; + } +} + +/** + * @brief Get I2C slave interrupt event + * + * @param hw Beginning address of the peripheral registers + * @param event Pointer to accept the interrupt event + * + * @return None + */ +static inline void i2c_ll_slave_get_event(i2c_dev_t *hw, i2c_intr_event_t *event) +{ + typeof(hw->int_status) int_sts = hw->int_status; + if (int_sts.tx_fifo_wm) { + *event = I2C_INTR_EVENT_TXFIFO_EMPTY; + } else if (int_sts.trans_complete) { + *event = I2C_INTR_EVENT_TRANS_DONE; + } else if (int_sts.rx_fifo_wm) { + *event = I2C_INTR_EVENT_RXFIFO_FULL; + } else { + *event = I2C_INTR_EVENT_ERR; + } +} + +/** + * @brief Init I2C master + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_master_init(i2c_dev_t *hw) +{ + typeof(hw->ctr) ctrl_reg; + ctrl_reg.val = 0; + ctrl_reg.ms_mode = 1; + ctrl_reg.clk_en = 1; + ctrl_reg.sda_force_out = 1; + ctrl_reg.scl_force_out = 1; + hw->ctr.val = ctrl_reg.val; +} + +/** + * @brief Init I2C slave + * + * @param hw Beginning address of the peripheral registers + * + * @return None + */ +static inline void i2c_ll_slave_init(i2c_dev_t *hw) +{ + typeof(hw->ctr) ctrl_reg; + ctrl_reg.val = 0; + ctrl_reg.sda_force_out = 1; + ctrl_reg.scl_force_out = 1; + hw->ctr.val = ctrl_reg.val; + hw->fifo_conf.fifo_addr_cfg_en = 0; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2s_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2s_ll.h new file mode 100644 index 00000000..4a6042cf --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/i2s_ll.h @@ -0,0 +1,912 @@ +// Copyright 2015-2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The LL layer for ESP32-S3 I2S register operations + +#pragma once + +#include +#include +#include "soc/i2s_periph.h" +#include "hal/i2s_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Get I2S hardware instance with giving i2s num +#define I2S_LL_GET_HW(num) (((num) == 0) ? (&I2S0) : NULL) + +#define I2S_INTR_IN_SUC_EOF BIT(9) +#define I2S_INTR_OUT_EOF BIT(12) +#define I2S_INTR_IN_DSCR_ERR BIT(13) +#define I2S_INTR_OUT_DSCR_ERR BIT(14) +#define I2S_INTR_MAX (0xFFFFFFFF) + +/** + * @brief Reset rx fifo + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_rx_fifo(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Reset tx fifo + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_tx_fifo(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Enable rx interrupt + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_enable_rx_intr(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Disable rx interrupt + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_disable_rx_intr(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Disable tx interrupt + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_disable_tx_intr(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Enable tx interrupt + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_enable_tx_intr(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Reset dma in + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_dma_in(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Reset dma out + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_dma_out(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Reset tx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_tx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Reset rx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_reset_rx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + + +} + +/** + * @brief Start out link + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_start_out_link(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Start tx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_start_tx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Start in link + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_start_in_link(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Start rx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_start_rx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Stop out link + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_stop_out_link(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Stop tx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_stop_tx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Stop in link + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_stop_in_link(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Stop rx + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_stop_rx(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Enable dma + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_enable_dma(i2s_dev_t *hw) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // //Enable and configure DMA + // typeof(hw->lc_conf) lc_conf; + // lc_conf.val = 0; + // lc_conf.out_eof_mode = 1; + +} + +/** + * @brief Get I2S interrupt status + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get interrupt status + */ +static inline void i2s_ll_get_intr_status(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->int_st.val; +} + +/** + * @brief Clear I2S interrupt status + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to clear interrupt status + */ +static inline void i2s_ll_clear_intr_status(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Get I2S out eof des address + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get out eof des address + */ +static inline void i2s_ll_get_out_eof_des_addr(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->out_eof_des_addr; +} + +/** + * @brief Get I2S in eof des address + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get in eof des address + */ +static inline void i2s_ll_get_in_eof_des_addr(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->in_eof_des_addr; +} + +/** + * @brief Get I2S tx fifo mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get tx fifo mode + */ +static inline void i2s_ll_get_tx_fifo_mod(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->fifo_conf.tx_fifo_mod; +} + +/** + * @brief Set I2S tx fifo mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx fifo mode + */ +static inline void i2s_ll_set_tx_fifo_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Get I2S rx fifo mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get rx fifo mode + */ +static inline void i2s_ll_get_rx_fifo_mod(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->fifo_conf.rx_fifo_mod; +} + +/** + * @brief Set I2S rx fifo mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx fifo mode + */ +static inline void i2s_ll_set_rx_fifo_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx chan mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx chan mode + */ +static inline void i2s_ll_set_tx_chan_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx chan mode + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx chan mode + */ +static inline void i2s_ll_set_rx_chan_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S out link address + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set out link address + */ +static inline void i2s_ll_set_out_link_addr(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S in link address + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set in link address + */ +static inline void i2s_ll_set_in_link_addr(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx eof num + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx eof num + */ +static inline void i2s_ll_set_rx_eof_num(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Get I2S tx pdm fp + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get tx pdm fp + */ +static inline void i2s_ll_get_tx_pdm_fp(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->pdm_freq_conf.tx_pdm_fp; +} + +/** + * @brief Get I2S tx pdm fs + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get tx pdm fs + */ +static inline void i2s_ll_get_tx_pdm_fs(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->pdm_freq_conf.tx_pdm_fs; +} + +/** + * @brief Set I2S tx pdm fp + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx pdm fp + */ +static inline void i2s_ll_set_tx_pdm_fp(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx pdm fs + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx pdm fs + */ +static inline void i2s_ll_set_tx_pdm_fs(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Get I2S rx sinc dsr 16 en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get rx sinc dsr 16 en + */ +static inline void i2s_ll_get_rx_sinc_dsr_16_en(i2s_dev_t *hw, bool *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->pdm_conf.rx_sinc_dsr_16_en; +} + +/** + * @brief Set I2S clkm div num + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set clkm div num + */ +static inline void i2s_ll_set_clkm_div_num(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S clkm div b + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set clkm div b + */ +static inline void i2s_ll_set_clkm_div_b(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S clkm div a + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set clkm div a + */ +static inline void i2s_ll_set_clkm_div_a(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx bck div num + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx bck div num + */ +static inline void i2s_ll_set_tx_bck_div_num(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx bck div num + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx bck div num + */ +static inline void i2s_ll_set_rx_bck_div_num(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S clk sel + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set clk sel + */ +static inline void i2s_ll_set_clk_sel(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx bits mod + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx bits mod + */ +static inline void i2s_ll_set_tx_bits_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx bits mod + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx bits mod + */ +static inline void i2s_ll_set_rx_bits_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx sinc dsr 16 en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx sinc dsr 16 en + */ +static inline void i2s_ll_set_rx_sinc_dsr_16_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S dscr en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set dscr en + */ +static inline void i2s_ll_set_dscr_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S lcd en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set lcd en + */ +static inline void i2s_ll_set_lcd_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S camera en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set camera en + */ +static inline void i2s_ll_set_camera_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S pcm2pdm conv en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set pcm2pdm conv en + */ +static inline void i2s_ll_set_pcm2pdm_conv_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S TX to MSB Alignment Standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_tx_format_msb_align(i2s_dev_t *hw) +{ +} + + +static inline void i2s_ll_set_rx_format_msb_align(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S TX to PCM long standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_tx_pcm_long(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S RX to PCM long standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_rx_pcm_long(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S RX to PCM short standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_rx_pcm_short(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S RX to philip standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_rx_format_philip(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S TX to PCM short standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_tx_pcm_short(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S TX to philip standard + * + * @param hw Peripheral I2S hardware instance address. + */ +static inline void i2s_ll_set_tx_format_philip(i2s_dev_t *hw) +{ +} + +/** + * @brief Set I2S pdm2pcm conv en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set pdm2pcm conv en + */ +static inline void i2s_ll_set_pdm2pcm_conv_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx pdm en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx pdm en + */ +static inline void i2s_ll_set_rx_pdm_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx pdm en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx pdm en + */ +static inline void i2s_ll_set_tx_pdm_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx fifo mod force en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx fifo mod force en + */ +static inline void i2s_ll_set_tx_fifo_mod_force_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx fifo mod force en + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx fifo mod force en + */ +static inline void i2s_ll_set_rx_fifo_mod_force_en(i2s_dev_t *hw, bool val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx right first + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx right first + */ +static inline void i2s_ll_set_tx_right_first(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx right first + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx right first + */ +static inline void i2s_ll_set_rx_right_first(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx slave mod + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx slave mod + */ +static inline void i2s_ll_set_tx_slave_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx slave mod + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx slave mod + */ +static inline void i2s_ll_set_rx_slave_mod(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Get I2S tx msb right + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get tx msb right + */ +static inline void i2s_ll_get_tx_msb_right(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->conf.tx_msb_right; +} + +/** + * @brief Get I2S rx msb right + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to get rx msb right + */ +static inline void i2s_ll_get_rx_msb_right(i2s_dev_t *hw, uint32_t *val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + // *val = hw->conf.rx_msb_right; +} + +/** + * @brief Set I2S tx msb right + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx msb right + */ +static inline void i2s_ll_set_tx_msb_right(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx msb right + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx msb right + */ +static inline void i2s_ll_set_rx_msb_right(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx mono + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx mono + */ +static inline void i2s_ll_set_tx_mono(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S rx mono + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set rx mono + */ +static inline void i2s_ll_set_rx_mono(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S tx sinc osr2 + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set tx sinc osr2 + */ +static inline void i2s_ll_set_tx_sinc_osr2(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +/** + * @brief Set I2S sig loopback + * + * @param hw Peripheral I2S hardware instance address. + * @param val value to set sig loopback + */ +static inline void i2s_ll_set_sig_loopback(i2s_dev_t *hw, uint32_t val) +{ + abort(); // TODO ESP32-C3 IDF-2098 + +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/interrupt_controller_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/interrupt_controller_ll.h new file mode 100644 index 00000000..1957e038 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/interrupt_controller_ll.h @@ -0,0 +1,152 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include "soc/soc_caps.h" +#include "soc/soc.h" +#include "soc/interrupt_core0_reg.h" +#include "riscv/interrupt.h" +#include "riscv/csr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief enable interrupts specified by the mask + * + * @param mask bitmask of interrupts that needs to be enabled + */ +static inline void intr_cntrl_ll_enable_interrupts(uint32_t mask) +{ + unsigned old_mstatus = RV_CLEAR_CSR(mstatus, MSTATUS_MIE); + esprv_intc_int_enable(mask); + RV_SET_CSR(mstatus, old_mstatus & MSTATUS_MIE); +} + +/** + * @brief disable interrupts specified by the mask + * + * @param mask bitmask of interrupts that needs to be disabled + */ +static inline void intr_cntrl_ll_disable_interrupts(uint32_t mask) +{ + unsigned old_mstatus = RV_CLEAR_CSR(mstatus, MSTATUS_MIE); + esprv_intc_int_disable(mask); + RV_SET_CSR(mstatus, old_mstatus & MSTATUS_MIE); +} + +/** + * @brief checks if given interrupt number has a valid handler + * + * @param intr interrupt number ranged from 0 to 31 + * @param cpu cpu number ranged betweeen 0 to SOC_CPU_CORES_NUM - 1 + * @return true for valid handler, false otherwise + */ +static inline bool intr_cntrl_ll_has_handler(uint8_t intr, uint8_t cpu) +{ + return intr_handler_get(intr); +} + +/** + * @brief sets interrupt handler and optional argument of a given interrupt number + * + * @param intr interrupt number ranged from 0 to 31 + * @param handler handler invoked when an interrupt occurs + * @param arg optional argument to pass to the handler + */ +static inline void intr_cntrl_ll_set_int_handler(uint8_t intr, interrupt_handler_t handler, void *arg) +{ + intr_handler_set(intr, (void *)handler, arg); +} + +/** + * @brief Gets argument passed to handler of a given interrupt number + * + * @param intr interrupt number ranged from 0 to 31 + * + * @return argument used by handler of passed interrupt number + */ +static inline void *intr_cntrl_ll_get_int_handler_arg(uint8_t intr) +{ + return intr_handler_get_arg(intr); +} + +/** + * @brief Disables interrupts that are not located in iram + * + * @param newmask mask of interrupts TO KEEP ENABLED (note: this is probably a bug, see IDF-2308) + * @return oldmask previous interrupt mask value + */ +static inline uint32_t intr_cntrl_ll_disable_int_mask(uint32_t newmask) +{ + // Disable interrupts in order to atomically update the interrupt enable register + unsigned old_mstatus = RV_CLEAR_CSR(mstatus, MSTATUS_MIE); + + uint32_t old_int_enable = REG_READ(INTERRUPT_CORE0_CPU_INT_ENABLE_REG); + REG_WRITE(INTERRUPT_CORE0_CPU_INT_ENABLE_REG, old_int_enable & newmask); + + RV_SET_CSR(mstatus, old_mstatus & MSTATUS_MIE); + return old_int_enable; +} + +/** + * @brief Enables interrupts that are not located in iram + * + * @param newmask mask of interrupts needs to be enabled + */ +static inline void intr_cntrl_ll_enable_int_mask(uint32_t newmask) +{ + unsigned old_mstatus = RV_CLEAR_CSR(mstatus, MSTATUS_MIE); + esprv_intc_int_enable(newmask); + RV_SET_CSR(mstatus, old_mstatus & MSTATUS_MIE); +} + +/** + * @brief Acknowledge an edge-trigger interrupt by clearing its pending flag + * + * @param intr interrupt number ranged from 0 to 31 + */ +static inline void intr_cntrl_ll_edge_int_acknowledge(int intr) +{ + REG_SET_BIT(INTERRUPT_CORE0_CPU_INT_CLEAR_REG, intr); +} + +/** + * @brief Sets the interrupt level int the interrupt controller. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param level priority between 1 (lowest) to 7 (highest) + */ +static inline void intr_cntrl_ll_set_int_level(int intr, int level) +{ + esprv_intc_int_set_priority(intr, level); +} + +/** + * @brief Set the type of an interrupt in the controller. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param type interrupt type as edge or level triggered + */ +static inline void intr_cntrl_ll_set_int_type(int intr, int_type_t type) +{ + esprv_intc_int_set_type(BIT(intr), type); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ledc_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ledc_ll.h new file mode 100644 index 00000000..eafae904 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/ledc_ll.h @@ -0,0 +1,518 @@ +// Copyright 2020 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. + +// The LL layer for LEDC register operations. +// Note that most of the register operations in this layer are non-atomic operations. + +#pragma once + +#include "hal/ledc_types.h" +#include "soc/ledc_periph.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define LEDC_LL_GET_HW() &LEDC + +/** + * @brief Set LEDC low speed timer clock + * + * @param hw Beginning address of the peripheral registers + * @param slow_clk_sel LEDC low speed timer clock source + * + * @return None + */ +static inline void ledc_ll_set_slow_clk_sel(ledc_dev_t *hw, ledc_slow_clk_sel_t slow_clk_sel) +{ + uint32_t clk_sel_val = 0; + if (slow_clk_sel == LEDC_SLOW_CLK_APB) { + clk_sel_val = 1; + } else if (slow_clk_sel == LEDC_SLOW_CLK_RTC8M) { + clk_sel_val = 2; + } else if (slow_clk_sel == LEDC_SLOW_CLK_XTAL) { + clk_sel_val = 3; + } + hw->conf.apb_clk_sel = clk_sel_val; +} + +/** + * @brief Get LEDC low speed timer clock + * + * @param hw Beginning address of the peripheral registers + * @param slow_clk_sel LEDC low speed timer clock source + * + * @return None + */ +static inline void ledc_ll_get_slow_clk_sel(ledc_dev_t *hw, ledc_slow_clk_sel_t *slow_clk_sel) +{ + uint32_t clk_sel_val = hw->conf.apb_clk_sel; + if (clk_sel_val == 1) { + *slow_clk_sel = LEDC_SLOW_CLK_APB; + } else if (clk_sel_val == 2) { + *slow_clk_sel = LEDC_SLOW_CLK_RTC8M; + } else if (clk_sel_val == 3) { + *slow_clk_sel = LEDC_SLOW_CLK_XTAL; + } +} + +/** + * @brief Update LEDC low speed timer + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +static inline void ledc_ll_ls_timer_update(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.low_speed_update = 1; +} + +/** + * @brief Reset LEDC timer + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +static inline void ledc_ll_timer_rst(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.rst = 1; + hw->timer_group[speed_mode].timer[timer_sel].conf.rst = 0; +} + +/** + * @brief Pause LEDC timer + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +static inline void ledc_ll_timer_pause(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.pause = 1; +} + +/** + * @brief Resume LEDC timer + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +static inline void ledc_ll_timer_resume(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.pause = 0; +} + +/** + * @brief Set LEDC timer clock divider + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clock_divider Timer clock divide value, the timer clock is divided from the selected clock source + * + * @return None + */ +static inline void ledc_ll_set_clock_divider(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t clock_divider) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.clock_divider = clock_divider; +} + +/** + * @brief Get LEDC timer clock divider + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clock_divider Timer clock divide value, the timer clock is divided from the selected clock source + * + * @return None + */ +static inline void ledc_ll_get_clock_divider(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t *clock_divider) +{ + *clock_divider = hw->timer_group[speed_mode].timer[timer_sel].conf.clock_divider; +} + +/** + * @brief Set LEDC timer clock source + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clk_src Timer clock source + * + * @return None + */ +static inline void ledc_ll_set_clock_source(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, ledc_clk_src_t clk_src) +{ + if (clk_src == LEDC_REF_TICK) { + //REF_TICK can only be used when APB is selected. + hw->timer_group[speed_mode].timer[timer_sel].conf.tick_sel = 1; + hw->conf.apb_clk_sel = 1; + } else { + hw->timer_group[speed_mode].timer[timer_sel].conf.tick_sel = 0; + } +} + +/** + * @brief Get LEDC timer clock source + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clk_src Pointer to accept the timer clock source + * + * @return None + */ +static inline void ledc_ll_get_clock_source(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, ledc_clk_src_t *clk_src) +{ + if (hw->timer_group[speed_mode].timer[timer_sel].conf.tick_sel == 1) { + *clk_src = LEDC_REF_TICK; + } else { + *clk_src = LEDC_APB_CLK; + } +} + +/** + * @brief Set LEDC duty resolution + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param duty_resolution Resolution of duty setting in number of bits. The range of duty values is [0, (2**duty_resolution)] + * + * @return None + */ +static inline void ledc_ll_set_duty_resolution(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t duty_resolution) +{ + hw->timer_group[speed_mode].timer[timer_sel].conf.duty_resolution = duty_resolution; +} + +/** + * @brief Get LEDC duty resolution + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param duty_resolution Pointer to accept the resolution of duty setting in number of bits. + * + * @return None + */ +static inline void ledc_ll_get_duty_resolution(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_timer_t timer_sel, uint32_t *duty_resolution) +{ + *duty_resolution = hw->timer_group[speed_mode].timer[timer_sel].conf.duty_resolution; +} + +/** + * @brief Update channel configure when select low speed mode + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * + * @return None + */ +static inline void ledc_ll_ls_channel_update(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num) +{ + hw->channel_group[speed_mode].channel[channel_num].conf0.low_speed_update = 1; +} + +/** + * @brief Get LEDC max duty + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param max_duty Pointer to accept the max duty + * + * @return None + */ +static inline void ledc_ll_get_max_duty(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t *max_duty) +{ + uint32_t timer_sel = hw->channel_group[speed_mode].channel[channel_num].conf0.timer_sel; + *max_duty = (1 << (LEDC.timer_group[speed_mode].timer[timer_sel].conf.duty_resolution)); +} + +/** + * @brief Set LEDC hpoint value + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param hpoint_val LEDC hpoint value(max: 0xfffff) + * + * @return None + */ +static inline void ledc_ll_set_hpoint(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t hpoint_val) +{ + hw->channel_group[speed_mode].channel[channel_num].hpoint.hpoint = hpoint_val; +} + +/** + * @brief Get LEDC hpoint value + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param hpoint_val Pointer to accept the LEDC hpoint value(max: 0xfffff) + * + * @return None + */ +static inline void ledc_ll_get_hpoint(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t *hpoint_val) +{ + *hpoint_val = hw->channel_group[speed_mode].channel[channel_num].hpoint.hpoint; +} + +/** + * @brief Set LEDC the integer part of duty value + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_val LEDC duty value, the range of duty setting is [0, (2**duty_resolution)] + * + * @return None + */ +static inline void ledc_ll_set_duty_int_part(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t duty_val) +{ + hw->channel_group[speed_mode].channel[channel_num].duty.duty = duty_val << 4; +} + +/** + * @brief Get LEDC duty value + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_val Pointer to accept the LEDC duty value + * + * @return None + */ +static inline void ledc_ll_get_duty(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t *duty_val) +{ + *duty_val = (hw->channel_group[speed_mode].channel[channel_num].duty_rd.duty_read >> 4); +} + +/** + * @brief Set LEDC duty change direction + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_direction LEDC duty change direction, increase or decrease + * + * @return None + */ +static inline void ledc_ll_set_duty_direction(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, ledc_duty_direction_t duty_direction) +{ + hw->channel_group[speed_mode].channel[channel_num].conf1.duty_inc = duty_direction; +} + +/** + * @brief Get LEDC duty change direction + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_direction Pointer to accept the LEDC duty change direction, increase or decrease + * + * @return None + */ +static inline void ledc_ll_get_duty_direction(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, ledc_duty_direction_t *duty_direction) +{ + *duty_direction = hw->channel_group[speed_mode].channel[channel_num].conf1.duty_inc; +} + +/** + * @brief Set the number of increased or decreased times + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_num The number of increased or decreased times + * + * @return None + */ +static inline void ledc_ll_set_duty_num(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t duty_num) +{ + hw->channel_group[speed_mode].channel[channel_num].conf1.duty_num = duty_num; +} + +/** + * @brief Set the duty cycles of increase or decrease + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_cycle The duty cycles + * + * @return None + */ +static inline void ledc_ll_set_duty_cycle(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t duty_cycle) +{ + hw->channel_group[speed_mode].channel[channel_num].conf1.duty_cycle = duty_cycle; +} + +/** + * @brief Set the step scale of increase or decrease + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_scale The step scale + * + * @return None + */ +static inline void ledc_ll_set_duty_scale(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t duty_scale) +{ + hw->channel_group[speed_mode].channel[channel_num].conf1.duty_scale = duty_scale; +} + +/** + * @brief Set the output enable + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param sig_out_en The output enable status + * + * @return None + */ +static inline void ledc_ll_set_sig_out_en(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, bool sig_out_en) +{ + hw->channel_group[speed_mode].channel[channel_num].conf0.sig_out_en = sig_out_en; +} + +/** + * @brief Set the duty start + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_start The duty start + * + * @return None + */ +static inline void ledc_ll_set_duty_start(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, bool duty_start) +{ + hw->channel_group[speed_mode].channel[channel_num].conf1.duty_start = duty_start; +} + +/** + * @brief Set output idle level + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param idle_level The output idle level + * + * @return None + */ +static inline void ledc_ll_set_idle_level(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, uint32_t idle_level) +{ + hw->channel_group[speed_mode].channel[channel_num].conf0.idle_lv = idle_level & 0x1; +} + +/** + * @brief Set fade end interrupt enable + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param fade_end_intr_en The fade end interrupt enable status + * + * @return None + */ +static inline void ledc_ll_set_fade_end_intr(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, bool fade_end_intr_en) +{ + uint32_t value = hw->int_ena.val; + uint32_t int_en_base = LEDC_DUTY_CHNG_END_LSCH0_INT_ENA_S; + hw->int_ena.val = fade_end_intr_en ? (value | BIT(int_en_base + channel_num)) : (value & (~(BIT(int_en_base + channel_num)))); +} + +/** + * @brief Get fade end interrupt status + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param intr_status The fade end interrupt status + * + * @return None + */ +static inline void ledc_ll_get_fade_end_intr_status(ledc_dev_t *hw, ledc_mode_t speed_mode, uint32_t *intr_status) +{ + uint32_t value = hw->int_st.val; + uint32_t int_en_base = LEDC_DUTY_CHNG_END_LSCH0_INT_ENA_S; + *intr_status = (value >> int_en_base) & 0xff; +} + +/** + * @brief Clear fade end interrupt status + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * + * @return None + */ +static inline void ledc_ll_clear_fade_end_intr_status(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num) +{ + uint32_t int_en_base = LEDC_DUTY_CHNG_END_LSCH0_INT_ENA_S; + hw->int_clr.val = BIT(int_en_base + channel_num); +} + +/** + * @brief Set timer index of the specified channel + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +static inline void ledc_ll_bind_channel_timer(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, ledc_timer_t timer_sel) +{ + hw->channel_group[speed_mode].channel[channel_num].conf0.timer_sel = timer_sel; +} + +/** + * @brief Get timer index of the specified channel + * + * @param hw Beginning address of the peripheral registers + * @param speed_mode LEDC speed_mode, high-speed mode or low-speed mode + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param timer_sel Pointer to accept the LEDC timer index + * + * @return None + */ +static inline void ledc_ll_get_channel_timer(ledc_dev_t *hw, ledc_mode_t speed_mode, ledc_channel_t channel_num, ledc_timer_t *timer_sel) +{ + *timer_sel = hw->channel_group[speed_mode].channel[channel_num].conf0.timer_sel; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/memprot_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/memprot_ll.h new file mode 100644 index 00000000..127d51b3 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/memprot_ll.h @@ -0,0 +1,446 @@ +// Copyright 2020 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. + +#pragma once + +#include "soc/sensitive_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * === globals ==== + */ +#ifndef SRAM_IRAM_START +#define SRAM_IRAM_START 0x4037C000 +#endif + +#ifndef SRAM_DRAM_START +#define SRAM_DRAM_START 0x3FC7C000 +#endif + +/* ICache size is fixed to 16KB on ESP32-C3 */ +#ifndef ICACHE_SIZE +#define ICACHE_SIZE 0x4000 +#endif + +#ifndef I_D_SRAM_SEGMENT_SIZE +#define I_D_SRAM_SEGMENT_SIZE 0x20000 +#endif + +#ifndef I_D_SRAM_OFFSET +#define I_D_SRAM_OFFSET (SRAM_IRAM_START - SRAM_DRAM_START) +#endif + +/* 2nd stage bootloader iram_loader_seg start address */ +#ifndef SRAM_DRAM_END +#define SRAM_DRAM_END (0x403D0000 - I_D_SRAM_OFFSET) +#endif + +#ifndef SRAM_IRAM_ORG +#define SRAM_IRAM_ORG (SRAM_IRAM_START + ICACHE_SIZE) +#endif + +#ifndef SRAM_DRAM_ORG +#define SRAM_DRAM_ORG (SRAM_DRAM_START + ICACHE_SIZE) +#endif + +#ifndef I_D_SRAM_SIZE +#define I_D_SRAM_SIZE SRAM_DRAM_END - SRAM_DRAM_ORG +#endif + +#define I_D_SPLIT_LINE_SHIFT 0x9 + +#define MAP_DRAM_TO_IRAM(addr) (addr - SRAM_DRAM_START + SRAM_IRAM_START) +#define MAP_IRAM_TO_DRAM(addr) (addr - SRAM_IRAM_START + SRAM_DRAM_START) + + +static inline void memprot_ll_set_iram0_dram0_split_line_lock(bool lock) +{ + REG_WRITE(SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_0_REG, lock ? 1 : 0); +} + +static inline bool memprot_ll_get_iram0_dram0_split_line_lock(void) +{ + return REG_READ(SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_0_REG) == 1; +} + + +/** + * === IRAM0 ==== + */ +//16kB (CACHE) +#define IRAM0_SRAM_LEVEL_0_LOW SRAM_IRAM_START //0x40370000 +#define IRAM0_SRAM_LEVEL_0_HIGH (IRAM0_SRAM_LEVEL_0_LOW + ICACHE_SIZE - 0x1) //0x4037FFFF + +//128kB (LEVEL 1) +#define IRAM0_SRAM_LEVEL_1_LOW (IRAM0_SRAM_LEVEL_0_HIGH + 0x1) //0x40380000 +#define IRAM0_SRAM_LEVEL_1_HIGH (IRAM0_SRAM_LEVEL_1_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x4039FFFF + +//128kB (LEVEL 2) +#define IRAM0_SRAM_LEVEL_2_LOW (IRAM0_SRAM_LEVEL_1_HIGH + 0x1) //0x403A0000 +#define IRAM0_SRAM_LEVEL_2_HIGH (IRAM0_SRAM_LEVEL_2_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x403BFFFF + +//128kB (LEVEL 3) +#define IRAM0_SRAM_LEVEL_3_LOW (IRAM0_SRAM_LEVEL_2_HIGH + 0x1) //0x403C0000 +#define IRAM0_SRAM_LEVEL_3_HIGH (IRAM0_SRAM_LEVEL_3_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x403DFFFF + +//permission bits +#define SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_R 0x1 +#define SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_W 0x2 +#define SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_F 0x4 + +static inline uint32_t memprot_ll_iram0_get_intr_source_num(void) +{ + return ETS_CORE0_IRAM0_PMS_INTR_SOURCE; +} + +/* SPLIT LINE */ + +static inline void memprot_ll_set_iram0_split_line(const void *line_addr, uint32_t sensitive_reg) +{ + uint32_t addr = (uint32_t)line_addr; + assert( addr >= IRAM0_SRAM_LEVEL_1_LOW && addr <= IRAM0_SRAM_LEVEL_3_HIGH ); + + uint32_t category[3] = {0}; + if (addr <= IRAM0_SRAM_LEVEL_1_HIGH) { + category[0] = 0x2; + category[1] = category[2] = 0x3; + } else if (addr >= IRAM0_SRAM_LEVEL_2_LOW && addr <= IRAM0_SRAM_LEVEL_2_HIGH) { + category[1] = 0x2; + category[2] = 0x3; + } else { + category[2] = 0x2; + } + + //category bits are the same for all areas + uint32_t category_bits = + (category[0] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_S) | + (category[1] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_S) | + (category[2] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_S); + + uint32_t conf_addr = ((addr >> I_D_SPLIT_LINE_SHIFT) & SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_V) << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_S; + + uint32_t reg_cfg = conf_addr | category_bits; + + REG_WRITE(sensitive_reg, reg_cfg); +} + +/* can be both IRAM0/DRAM0 address */ +static inline void memprot_ll_set_iram0_split_line_main_I_D(const void *line_addr) +{ + memprot_ll_set_iram0_split_line(line_addr, SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_1_REG); +} + +static inline void memprot_ll_set_iram0_split_line_I_0(const void *line_addr) +{ + memprot_ll_set_iram0_split_line(line_addr, SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_2_REG); +} + +static inline void memprot_ll_set_iram0_split_line_I_1(const void *line_addr) +{ + memprot_ll_set_iram0_split_line(line_addr, SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_3_REG); +} + + +/* PMS */ + +static inline void memprot_ll_iram0_set_pms_lock(bool lock) +{ + REG_WRITE(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_0_REG, lock ? 1 : 0); +} + +static inline bool memprot_ll_iram0_get_pms_lock(void) +{ + return REG_READ(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_0_REG) == 1; +} + +//world_0 permissions +static inline uint32_t memprot_ll_iram0_set_permissions(bool r, bool w, bool x) +{ + uint32_t permissions = 0; + if ( r ) { + permissions |= SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_R; + } + if ( w ) { + permissions |= SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_W; + } + if ( x ) { + permissions |= SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_F; + } + + return permissions; +} + +static inline void memprot_ll_iram0_set_pms_area_0(bool r, bool w, bool x) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_2_REG, SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_0, memprot_ll_iram0_set_permissions(r, w, x)); +} + +static inline void memprot_ll_iram0_set_pms_area_1(bool r, bool w, bool x) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_2_REG, SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_1, memprot_ll_iram0_set_permissions(r, w, x)); +} + +static inline void memprot_ll_iram0_set_pms_area_2(bool r, bool w, bool x) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_2_REG, SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_2, memprot_ll_iram0_set_permissions(r, w, x)); +} + +static inline void memprot_ll_iram0_set_pms_area_3(bool r, bool w, bool x) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_2_REG, SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_3, memprot_ll_iram0_set_permissions(r, w, x)); +} + +/* MONITOR */ + +static inline void memprot_ll_iram0_set_monitor_lock(bool lock) +{ + REG_WRITE(SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_0_REG, lock ? 1 : 0); +} + +static inline bool memprot_ll_iram0_get_monitor_lock(void) +{ + return REG_READ(SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_0_REG) == 1; +} + +static inline void memprot_ll_iram0_set_monitor_en(bool enable) +{ + if ( enable ) { + REG_SET_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_EN ); + } else { + REG_CLR_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_EN ); + } +} + +static inline bool memprot_ll_iram0_get_monitor_en(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_EN ) == 1; +} + +static inline void memprot_ll_iram0_clear_monitor_intr(void) +{ + REG_CLR_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_CLR ); +} + +static inline uint32_t memprot_ll_iram0_get_monitor_status_intr(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_INTR ); +} + +static inline uint32_t memprot_ll_iram0_get_monitor_status_fault_wr(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_STATUS_WR ); +} + +static inline uint32_t memprot_ll_iram0_get_monitor_status_fault_loadstore(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_STATUS_LOADSTORE ); +} + +static inline uint32_t memprot_ll_iram0_get_monitor_status_fault_world(void) +{ + return REG_GET_FIELD( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_STATUS_WORLD ); +} + +static inline uint32_t memprot_ll_iram0_get_monitor_status_fault_addr(void) +{ + return REG_GET_FIELD( SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_IRAM0_PMS_MONITOR_VIOLATE_STATUS_ADDR ); +} + + +/** + * === DRAM0 ==== + */ + +//cache not available from DRAM +#define DRAM0_SRAM_LEVEL_0_LOW SRAM_DRAM_START //0x3FC7C000 +#define DRAM0_SRAM_LEVEL_0_HIGH (DRAM0_SRAM_LEVEL_0_LOW + ICACHE_SIZE - 0x1) //0x3FC7FFFF + +//128kB +#define DRAM0_SRAM_LEVEL_1_LOW (DRAM0_SRAM_LEVEL_0_HIGH + 0x1) //0x3FC80000 +#define DRAM0_SRAM_LEVEL_1_HIGH (DRAM0_SRAM_LEVEL_1_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x3FC9FFFF + +//128kB +#define DRAM0_SRAM_LEVEL_2_LOW (DRAM0_SRAM_LEVEL_1_HIGH + 0x1) //0x3FCA0000 +#define DRAM0_SRAM_LEVEL_2_HIGH (DRAM0_SRAM_LEVEL_2_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x3FCBFFFF + +//128kB +#define DRAM0_SRAM_LEVEL_3_LOW (DRAM0_SRAM_LEVEL_2_HIGH + 0x1) //0x3FCC0000 +#define DRAM0_SRAM_LEVEL_3_HIGH (DRAM0_SRAM_LEVEL_3_LOW + I_D_SRAM_SEGMENT_SIZE - 0x1) //0x3FCDFFFF + +#define SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_W 0x2 +#define SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_R 0x1 + + +static inline uint32_t memprot_ll_dram0_get_intr_source_num(void) +{ + return ETS_CORE0_DRAM0_PMS_INTR_SOURCE; +} + + +/* SPLIT LINE */ + +static inline void memprot_ll_set_dram0_split_line(const void *line_addr, uint32_t sensitive_reg) +{ + uint32_t addr = (uint32_t)line_addr; + assert( addr >= DRAM0_SRAM_LEVEL_1_LOW && addr <= DRAM0_SRAM_LEVEL_3_HIGH ); + + uint32_t category[3] = {0}; + if (addr <= DRAM0_SRAM_LEVEL_1_HIGH) { + category[0] = 0x2; + category[1] = category[2] = 0x3; + } else if (addr >= DRAM0_SRAM_LEVEL_2_LOW && addr <= DRAM0_SRAM_LEVEL_2_HIGH) { + category[1] = 0x2; + category[2] = 0x3; + } else { + category[2] = 0x2; + } + + //category bits are the same for all areas + uint32_t category_bits = + (category[0] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_0_S) | + (category[1] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_1_S) | + (category[2] << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_CATEGORY_2_S); + + uint32_t conf_addr = ((addr >> I_D_SPLIT_LINE_SHIFT) & SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_V) << SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SRAM_SPLITADDR_S; + + uint32_t reg_cfg = conf_addr | category_bits; + + REG_WRITE(sensitive_reg, reg_cfg); +} + +static inline void memprot_ll_set_dram0_split_line_D_0(const void *line_addr) +{ + memprot_ll_set_dram0_split_line(line_addr, SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_2_REG); +} + +static inline void memprot_ll_set_dram0_split_line_D_1(const void *line_addr) +{ + memprot_ll_set_dram0_split_line(line_addr, SENSITIVE_CORE_X_IRAM0_DRAM0_DMA_SPLIT_LINE_CONSTRAIN_3_REG); +} + + +/* PMS */ + +static inline void memprot_ll_dram0_set_pms_lock(bool lock) +{ + REG_WRITE(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_0_REG, lock ? 1 : 0); +} + +static inline bool memprot_ll_dram0_get_pms_lock(void) +{ + return REG_READ(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_0_REG) == 1; +} + +static inline uint32_t memprot_ll_dram0_set_permissions(bool r, bool w) +{ + uint32_t permissions = 0; + if ( r ) { + permissions |= SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_R; + } + if ( w ) { + permissions |= SENSITIVE_CORE_X_IRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_W; + } + + return permissions; +} + +static inline void memprot_ll_dram0_set_pms_area_0(bool r, bool w) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_1_REG, SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_0, memprot_ll_dram0_set_permissions(r, w)); +} + +static inline void memprot_ll_dram0_set_pms_area_1(bool r, bool w) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_1_REG, SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_1, memprot_ll_dram0_set_permissions(r, w)); +} + +static inline void memprot_ll_dram0_set_pms_area_2(bool r, bool w) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_1_REG, SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_2, memprot_ll_dram0_set_permissions(r, w)); +} + +static inline void memprot_ll_dram0_set_pms_area_3(bool r, bool w) +{ + REG_SET_FIELD(SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_1_REG, SENSITIVE_CORE_X_DRAM0_PMS_CONSTRAIN_SRAM_WORLD_0_PMS_3, memprot_ll_dram0_set_permissions(r, w)); +} + + +/* MONITOR */ + +static inline void memprot_ll_dram0_set_monitor_lock(bool lock) +{ + REG_WRITE(SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_0_REG, lock ? 1 : 0); +} + +static inline bool memprot_ll_dram0_get_monitor_lock(void) +{ + return REG_READ(SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_0_REG) == 1; +} + +static inline void memprot_ll_dram0_set_monitor_en(bool enable) +{ + if ( enable ) { + REG_SET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_EN ); + } else { + REG_CLR_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_EN ); + } +} + +static inline bool memprot_ll_dram0_get_monitor_en(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_EN ) == 1; +} + +static inline void memprot_ll_dram0_clear_monitor_intr(void) +{ + REG_CLR_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_1_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_CLR ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_intr(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_INTR ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_fault_lock(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_STATUS_LOCK ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_fault_world(void) +{ + return REG_GET_FIELD( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_STATUS_WORLD ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_fault_addr(void) +{ + return REG_GET_FIELD( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_STATUS_ADDR ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_fault_wr(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_3_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_STATUS_WR ); +} + +static inline uint32_t memprot_ll_dram0_get_monitor_status_fault_byte_en(void) +{ + return REG_GET_BIT( SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_2_REG, SENSITIVE_CORE_0_DRAM0_PMS_MONITOR_VIOLATE_STATUS_BYTEEN ); +} + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mpu_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mpu_ll.h new file mode 100644 index 00000000..cfeec1d6 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mpu_ll.h @@ -0,0 +1,53 @@ +// Copyright 2020 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 + +#include "soc/mpu_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* This LL is currently unused for ESP32-C3 - cleanup is TODO ESP32-C3 IDF-2375 */ + +static inline uint32_t mpu_ll_id_to_addr(int id) +{ + abort(); +} + +static inline void mpu_ll_set_region_rw(uint32_t addr) +{ + abort(); +} + +static inline void mpu_ll_set_region_rwx(uint32_t addr) +{ + abort(); +} + +static inline void mpu_ll_set_region_x(uint32_t addr) +{ + abort(); +} + + +static inline void mpu_ll_set_region_illegal(uint32_t addr) +{ + abort(); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mwdt_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mwdt_ll.h new file mode 100644 index 00000000..c1fd5be9 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/mwdt_ll.h @@ -0,0 +1,254 @@ +// Copyright 2020 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. + +// The LL layer for Timer Group register operations. +// Note that most of the register operations in this layer are non-atomic operations. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/timer_periph.h" +#include "hal/wdt_types.h" +#include "esp_attr.h" + +//Type check wdt_stage_action_t +_Static_assert(WDT_STAGE_ACTION_OFF == TIMG_WDT_STG_SEL_OFF, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_INT == TIMG_WDT_STG_SEL_INT, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_RESET_CPU == TIMG_WDT_STG_SEL_RESET_CPU, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_RESET_SYSTEM == TIMG_WDT_STG_SEL_RESET_SYSTEM, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +//Type check wdt_reset_sig_length_t +_Static_assert(WDT_RESET_SIG_LENGTH_100ns == TIMG_WDT_RESET_LENGTH_100_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_200ns == TIMG_WDT_RESET_LENGTH_200_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_300ns == TIMG_WDT_RESET_LENGTH_300_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_400ns == TIMG_WDT_RESET_LENGTH_400_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_500ns == TIMG_WDT_RESET_LENGTH_500_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_800ns == TIMG_WDT_RESET_LENGTH_800_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_1_6us == TIMG_WDT_RESET_LENGTH_1600_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_3_2us == TIMG_WDT_RESET_LENGTH_3200_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); + +/** + * @brief Enable the MWDT + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void mwdt_ll_enable(timg_dev_t *hw) +{ + hw->wdt_config0.en = 1; +} + +/** + * @brief Disable the MWDT + * + * @param hw Start address of the peripheral registers. + * @note This function does not disable the flashboot mode. Therefore, given that + * the MWDT is disabled using this function, a timeout can still occur + * if the flashboot mode is simultaneously enabled. + */ +FORCE_INLINE_ATTR void mwdt_ll_disable(timg_dev_t *hw) +{ + hw->wdt_config0.en = 0; +} + +/** + * Check if the MWDT is enabled + * + * @param hw Start address of the peripheral registers. + * @return True if the MWDT is enabled, false otherwise + */ +FORCE_INLINE_ATTR bool mwdt_ll_check_if_enabled(timg_dev_t *hw) +{ + return (hw->wdt_config0.en) ? true : false; +} + +/** + * @brief Configure a particular stage of the MWDT + * + * @param hw Start address of the peripheral registers. + * @param stage Which stage to configure + * @param timeout Number of timer ticks for the stage to timeout + * @param behavior What action to take when the stage times out + */ +FORCE_INLINE_ATTR void mwdt_ll_config_stage(timg_dev_t *hw, wdt_stage_t stage, uint32_t timeout, wdt_stage_action_t behavior) +{ + switch (stage) { + case WDT_STAGE0: + hw->wdt_config0.stg0 = behavior; + hw->wdt_config2 = timeout; + break; + case WDT_STAGE1: + hw->wdt_config0.stg1 = behavior; + hw->wdt_config3 = timeout; + break; + case WDT_STAGE2: + hw->wdt_config0.stg2 = behavior; + hw->wdt_config4 = timeout; + break; + case WDT_STAGE3: + hw->wdt_config0.stg3 = behavior; + hw->wdt_config5 = timeout; + break; + default: + break; + } + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Disable a particular stage of the MWDT + * + * @param hw Start address of the peripheral registers. + * @param stage Which stage to disable + */ +FORCE_INLINE_ATTR void mwdt_ll_disable_stage(timg_dev_t *hw, uint32_t stage) +{ + switch (stage) { + case WDT_STAGE0: + hw->wdt_config0.stg0 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE1: + hw->wdt_config0.stg1 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE2: + hw->wdt_config0.stg2 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE3: + hw->wdt_config0.stg3 = WDT_STAGE_ACTION_OFF; + break; + default: + break; + } + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Set the length of the CPU reset action + * + * @param hw Start address of the peripheral registers. + * @param length Length of CPU reset signal + */ +FORCE_INLINE_ATTR void mwdt_ll_set_cpu_reset_length(timg_dev_t *hw, wdt_reset_sig_length_t length) +{ + hw->wdt_config0.cpu_reset_length = length; + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Set the length of the system reset action + * + * @param hw Start address of the peripheral registers. + * @param length Length of system reset signal + */ +FORCE_INLINE_ATTR void mwdt_ll_set_sys_reset_length(timg_dev_t *hw, wdt_reset_sig_length_t length) +{ + hw->wdt_config0.sys_reset_length = length; + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Enable/Disable the MWDT flashboot mode. + * + * @param hw Beginning address of the peripheral registers. + * @param enable True to enable WDT flashboot mode, false to disable WDT flashboot mode. + * + * @note Flashboot mode is independent and can trigger a WDT timeout event if the + * WDT's enable bit is set to 0. Flashboot mode for TG0 is automatically enabled + * on flashboot, and should be disabled by software when flashbooting completes. + */ +FORCE_INLINE_ATTR void mwdt_ll_set_flashboot_en(timg_dev_t *hw, bool enable) +{ + hw->wdt_config0.flashboot_mod_en = (enable) ? 1 : 0; + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Set the clock prescaler of the MWDT + * + * @param hw Start address of the peripheral registers. + * @param prescaler Prescaler value between 1 to 65535 + */ +FORCE_INLINE_ATTR void mwdt_ll_set_prescaler(timg_dev_t *hw, uint32_t prescaler) +{ + hw->wdt_config1.clk_prescale = prescaler; + //Config registers are updated asynchronously + hw->wdt_config0.conf_update_en = 1; +} + +/** + * @brief Feed the MWDT + * + * Resets the current timer count and current stage. + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void mwdt_ll_feed(timg_dev_t *hw) +{ + hw->wdt_feed = 1; +} + +/** + * @brief Enable write protection of the MWDT registers + * + * Locking the MWDT will prevent any of the MWDT's registers from being modified + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void mwdt_ll_write_protect_enable(timg_dev_t *hw) +{ + hw->wdt_wprotect = 0; +} + +/** + * @brief Disable write protection of the MWDT registers + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void mwdt_ll_write_protect_disable(timg_dev_t *hw) +{ + hw->wdt_wprotect = TIMG_WDT_WKEY_VALUE; +} + +/** + * @brief Clear the MWDT interrupt status. + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void mwdt_ll_clear_intr_status(timg_dev_t *hw) +{ + hw->int_clr.wdt = 1; +} + +/** + * @brief Set the interrupt enable bit for the MWDT interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param enable Whether to enable the MWDT interrupt + */ +FORCE_INLINE_ATTR void mwdt_ll_set_intr_enable(timg_dev_t *hw, bool enable) +{ + hw->int_ena.wdt = (enable) ? 1 : 0; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rmt_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rmt_ll.h new file mode 100644 index 00000000..a323adfb --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rmt_ll.h @@ -0,0 +1,502 @@ +// Copyright 2020 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. +#pragma once + +#include +#include +#include "soc/rmt_struct.h" +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define RMT_LL_HW_BASE (&RMT) +#define RMT_LL_MEM_BASE (&RMTMEM) + +// Note: TX and RX channel number are all index from zero in the LL driver +// i.e. tx_channel belongs to [0,2], and rx_channel belongs to [0,2] + +static inline void rmt_ll_enable_drive_clock(rmt_dev_t *dev, bool enable) +{ + dev->sys_conf.clk_en = enable; // register clock gating + dev->sys_conf.mem_clk_force_on = enable; // memory clock gating +} + +static inline void rmt_ll_power_down_mem(rmt_dev_t *dev, bool enable) +{ + dev->sys_conf.mem_force_pu = !enable; + dev->sys_conf.mem_force_pd = enable; +} + +static inline bool rmt_ll_is_mem_power_down(rmt_dev_t *dev) +{ + // the RTC domain can also power down RMT memory + // so it's probably not enough to detect whether it's powered down or not + // mem_force_pd has higher priority than mem_force_pu + return (dev->sys_conf.mem_force_pd) || !(dev->sys_conf.mem_force_pu); +} + +static inline void rmt_ll_enable_mem_access(rmt_dev_t *dev, bool enable) +{ + dev->sys_conf.fifo_mask = enable; +} + +static inline void rmt_ll_set_group_clock_src(rmt_dev_t *dev, uint32_t channel, uint8_t src, uint8_t div_num, uint8_t div_a, uint8_t div_b) +{ + // Formula: rmt_sclk = module_clock_src / (1 + div_num + div_a / div_b) + dev->sys_conf.sclk_active = 0; + dev->sys_conf.sclk_sel = src; + dev->sys_conf.sclk_div_num = div_num; + dev->sys_conf.sclk_div_a = div_a; + dev->sys_conf.sclk_div_b = div_b; + dev->sys_conf.sclk_active = 1; +} + +static inline uint32_t rmt_ll_get_group_clock_src(rmt_dev_t *dev, uint32_t channel) +{ + return dev->sys_conf.sclk_sel; +} + +static inline void rmt_ll_tx_reset_channel_clock_div(rmt_dev_t *dev, uint32_t channel) +{ + dev->ref_cnt_rst.val |= (1 << channel); +} + +static inline void rmt_ll_tx_reset_channels_clock_div(rmt_dev_t *dev, uint32_t channel_mask) +{ + dev->ref_cnt_rst.val |= channel_mask; +} + +static inline void rmt_ll_rx_reset_channel_clock_div(rmt_dev_t *dev, uint32_t channel) +{ + dev->ref_cnt_rst.val |= (1 << (channel + 2)); +} + +static inline void rmt_ll_tx_reset_pointer(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_conf[channel].mem_rd_rst = 1; + dev->tx_conf[channel].mem_rd_rst = 0; + dev->tx_conf[channel].mem_rst = 1; + dev->tx_conf[channel].mem_rst = 0; +} + +static inline void rmt_ll_rx_reset_pointer(rmt_dev_t *dev, uint32_t channel) +{ + dev->rx_conf[channel].conf1.mem_wr_rst = 1; + dev->rx_conf[channel].conf1.mem_wr_rst = 0; + dev->rx_conf[channel].conf1.mem_rst = 1; + dev->rx_conf[channel].conf1.mem_rst = 0; +} + +static inline void rmt_ll_tx_start(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_conf[channel].conf_update = 1; + dev->tx_conf[channel].tx_start = 1; +} + +static inline void rmt_ll_tx_stop(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_conf[channel].tx_stop = 1; + dev->tx_conf[channel].conf_update = 1; +} + +static inline void rmt_ll_rx_enable(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->rx_conf[channel].conf1.rx_en = enable; + dev->rx_conf[channel].conf1.conf_update = 1; +} + +static inline void rmt_ll_tx_set_mem_blocks(rmt_dev_t *dev, uint32_t channel, uint8_t block_num) +{ + dev->tx_conf[channel].mem_size = block_num; +} + +static inline void rmt_ll_rx_set_mem_blocks(rmt_dev_t *dev, uint32_t channel, uint8_t block_num) +{ + dev->rx_conf[channel].conf0.mem_size = block_num; +} + +static inline uint32_t rmt_ll_tx_get_mem_blocks(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_conf[channel].mem_size; +} + +static inline uint32_t rmt_ll_rx_get_mem_blocks(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_conf[channel].conf0.mem_size; +} + +static inline void rmt_ll_tx_set_channel_clock_div(rmt_dev_t *dev, uint32_t channel, uint32_t div) +{ + dev->tx_conf[channel].div_cnt = div; +} + +static inline void rmt_ll_rx_set_channel_clock_div(rmt_dev_t *dev, uint32_t channel, uint32_t div) +{ + dev->rx_conf[channel].conf0.div_cnt = div; +} + +static inline uint32_t rmt_ll_tx_get_channel_clock_div(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_conf[channel].div_cnt; +} + +static inline uint32_t rmt_ll_rx_get_channel_clock_div(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_conf[channel].conf0.div_cnt; +} + +static inline void rmt_ll_tx_enable_pingpong(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_conf[channel].mem_tx_wrap_en = enable; +} + +static inline void rmt_ll_rx_set_idle_thres(rmt_dev_t *dev, uint32_t channel, uint32_t thres) +{ + dev->rx_conf[channel].conf0.idle_thres = thres; +} + +static inline uint32_t rmt_ll_rx_get_idle_thres(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_conf[channel].conf0.idle_thres; +} + +static inline void rmt_ll_rx_set_mem_owner(rmt_dev_t *dev, uint32_t channel, uint8_t owner) +{ + dev->rx_conf[channel].conf1.mem_owner = owner; +} + +static inline uint32_t rmt_ll_rx_get_mem_owner(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_conf[channel].conf1.mem_owner; +} + +static inline void rmt_ll_tx_enable_loop(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_conf[channel].tx_conti_mode = enable; +} + +static inline bool rmt_ll_is_tx_loop_enabled(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_conf[channel].tx_conti_mode; +} + +static inline void rmt_ll_tx_set_loop_count(rmt_dev_t *dev, uint32_t channel, uint32_t count) +{ + dev->tx_lim[channel].tx_loop_num = count; +} + +static inline void rmt_ll_tx_reset_loop(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_lim[channel].loop_count_reset = 1; + dev->tx_lim[channel].loop_count_reset = 0; +} + +static inline void rmt_ll_tx_enable_loop_count(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_lim[channel].tx_loop_cnt_en = enable; +} + +static inline void rmt_ll_tx_enable_sync(rmt_dev_t *dev, bool enable) +{ + dev->tx_sim.en = enable; +} + +static inline void rmt_ll_tx_add_to_sync_group(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_sim.val |= 1 << channel; +} + +static inline void rmt_ll_tx_remove_from_sync_group(rmt_dev_t *dev, uint32_t channel) +{ + dev->tx_sim.val &= ~(1 << channel); +} + +static inline void rmt_ll_rx_enable_filter(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->rx_conf[channel].conf1.rx_filter_en = enable; +} + +static inline void rmt_ll_rx_set_filter_thres(rmt_dev_t *dev, uint32_t channel, uint32_t thres) +{ + dev->rx_conf[channel].conf1.rx_filter_thres = thres; +} + +static inline void rmt_ll_tx_enable_idle(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_conf[channel].idle_out_en = enable; +} + +static inline bool rmt_ll_is_tx_idle_enabled(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_conf[channel].idle_out_en; +} + +static inline void rmt_ll_tx_set_idle_level(rmt_dev_t *dev, uint32_t channel, uint8_t level) +{ + dev->tx_conf[channel].idle_out_lv = level; +} + +static inline uint32_t rmt_ll_tx_get_idle_level(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_conf[channel].idle_out_lv; +} + +static inline uint32_t rmt_ll_rx_get_channel_status(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_status[channel].val; +} + +static inline uint32_t rmt_ll_tx_get_channel_status(rmt_dev_t *dev, uint32_t channel) +{ + return dev->tx_status[channel].val; +} + +static inline void rmt_ll_tx_set_limit(rmt_dev_t *dev, uint32_t channel, uint32_t limit) +{ + dev->tx_lim[channel].limit = limit; +} + +static inline void rmt_ll_rx_set_limit(rmt_dev_t *dev, uint32_t channel, uint32_t limit) +{ + dev->rx_lim[channel].rx_lim = limit; +} + +static inline uint32_t rmt_ll_rx_get_limit(rmt_dev_t *dev, uint32_t channel) +{ + return dev->rx_lim[channel].rx_lim; +} + +static inline void rmt_ll_enable_tx_end_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << channel); + } else { + dev->int_ena.val &= ~(1 << channel); + } +} + +static inline void rmt_ll_enable_tx_err_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 4)); + } else { + dev->int_ena.val &= ~(1 << (channel + 4)); + } +} + +static inline void rmt_ll_enable_rx_end_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 2)); + } else { + dev->int_ena.val &= ~(1 << (channel + 2)); + } +} + +static inline void rmt_ll_enable_rx_err_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 6)); + } else { + dev->int_ena.val &= ~(1 << (channel + 6)); + } +} + +static inline void rmt_ll_enable_tx_thres_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 8)); + } else { + dev->int_ena.val &= ~(1 << (channel + 8)); + } +} + +static inline void rmt_ll_enable_tx_loop_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 12)); + } else { + dev->int_ena.val &= ~(1 << (channel + 12)); + } +} + +static inline void rmt_ll_enable_rx_thres_interrupt(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + if (enable) { + dev->int_ena.val |= (1 << (channel + 10)); + } else { + dev->int_ena.val &= ~(1 << (channel + 10)); + } +} + +static inline void rmt_ll_clear_tx_end_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel)); +} + +static inline void rmt_ll_clear_rx_end_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 2)); +} + +static inline void rmt_ll_clear_tx_err_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 4)); +} + +static inline void rmt_ll_clear_rx_err_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 6)); +} + +static inline void rmt_ll_clear_tx_thres_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 8)); +} + +static inline void rmt_ll_clear_tx_loop_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 12)); +} + +static inline void rmt_ll_clear_rx_thres_interrupt(rmt_dev_t *dev, uint32_t channel) +{ + dev->int_clr.val = (1 << (channel + 10)); +} + +static inline uint32_t rmt_ll_get_tx_end_interrupt_status(rmt_dev_t *dev) +{ + return dev->int_st.val & 0x03; +} + +static inline uint32_t rmt_ll_get_rx_end_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 2) & 0x03; +} + +static inline uint32_t rmt_ll_get_tx_err_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 4) & 0x03; +} + +static inline uint32_t rmt_ll_get_rx_err_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 6) & 0x03; +} + +static inline uint32_t rmt_ll_get_tx_thres_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 8) & 0x03; +} + +static inline uint32_t rmt_ll_get_rx_thres_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 10) & 0x03; +} + +static inline uint32_t rmt_ll_get_tx_loop_interrupt_status(rmt_dev_t *dev) +{ + return (dev->int_st.val >> 12) & 0x03; +} + +static inline void rmt_ll_tx_set_carrier_high_low_ticks(rmt_dev_t *dev, uint32_t channel, uint32_t high_ticks, uint32_t low_ticks) +{ + // In case the compiler optimise a 32bit instruction (e.g. s32i) into two 16bit instruction (e.g. s16i, which is not allowed to access a register) + // We take care of the "read-modify-write" procedure by ourselves. + typeof(dev->tx_carrier[0]) reg; + reg.high = high_ticks; + reg.low = low_ticks; + dev->tx_carrier[channel].val = reg.val; +} + +static inline void rmt_ll_rx_set_carrier_high_low_ticks(rmt_dev_t *dev, uint32_t channel, uint32_t high_ticks, uint32_t low_ticks) +{ + typeof(dev->rx_carrier[0]) reg; + reg.high_thres = high_ticks; + reg.low_thres = low_ticks; + dev->rx_carrier[channel].val = reg.val; +} + +static inline void rmt_ll_tx_get_carrier_high_low_ticks(rmt_dev_t *dev, uint32_t channel, uint32_t *high_ticks, uint32_t *low_ticks) +{ + *high_ticks = dev->tx_carrier[channel].high; + *low_ticks = dev->tx_carrier[channel].low; +} + +static inline void rmt_ll_rx_get_carrier_high_low_ticks(rmt_dev_t *dev, uint32_t channel, uint32_t *high_ticks, uint32_t *low_ticks) +{ + *high_ticks = dev->rx_carrier[channel].high_thres; + *low_ticks = dev->rx_carrier[channel].low_thres; +} + +static inline void rmt_ll_tx_enable_carrier_modulation(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_conf[channel].carrier_en = enable; +} + +static inline void rmt_ll_rx_enable_carrier_demodulation(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->rx_conf[channel].conf0.carrier_en = enable; +} + +static inline void rmt_ll_tx_set_carrier_level(rmt_dev_t *dev, uint32_t channel, uint8_t level) +{ + dev->tx_conf[channel].carrier_out_lv = level; +} + +static inline void rmt_ll_rx_set_carrier_level(rmt_dev_t *dev, uint32_t channel, uint8_t level) +{ + dev->rx_conf[channel].conf0.carrier_out_lv = level; +} + +// set true, enable carrier in all RMT state (idle, reading, sending) +// set false, enable carrier only in sending state (i.e. there're effective data in RAM to be sent) +static inline void rmt_ll_tx_set_carrier_always_on(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->tx_conf[channel].carrier_eff_en = !enable; +} + +//Writes items to the specified TX channel memory with the given offset and writen length. +//the caller should ensure that (length + off) <= (memory block * SOC_RMT_MEM_WORDS_PER_CHANNEL) +static inline void rmt_ll_write_memory(rmt_mem_t *mem, uint32_t channel, const rmt_item32_t *data, uint32_t length, uint32_t off) +{ + for (uint32_t i = 0; i < length; i++) { + mem->chan[channel].data32[i + off].val = data[i].val; + } +} + +static inline void rmt_ll_rx_enable_pingpong(rmt_dev_t *dev, uint32_t channel, bool enable) +{ + dev->rx_conf[channel].conf1.mem_rx_wrap_en = enable; +} + +/************************************************************************************************ + * Following Low Level APIs only used for backward compatible, will be deprecated in the IDF v5.0 + ***********************************************************************************************/ + +static inline void rmt_ll_set_intr_enable_mask(uint32_t mask) +{ + RMT.int_ena.val |= mask; +} + +static inline void rmt_ll_clr_intr_enable_mask(uint32_t mask) +{ + RMT.int_ena.val &= (~mask); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rtc_cntl_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rtc_cntl_ll.h new file mode 100644 index 00000000..72385568 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rtc_cntl_ll.h @@ -0,0 +1,67 @@ +// Copyright 2020 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. + +#pragma once + +#include "soc/soc.h" +#include "soc/rtc.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/apb_ctrl_reg.h" + +#ifdef __cplusplus +extern "C" { +#endif + +static inline void rtc_cntl_ll_set_wakeup_timer(uint64_t t) +{ + WRITE_PERI_REG(RTC_CNTL_SLP_TIMER0_REG, t & UINT32_MAX); + WRITE_PERI_REG(RTC_CNTL_SLP_TIMER1_REG, t >> 32); + + SET_PERI_REG_MASK(RTC_CNTL_INT_CLR_REG, RTC_CNTL_MAIN_TIMER_INT_CLR_M); + SET_PERI_REG_MASK(RTC_CNTL_SLP_TIMER1_REG, RTC_CNTL_MAIN_TIMER_ALARM_EN_M); +} + +static inline uint32_t rtc_cntl_ll_gpio_get_wakeup_pins(void) +{ + return GET_PERI_REG_MASK(RTC_CNTL_GPIO_WAKEUP_REG, RTC_CNTL_GPIO_WAKEUP_STATUS); +} + +static inline void rtc_cntl_ll_gpio_set_wakeup_pins(void) +{ + REG_CLR_BIT(RTC_CNTL_GPIO_WAKEUP_REG, RTC_CNTL_GPIO_WAKEUP_STATUS_CLR); +} + +static inline void rtc_cntl_ll_gpio_clear_wakeup_pins(void) +{ + REG_SET_BIT(RTC_CNTL_GPIO_WAKEUP_REG, RTC_CNTL_GPIO_WAKEUP_STATUS_CLR); +} + +static inline void rtc_cntl_ll_enable_cpu_retention(uint32_t addr) +{ + /* write memory address to register */ + REG_SET_FIELD(APB_CTRL_RETENTION_CTRL_REG, APB_CTRL_RETENTION_LINK_ADDR, (uint32_t)addr); + /* Enable clock */ + REG_SET_BIT(RTC_CNTL_CLK_CONF_REG, RTC_CNTL_DIG_CLK8M_EN); + /* Enable retention when cpu sleep enable */ + REG_SET_BIT(RTC_CNTL_RETENTION_CTRL_REG, RTC_CNTL_RETENTION_EN); +} + +static inline void rtc_cntl_ll_disable_cpu_retention(void) +{ + REG_CLR_BIT(RTC_CNTL_RETENTION_CTRL_REG, RTC_CNTL_RETENTION_EN); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rwdt_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rwdt_ll.h new file mode 100644 index 00000000..87ae4f72 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/rwdt_ll.h @@ -0,0 +1,311 @@ +// Copyright 2020 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. + +// The LL layer for Timer Group register operations. +// Note that most of the register operations in this layer are non-atomic operations. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "hal/wdt_types.h" +#include "soc/rtc_cntl_periph.h" +#include "soc/efuse_reg.h" +#include "esp_attr.h" + +//Type check wdt_stage_action_t +_Static_assert(WDT_STAGE_ACTION_OFF == RTC_WDT_STG_SEL_OFF, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_INT == RTC_WDT_STG_SEL_INT, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_RESET_CPU == RTC_WDT_STG_SEL_RESET_CPU, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_RESET_SYSTEM == RTC_WDT_STG_SEL_RESET_SYSTEM, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +_Static_assert(WDT_STAGE_ACTION_RESET_RTC == RTC_WDT_STG_SEL_RESET_RTC, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_stage_action_t"); +//Type check wdt_reset_sig_length_t +_Static_assert(WDT_RESET_SIG_LENGTH_100ns == RTC_WDT_RESET_LENGTH_100_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_200ns == RTC_WDT_RESET_LENGTH_200_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_300ns == RTC_WDT_RESET_LENGTH_300_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_400ns == RTC_WDT_RESET_LENGTH_400_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_500ns == RTC_WDT_RESET_LENGTH_500_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_800ns == RTC_WDT_RESET_LENGTH_800_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_1_6us == RTC_WDT_RESET_LENGTH_1600_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); +_Static_assert(WDT_RESET_SIG_LENGTH_3_2us == RTC_WDT_RESET_LENGTH_3200_NS, "Add mapping to LL watchdog timeout behavior, since it's no longer naturally compatible with wdt_reset_sig_length_t"); + +/** + * @brief Enable the RWDT + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void rwdt_ll_enable(rtc_cntl_dev_t *hw) +{ + hw->wdt_config0.en = 1; +} + +/** + * @brief Disable the RWDT + * + * @param hw Start address of the peripheral registers. + * @note This function does not disable the flashboot mode. Therefore, given that + * the MWDT is disabled using this function, a timeout can still occur + * if the flashboot mode is simultaneously enabled. + */ +FORCE_INLINE_ATTR void rwdt_ll_disable(rtc_cntl_dev_t *hw) +{ + hw->wdt_config0.en = 0; +} + +/** + * @brief Check if the RWDT is enabled + * + * @param hw Start address of the peripheral registers. + * @return True if RTC WDT is enabled + */ +FORCE_INLINE_ATTR bool rwdt_ll_check_if_enabled(rtc_cntl_dev_t *hw) +{ + return (hw->wdt_config0.en) ? true : false; +} + +/** + * @brief Configure a particular stage of the RWDT + * + * @param hw Start address of the peripheral registers. + * @param stage Which stage to configure + * @param timeout Number of timer ticks for the stage to timeout (see note). + * @param behavior What action to take when the stage times out + * + * @note The value of of RWDT stage 0 timeout register is special, in + * that an implicit multiplier is applied to that value to produce + * and effective timeout tick value. The multiplier is dependent + * on an EFuse value. Therefore, when configuring stage 0, the valid + * values for the timeout argument are: + * - If Efuse value is 0, any even number between [2,2*UINT32_MAX] + * - If Efuse value is 1, any multiple of 4 between [4,4*UINT32_MAX] + * - If Efuse value is 2, any multiple of 8 between [8,8*UINT32_MAX] + * - If Efuse value is 3, any multiple of 16 between [16,16*UINT32_MAX] + */ +FORCE_INLINE_ATTR void rwdt_ll_config_stage(rtc_cntl_dev_t *hw, wdt_stage_t stage, uint32_t timeout_ticks, wdt_stage_action_t behavior) +{ + switch (stage) { + case WDT_STAGE0: + hw->wdt_config0.stg0 = behavior; + //Account of implicty multiplier applied to stage 0 timeout tick config value + hw->wdt_config1 = timeout_ticks >> (1 + REG_GET_FIELD(EFUSE_RD_REPEAT_DATA1_REG, EFUSE_WDT_DELAY_SEL)); + break; + case WDT_STAGE1: + hw->wdt_config0.stg1 = behavior; + hw->wdt_config2 = timeout_ticks; + break; + case WDT_STAGE2: + hw->wdt_config0.stg2 = behavior; + hw->wdt_config3 = timeout_ticks; + break; + case WDT_STAGE3: + hw->wdt_config0.stg3 = behavior; + hw->wdt_config4 = timeout_ticks; + break; + default: + abort(); + } +} + +/** + * @brief Disable a particular stage of the RWDT + * + * @param hw Start address of the peripheral registers. + * @param stage Which stage to disable + */ +FORCE_INLINE_ATTR void rwdt_ll_disable_stage(rtc_cntl_dev_t *hw, wdt_stage_t stage) +{ + switch (stage) { + case WDT_STAGE0: + hw->wdt_config0.stg0 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE1: + hw->wdt_config0.stg1 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE2: + hw->wdt_config0.stg2 = WDT_STAGE_ACTION_OFF; + break; + case WDT_STAGE3: + hw->wdt_config0.stg3 = WDT_STAGE_ACTION_OFF; + break; + default: + abort(); + } +} + +/** + * @brief Set the length of the CPU reset action + * + * @param hw Start address of the peripheral registers. + * @param length Length of CPU reset signal + */ +FORCE_INLINE_ATTR void rwdt_ll_set_cpu_reset_length(rtc_cntl_dev_t *hw, wdt_reset_sig_length_t length) +{ + hw->wdt_config0.cpu_reset_length = length; +} + +/** + * @brief Set the length of the system reset action + * + * @param hw Start address of the peripheral registers. + * @param length Length of system reset signal + */ +FORCE_INLINE_ATTR void rwdt_ll_set_sys_reset_length(rtc_cntl_dev_t *hw, wdt_reset_sig_length_t length) +{ + hw->wdt_config0.sys_reset_length = length; +} + +/** + * @brief Enable/Disable the RWDT flashboot mode. + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable RWDT flashboot mode, false to disable RWDT flashboot mode. + * + * @note Flashboot mode is independent and can trigger a WDT timeout event if the + * WDT's enable bit is set to 0. Flashboot mode for RWDT is automatically enabled + * on flashboot, and should be disabled by software when flashbooting completes. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_flashboot_en(rtc_cntl_dev_t *hw, bool enable) +{ + hw->wdt_config0.flashboot_mod_en = (enable) ? 1 : 0; +} + +/** + * @brief Enable/Disable the CPU0 to be reset on WDT_STAGE_ACTION_RESET_CPU + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable CPU0 to be reset, false to disable. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_procpu_reset_en(rtc_cntl_dev_t *hw, bool enable) +{ + hw->wdt_config0.procpu_reset_en = (enable) ? 1 : 0; +} + +/** + * @brief Enable/Disable the CPU1 to be reset on WDT_STAGE_ACTION_RESET_CPU + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable CPU1 to be reset, false to disable. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_appcpu_reset_en(rtc_cntl_dev_t *hw, bool enable) +{ + hw->wdt_config0.appcpu_reset_en = (enable) ? 1 : 0; +} + +/** + * @brief Enable/Disable the RWDT pause during sleep functionality + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable, false to disable. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_pause_in_sleep_en(rtc_cntl_dev_t *hw, bool enable) +{ + hw->wdt_config0.pause_in_slp = (enable) ? 1 : 0; +} + +/** + * @brief Enable/Disable chip reset on RWDT timeout. + * + * A chip reset also resets the analog portion of the chip. It will appear as a + * POWERON reset rather than an RTC reset. + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable, false to disable. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_chip_reset_en(rtc_cntl_dev_t *hw, bool enable) +{ + hw->wdt_config0.chip_reset_en = (enable) ? 1 : 0; +} + +/** + * @brief Set width of chip reset signal + * + * @param hw Start address of the peripheral registers. + * @param width Width of chip reset signal in terms of number of RTC_SLOW_CLK cycles + */ +FORCE_INLINE_ATTR void rwdt_ll_set_chip_reset_width(rtc_cntl_dev_t *hw, uint32_t width) +{ + hw->wdt_config0.chip_reset_width = width; +} + +/** + * @brief Feed the RWDT + * + * Resets the current timer count and current stage. + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void rwdt_ll_feed(rtc_cntl_dev_t *hw) +{ + hw->wdt_feed.feed = 1; +} + +/** + * @brief Enable write protection of the RWDT registers + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void rwdt_ll_write_protect_enable(rtc_cntl_dev_t *hw) +{ + hw->wdt_wprotect = 0; +} + +/** + * @brief Disable write protection of the RWDT registers + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void rwdt_ll_write_protect_disable(rtc_cntl_dev_t *hw) +{ + hw->wdt_wprotect = RTC_CNTL_WDT_WKEY_VALUE; +} + +/** + * @brief Enable the RWDT interrupt. + * + * @param hw Start address of the peripheral registers. + * @param enable True to enable RWDT interrupt, false to disable. + */ +FORCE_INLINE_ATTR void rwdt_ll_set_intr_enable(rtc_cntl_dev_t *hw, bool enable) +{ + hw->int_ena.rtc_wdt = (enable) ? 1 : 0; +} + +/** + * @brief Check if the RWDT interrupt has been triggered + * + * @param hw Start address of the peripheral registers. + * @return True if the RWDT interrupt was triggered + */ +FORCE_INLINE_ATTR bool rwdt_ll_check_intr_status(rtc_cntl_dev_t *hw) +{ + return (hw->int_st.rtc_wdt) ? true : false; +} + +/** + * @brief Clear the RWDT interrupt status. + * + * @param hw Start address of the peripheral registers. + */ +FORCE_INLINE_ATTR void rwdt_ll_clear_intr_status(rtc_cntl_dev_t *hw) +{ + hw->int_clr.rtc_wdt = 1; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sha_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sha_ll.h new file mode 100644 index 00000000..a7bc4932 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sha_ll.h @@ -0,0 +1,157 @@ +// Copyright 2020 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. +#pragma once + +#include +#include "soc/hwcrypto_reg.h" +#include "hal/sha_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Start a new SHA block conversions (no initial hash in HW) + * + * @param sha_type The SHA algorithm type + */ +static inline void sha_ll_start_block(esp_sha_type sha_type) +{ + REG_WRITE(SHA_MODE_REG, sha_type); + REG_WRITE(SHA_START_REG, 1); +} + +/** + * @brief Continue a SHA block conversion (initial hash in HW) + * + * @param sha_type The SHA algorithm type + */ +static inline void sha_ll_continue_block(esp_sha_type sha_type) +{ + REG_WRITE(SHA_MODE_REG, sha_type); + REG_WRITE(SHA_CONTINUE_REG, 1); +} + +/** + * @brief Start a new SHA message conversion using DMA (no initial hash in HW) + * + * @param sha_type The SHA algorithm type + */ +static inline void sha_ll_start_dma(esp_sha_type sha_type) +{ + REG_WRITE(SHA_MODE_REG, sha_type); + REG_WRITE(SHA_DMA_START_REG, 1); +} + +/** + * @brief Continue a SHA message conversion using DMA (initial hash in HW) + * + * @param sha_type The SHA algorithm type + */ +static inline void sha_ll_continue_dma(esp_sha_type sha_type) +{ + REG_WRITE(SHA_MODE_REG, sha_type); + REG_WRITE(SHA_DMA_CONTINUE_REG, 1); +} + +/** + * @brief Load the current hash digest to digest register + * + * @note Happens automatically on ESP32S3 + * + * @param sha_type The SHA algorithm type + */ +static inline void sha_ll_load(esp_sha_type sha_type) +{ +} + +/** + * @brief Sets the number of message blocks to be hashed + * + * @note DMA operation only + * + * @param num_blocks Number of message blocks to process + */ +static inline void sha_ll_set_block_num(size_t num_blocks) +{ + REG_WRITE(SHA_BLOCK_NUM_REG, num_blocks); +} + +/** + * @brief Checks if the SHA engine is currently busy hashing a block + * + * @return true SHA engine busy + * @return false SHA engine idle + */ +static inline bool sha_ll_busy(void) +{ + return REG_READ(SHA_BUSY_REG); +} + +/** + * @brief Write a text (message) block to the SHA engine + * + * @param input_text Input buffer to be written to the SHA engine + * @param block_word_len Number of words in block + */ +static inline void sha_ll_fill_text_block(const void *input_text, size_t block_word_len) +{ + uint32_t *data_words = (uint32_t *)input_text; + uint32_t *reg_addr_buf = (uint32_t *)(SHA_TEXT_BASE); + + for (int i = 0; i < block_word_len; i++) { + REG_WRITE(®_addr_buf[i], data_words[i]); + } +} + +/** + * @brief Read the message digest from the SHA engine + * + * @param sha_type The SHA algorithm type + * @param digest_state Buffer that message digest will be written to + * @param digest_word_len Length of the message digest + */ +static inline void sha_ll_read_digest(esp_sha_type sha_type, void *digest_state, size_t digest_word_len) +{ + uint32_t *digest_state_words = (uint32_t *)digest_state; + const size_t REG_WIDTH = sizeof(uint32_t); + + for (size_t i = 0; i < digest_word_len; i++) { + digest_state_words[i] = REG_READ(SHA_H_BASE + (i * REG_WIDTH)); + } + +} + +/** + * @brief Write the message digest to the SHA engine + * + * @param sha_type The SHA algorithm type + * @param digest_state Message digest to be written to SHA engine + * @param digest_word_len Length of the message digest + */ +static inline void sha_ll_write_digest(esp_sha_type sha_type, void *digest_state, size_t digest_word_len) +{ + uint32_t *digest_state_words = (uint32_t *)digest_state; + uint32_t *reg_addr_buf = (uint32_t *)(SHA_H_BASE); + + for (int i = 0; i < digest_word_len; i++) { + REG_WRITE(®_addr_buf[i], digest_state_words[i]); + } +} + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sigmadelta_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sigmadelta_ll.h new file mode 100644 index 00000000..87f75dab --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/sigmadelta_ll.h @@ -0,0 +1,73 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The LL layer for ESP32 SIGMADELTA register operations + +#pragma once + +#include +#include "soc/sigmadelta_periph.h" +#include "hal/sigmadelta_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// Get SIGMADELTA hardware instance with giving sigmadelta num +#define SIGMADELTA_LL_GET_HW(num) (((num) == 0) ? (&SIGMADELTA) : NULL) + +/** + * @brief Set Sigma-delta enable + * + * @param hw Peripheral SIGMADELTA hardware instance address. + * @param en Sigma-delta enable value + */ +static inline void sigmadelta_ll_set_en(gpio_sd_dev_t *hw, bool en) +{ + hw->misc.function_clk_en = en; +} + +/** + * @brief Set Sigma-delta channel duty. + * + * @param hw Peripheral SIGMADELTA hardware instance address. + * @param channel Sigma-delta channel number + * @param duty Sigma-delta duty of one channel, the value ranges from -128 to 127, recommended range is -90 ~ 90. + * The waveform is more like a random one in this range. + */ +static inline void sigmadelta_ll_set_duty(gpio_sd_dev_t *hw, sigmadelta_channel_t channel, int8_t duty) +{ + hw->channel[channel].duty = duty; +} + +/** + * @brief Set Sigma-delta channel's clock pre-scale value. + * + * @param hw Peripheral SIGMADELTA hardware instance address. + * @param channel Sigma-delta channel number + * @param val The divider of source clock, ranges from 0 to 255 + */ +static inline void sigmadelta_ll_set_prescale(gpio_sd_dev_t *hw, sigmadelta_channel_t channel, uint8_t prescale) +{ + hw->channel[channel].prescale = prescale; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/soc_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/soc_ll.h new file mode 100644 index 00000000..36f2bd13 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/soc_ll.h @@ -0,0 +1,52 @@ +// Copyright 2020 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. +#pragma once + +#include "soc/soc.h" +#include "soc/rtc_cntl_reg.h" +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +static inline void soc_ll_stall_core(int core) +{ + const int rtc_cntl_c1_m[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C1_M}; + const int rtc_cntl_c1_s[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C1_S}; + const int rtc_cntl_c0_m[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C0_M}; + const int rtc_cntl_c0_s[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C0_S}; + + CLEAR_PERI_REG_MASK(RTC_CNTL_SW_CPU_STALL_REG, rtc_cntl_c1_m[core]); + SET_PERI_REG_MASK(RTC_CNTL_SW_CPU_STALL_REG, 0x21 << rtc_cntl_c1_s[core]); + CLEAR_PERI_REG_MASK(RTC_CNTL_OPTIONS0_REG, rtc_cntl_c0_m[core]); + SET_PERI_REG_MASK(RTC_CNTL_OPTIONS0_REG, 2 << rtc_cntl_c0_s[core]); +} + +static inline void soc_ll_unstall_core(int core) +{ + const int rtc_cntl_c1_m[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C1_M}; + const int rtc_cntl_c0_m[SOC_CPU_CORES_NUM] = {RTC_CNTL_SW_STALL_PROCPU_C0_M}; + CLEAR_PERI_REG_MASK(RTC_CNTL_SW_CPU_STALL_REG, rtc_cntl_c1_m[core]); + CLEAR_PERI_REG_MASK(RTC_CNTL_OPTIONS0_REG, rtc_cntl_c0_m[core]); +} + +static inline void soc_ll_reset_core(int core) +{ + SET_PERI_REG_MASK(RTC_CNTL_OPTIONS0_REG, RTC_CNTL_SW_PROCPU_RST_M); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_flash_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_flash_ll.h new file mode 100644 index 00000000..ab787644 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_flash_ll.h @@ -0,0 +1,109 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The ll is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The Lowlevel layer for SPI Flash + +#pragma once + +#include "gpspi_flash_ll.h" +#include "spimem_flash_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// For esp32s2, spimem is equivalent to traditional spi peripherals found +// in esp32. Let the spi flash clock reg definitions reflect this. +#define SPI_FLASH_LL_CLKREG_VAL_5MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_5MHZ} +#define SPI_FLASH_LL_CLKREG_VAL_10MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_10MHZ} +#define SPI_FLASH_LL_CLKREG_VAL_20MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_20MHZ} +#define SPI_FLASH_LL_CLKREG_VAL_26MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_26MHZ} +#define SPI_FLASH_LL_CLKREG_VAL_40MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_40MHZ} +#define SPI_FLASH_LL_CLKREG_VAL_80MHZ {.spimem=SPIMEM_FLASH_LL_CLKREG_VAL_80MHZ} + +#define spi_flash_ll_get_hw(host_id) (((host_id)<=SPI1_HOST ? (spi_dev_t*) spimem_flash_ll_get_hw(host_id) \ + : gpspi_flash_ll_get_hw(host_id))) + +#define spi_flash_ll_hw_get_id(dev) ({int dev_id = spimem_flash_ll_hw_get_id(dev); \ + if (dev_id < 0) {\ + dev_id = gpspi_flash_ll_hw_get_id(dev);\ + }\ + dev_id; \ + }) + + +typedef union { + gpspi_flash_ll_clock_reg_t gpspi; + spimem_flash_ll_clock_reg_t spimem; +} spi_flash_ll_clock_reg_t; + +#ifdef GPSPI_BUILD +#define spi_flash_ll_reset(dev) gpspi_flash_ll_reset((spi_dev_t*)dev) +#define spi_flash_ll_cmd_is_done(dev) gpspi_flash_ll_cmd_is_done((spi_dev_t*)dev) +#define spi_flash_ll_get_buffer_data(dev, buffer, read_len) gpspi_flash_ll_get_buffer_data((spi_dev_t*)dev, buffer, read_len) +#define spi_flash_ll_set_buffer_data(dev, buffer, len) gpspi_flash_ll_set_buffer_data((spi_dev_t*)dev, buffer, len) +#define spi_flash_ll_user_start(dev) gpspi_flash_ll_user_start((spi_dev_t*)dev) +#define spi_flash_ll_host_idle(dev) gpspi_flash_ll_host_idle((spi_dev_t*)dev) +#define spi_flash_ll_read_phase(dev) gpspi_flash_ll_read_phase((spi_dev_t*)dev) +#define spi_flash_ll_set_cs_pin(dev, pin) gpspi_flash_ll_set_cs_pin((spi_dev_t*)dev, pin) +#define spi_flash_ll_set_read_mode(dev, read_mode) gpspi_flash_ll_set_read_mode((spi_dev_t*)dev, read_mode) +#define spi_flash_ll_set_clock(dev, clk) gpspi_flash_ll_set_clock((spi_dev_t*)dev, (gpspi_flash_ll_clock_reg_t*)clk) +#define spi_flash_ll_set_miso_bitlen(dev, bitlen) gpspi_flash_ll_set_miso_bitlen((spi_dev_t*)dev, bitlen) +#define spi_flash_ll_set_mosi_bitlen(dev, bitlen) gpspi_flash_ll_set_mosi_bitlen((spi_dev_t*)dev, bitlen) +#define spi_flash_ll_set_command(dev, cmd, bitlen) gpspi_flash_ll_set_command((spi_dev_t*)dev, cmd, bitlen) +#define spi_flash_ll_set_addr_bitlen(dev, bitlen) gpspi_flash_ll_set_addr_bitlen((spi_dev_t*)dev, bitlen) +#define spi_flash_ll_get_addr_bitlen(dev) gpspi_flash_ll_get_addr_bitlen((spi_dev_t*)dev) +#define spi_flash_ll_set_address(dev, addr) gpspi_flash_ll_set_address((spi_dev_t*)dev, addr) +#define spi_flash_ll_set_usr_address(dev, addr, bitlen) gpspi_flash_ll_set_usr_address((spi_dev_t*)dev, addr, bitlen) +#define spi_flash_ll_set_dummy(dev, dummy) gpspi_flash_ll_set_dummy((spi_dev_t*)dev, dummy) +#define spi_flash_ll_set_dummy_out(dev, en, lev) gpspi_flash_ll_set_dummy_out((spi_dev_t*)dev, en, lev) +#define spi_flash_ll_set_hold(dev, hold_n) gpspi_flash_ll_set_hold((spi_dev_t*)dev, hold_n) +#else +#define spi_flash_ll_reset(dev) spimem_flash_ll_reset((spi_mem_dev_t*)dev) +#define spi_flash_ll_cmd_is_done(dev) spimem_flash_ll_cmd_is_done((spi_mem_dev_t*)dev) +#define spi_flash_ll_erase_chip(dev) spimem_flash_ll_erase_chip((spi_mem_dev_t*)dev) +#define spi_flash_ll_erase_sector(dev) spimem_flash_ll_erase_sector((spi_mem_dev_t*)dev) +#define spi_flash_ll_erase_block(dev) spimem_flash_ll_erase_block((spi_mem_dev_t*)dev) +#define spi_flash_ll_set_write_protect(dev, wp) spimem_flash_ll_set_write_protect((spi_mem_dev_t*)dev, wp) +#define spi_flash_ll_get_buffer_data(dev, buffer, read_len) spimem_flash_ll_get_buffer_data((spi_mem_dev_t*)dev, buffer, read_len) +#define spi_flash_ll_set_buffer_data(dev, buffer, len) spimem_flash_ll_set_buffer_data((spi_mem_dev_t*)dev, buffer, len) +#define spi_flash_ll_program_page(dev, buffer, len) spimem_flash_ll_program_page((spi_mem_dev_t*)dev, buffer, len) +#define spi_flash_ll_user_start(dev) spimem_flash_ll_user_start((spi_mem_dev_t*)dev) +#define spi_flash_ll_host_idle(dev) spimem_flash_ll_host_idle((spi_mem_dev_t*)dev) +#define spi_flash_ll_read_phase(dev) spimem_flash_ll_read_phase((spi_mem_dev_t*)dev) +#define spi_flash_ll_set_cs_pin(dev, pin) spimem_flash_ll_set_cs_pin((spi_mem_dev_t*)dev, pin) +#define spi_flash_ll_set_read_mode(dev, read_mode) spimem_flash_ll_set_read_mode((spi_mem_dev_t*)dev, read_mode) +#define spi_flash_ll_set_clock(dev, clk) spimem_flash_ll_set_clock((spi_mem_dev_t*)dev, (spimem_flash_ll_clock_reg_t*)clk) +#define spi_flash_ll_set_miso_bitlen(dev, bitlen) spimem_flash_ll_set_miso_bitlen((spi_mem_dev_t*)dev, bitlen) +#define spi_flash_ll_set_mosi_bitlen(dev, bitlen) spimem_flash_ll_set_mosi_bitlen((spi_mem_dev_t*)dev, bitlen) +#define spi_flash_ll_set_command(dev, cmd, bitlen) spimem_flash_ll_set_command((spi_mem_dev_t*)dev, cmd, bitlen) +#define spi_flash_ll_set_addr_bitlen(dev, bitlen) spimem_flash_ll_set_addr_bitlen((spi_mem_dev_t*)dev, bitlen) +#define spi_flash_ll_get_addr_bitlen(dev) spimem_flash_ll_get_addr_bitlen((spi_mem_dev_t*) dev) +#define spi_flash_ll_set_address(dev, addr) spimem_flash_ll_set_address((spi_mem_dev_t*)dev, addr) +#define spi_flash_ll_set_usr_address(dev, addr, bitlen) spimem_flash_ll_set_usr_address((spi_mem_dev_t*)dev, addr, bitlen) +#define spi_flash_ll_set_dummy(dev, dummy) spimem_flash_ll_set_dummy((spi_mem_dev_t*)dev, dummy) +#define spi_flash_ll_set_dummy_out(dev, en, lev) spimem_flash_ll_set_dummy_out((spi_mem_dev_t*)dev, en, lev) +#define spi_flash_ll_set_hold(dev, hold_n) spimem_flash_ll_set_hold((spi_mem_dev_t*)dev, hold_n) + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_ll.h new file mode 100644 index 00000000..5527ee1e --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spi_ll.h @@ -0,0 +1,1090 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The LL layer for SPI register operations + +#pragma once + +#include //for abs() +#include +#include "hal/hal_defs.h" +#include "esp_types.h" +#include "soc/spi_periph.h" +#include "esp32c3/rom/lldesc.h" +#include "esp_attr.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/// Interrupt not used. Don't use in app. +#define SPI_LL_UNUSED_INT_MASK (SPI_TRANS_DONE_INT_ENA | SPI_SLV_WR_DMA_DONE_INT_ENA | SPI_SLV_RD_DMA_DONE_INT_ENA | SPI_SLV_WR_BUF_DONE_INT_ENA | SPI_SLV_RD_BUF_DONE_INT_ENA) +/// Swap the bit order to its correct place to send +#define HAL_SPI_SWAP_DATA_TX(data, len) HAL_SWAP32((uint32_t)data<<(32-len)) +/// This is the expected clock frequency +#define SPI_LL_PERIPH_CLK_FREQ (80 * 1000000) +#define SPI_LL_GET_HW(ID) ((ID)==0? ({abort();NULL;}):&GPSPI2) + +/** + * The data structure holding calculated clock configuration. Since the + * calculation needs long time, it should be calculated during initialization and + * stored somewhere to be quickly used. + */ +typedef uint32_t spi_ll_clock_val_t; +typedef spi_dev_t spi_dma_dev_t; + +/** IO modes supported by the master. */ +typedef enum { + SPI_LL_IO_MODE_NORMAL = 0, ///< 1-bit mode for all phases + SPI_LL_IO_MODE_DIO, ///< 2-bit mode for address and data phases, 1-bit mode for command phase + SPI_LL_IO_MODE_DUAL, ///< 2-bit mode for data phases only, 1-bit mode for command and address phases + SPI_LL_IO_MODE_QIO, ///< 4-bit mode for address and data phases, 1-bit mode for command phase + SPI_LL_IO_MODE_QUAD, ///< 4-bit mode for data phases only, 1-bit mode for command and address phases +} spi_ll_io_mode_t; + +// Type definition of all supported interrupts +typedef enum { + SPI_LL_INTR_TRANS_DONE = BIT(0), ///< A transaction has done + SPI_LL_INTR_RDBUF = BIT(6), ///< Has received RDBUF command. Only available in slave HD. + SPI_LL_INTR_WRBUF = BIT(7), ///< Has received WRBUF command. Only available in slave HD. + SPI_LL_INTR_RDDMA = BIT(8), ///< Has received RDDMA command. Only available in slave HD. + SPI_LL_INTR_WRDMA = BIT(9), ///< Has received WRDMA command. Only available in slave HD. + SPI_LL_INTR_CMD7 = BIT(10), ///< Has received CMD7 command. Only available in slave HD. + SPI_LL_INTR_CMD8 = BIT(11), ///< Has received CMD8 command. Only available in slave HD. + SPI_LL_INTR_CMD9 = BIT(12), ///< Has received CMD9 command. Only available in slave HD. + SPI_LL_INTR_CMDA = BIT(13), ///< Has received CMDA command. Only available in slave HD. + SPI_LL_INTR_SEG_DONE = BIT(14), +} spi_ll_intr_t; +FLAG_ATTR(spi_ll_intr_t) + +// Flags for conditions under which the transaction length should be recorded +typedef enum { + SPI_LL_TRANS_LEN_COND_WRBUF = BIT(0), ///< WRBUF length will be recorded + SPI_LL_TRANS_LEN_COND_RDBUF = BIT(1), ///< RDBUF length will be recorded + SPI_LL_TRANS_LEN_COND_WRDMA = BIT(2), ///< WRDMA length will be recorded + SPI_LL_TRANS_LEN_COND_RDDMA = BIT(3), ///< RDDMA length will be recorded +} spi_ll_trans_len_cond_t; +FLAG_ATTR(spi_ll_trans_len_cond_t) + +/*------------------------------------------------------------------------------ + * Control + *----------------------------------------------------------------------------*/ +/** + * Initialize SPI peripheral (master). + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_master_init(spi_dev_t *hw) +{ + //Reset timing + hw->user1.cs_setup_time = 0; + hw->user1.cs_hold_time = 0; + + //use all 64 bytes of the buffer + hw->user.usr_miso_highpart = 0; + hw->user.usr_mosi_highpart = 0; + + //Disable unneeded ints + hw->slave.val = 0; + hw->user.val = 0; + + hw->clk_gate.clk_en = 1; + hw->clk_gate.mst_clk_active = 1; + hw->clk_gate.mst_clk_sel = 1; + + hw->dma_conf.val = 0; + hw->dma_conf.tx_seg_trans_clr_en = 1; + hw->dma_conf.rx_seg_trans_clr_en = 1; + hw->dma_conf.dma_seg_trans_en = 0; +} + +/** + * Initialize SPI peripheral (slave). + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_slave_init(spi_dev_t *hw) +{ + //Configure slave + hw->clock.val = 0; + hw->user.val = 0; + hw->ctrl.val = 0; + hw->user.doutdin = 1; //we only support full duplex + hw->user.sio = 0; + hw->slave.slave_mode = 1; + hw->slave.soft_reset = 1; + hw->slave.soft_reset = 0; + //use all 64 bytes of the buffer + hw->user.usr_miso_highpart = 0; + hw->user.usr_mosi_highpart = 0; + + hw->dma_conf.dma_seg_trans_en = 0; + + //Disable unneeded ints + hw->slave.val &= ~SPI_LL_UNUSED_INT_MASK; +} + +/** + * Initialize SPI peripheral (slave half duplex mode) + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_slave_hd_init(spi_dev_t *hw) +{ + hw->clock.val = 0; + hw->user.val = 0; + hw->ctrl.val = 0; + hw->user.doutdin = 0; + hw->user.sio = 0; + + hw->slave.soft_reset = 1; + hw->slave.soft_reset = 0; + hw->slave.slave_mode = 1; +} + +/** + * Check whether user-defined transaction is done. + * + * @param hw Beginning address of the peripheral registers. + * + * @return True if transaction is done, otherwise false. + */ +static inline bool spi_ll_usr_is_done(spi_dev_t *hw) +{ + return hw->dma_int_raw.trans_done; +} + +/** + * Trigger start of user-defined transaction for master. + * The synchronization between two clock domains is required in ESP32-S3 + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_master_user_start(spi_dev_t *hw) +{ + hw->cmd.update = 1; + while (hw->cmd.update); + hw->cmd.usr = 1; +} + +/** + * Trigger start of user-defined transaction for slave. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_slave_user_start(spi_dev_t *hw) +{ + hw->cmd.usr = 1; +} + +/** + * Get current running command bit-mask. (Preview) + * + * @param hw Beginning address of the peripheral registers. + * + * @return Bitmask of running command, see ``SPI_CMD_REG``. 0 if no in-flight command. + */ +static inline uint32_t spi_ll_get_running_cmd(spi_dev_t *hw) +{ + return hw->cmd.val; +} + +/** + * Reset the slave peripheral before next transaction. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_slave_reset(spi_dev_t *hw) +{ + hw->slave.soft_reset = 1; + hw->slave.soft_reset = 0; +} + +/** + * Reset SPI CPU TX FIFO + * + * On ESP32C3, this function is not seperated + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_cpu_tx_fifo_reset(spi_dev_t *hw) +{ + hw->dma_conf.buf_afifo_rst = 1; + hw->dma_conf.buf_afifo_rst = 0; +} + +/** + * Reset SPI CPU RX FIFO + * + * On ESP32C3, this function is not seperated + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_cpu_rx_fifo_reset(spi_dev_t *hw) +{ + hw->dma_conf.rx_afifo_rst = 1; + hw->dma_conf.rx_afifo_rst = 0; +} + +/** + * Reset SPI DMA TX FIFO + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_dma_tx_fifo_reset(spi_dev_t *hw) +{ + hw->dma_conf.dma_afifo_rst = 1; + hw->dma_conf.dma_afifo_rst = 0; +} + +/** + * Reset SPI DMA RX FIFO + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_dma_rx_fifo_reset(spi_dev_t *hw) +{ + hw->dma_conf.rx_afifo_rst = 1; + hw->dma_conf.rx_afifo_rst = 0; +} + +/** + * Clear in fifo full error + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_infifo_full_clr(spi_dev_t *hw) +{ + hw->dma_int_clr.infifo_full_err = 1; +} + +/** + * Clear out fifo empty error + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_outfifo_empty_clr(spi_dev_t *hw) +{ + hw->dma_int_clr.outfifo_empty_err = 1; +} + +/*------------------------------------------------------------------------------ + * DMA + *----------------------------------------------------------------------------*/ +/** + * Enable/Disable RX DMA (Peripherals->DMA->RAM) + * + * @param hw Beginning address of the peripheral registers. + * @param enable 1: enable; 2: disable + */ +static inline void spi_ll_dma_rx_enable(spi_dev_t *hw, bool enable) +{ + hw->dma_conf.dma_rx_ena = enable; +} + +/** + * Enable/Disable TX DMA (RAM->DMA->Peripherals) + * + * @param hw Beginning address of the peripheral registers. + * @param enable 1: enable; 2: disable + */ +static inline void spi_ll_dma_tx_enable(spi_dev_t *hw, bool enable) +{ + hw->dma_conf.dma_tx_ena = enable; +} + +/** + * Configuration of RX DMA EOF interrupt generation way + * + * @param hw Beginning address of the peripheral registers. + * @param enable 1: spi_dma_inlink_eof is set when the number of dma pushed data bytes is equal to the value of spi_slv/mst_dma_rd_bytelen[19:0] in spi dma transition. 0: spi_dma_inlink_eof is set by spi_trans_done in non-seg-trans or spi_dma_seg_trans_done in seg-trans. + */ +static inline void spi_ll_dma_set_rx_eof_generation(spi_dev_t *hw, bool enable) +{ + hw->dma_conf.rx_eof_en = enable; +} + +/*------------------------------------------------------------------------------ + * Buffer + *----------------------------------------------------------------------------*/ +/** + * Write to SPI hardware data buffer. + * + * @param hw Beginning address of the peripheral registers. + * @param buffer_to_send Address of the data to be written to the hardware data buffer. + * @param bitlen Length to write, in bits. + */ +static inline void spi_ll_write_buffer(spi_dev_t *hw, const uint8_t *buffer_to_send, size_t bitlen) +{ + for (int x = 0; x < bitlen; x += 32) { + //Use memcpy to get around alignment issues for txdata + uint32_t word; + memcpy(&word, &buffer_to_send[x / 8], 4); + hw->data_buf[(x / 32)] = word; + } +} + +/** + * Write to SPI hardware data buffer by buffer ID (address) + * + * @param hw Beginning address of the peripheral registers + * @param byte_id Start ID (address) of the hardware buffer to be written + * @param data Address of the data to be written to the hardware data buffer. + * @param len Length to write, in bytes. + */ +static inline void spi_ll_write_buffer_byte(spi_dev_t *hw, int byte_id, uint8_t *data, int len) +{ + assert(byte_id+len <= 64); + assert(len > 0); + assert(byte_id >= 0); + + while (len > 0) { + uint32_t word; + int offset = byte_id % 4; + int copy_len = 4 - offset; + if (copy_len > len) copy_len = len; + + //read-modify-write + if (copy_len != 4) word = hw->data_buf[byte_id / 4]; //read + memcpy(((uint8_t *)&word) + offset, data, copy_len); //modify + hw->data_buf[byte_id / 4] = word; //write + + data += copy_len; + byte_id += copy_len; + len -= copy_len; + } +} + +/** + * Read from SPI hardware data buffer. + * + * @param hw Beginning address of the peripheral registers. + * @param buffer_to_rcv Address of a buffer to read data from hardware data buffer + * @param bitlen Length to read, in bits. + */ +static inline void spi_ll_read_buffer(spi_dev_t *hw, uint8_t *buffer_to_rcv, size_t bitlen) +{ + for (int x = 0; x < bitlen; x += 32) { + //Do a memcpy to get around possible alignment issues in rx_buffer + uint32_t word = hw->data_buf[x / 32]; + int len = bitlen - x; + if (len > 32) { + len = 32; + } + memcpy(&buffer_to_rcv[x / 8], &word, (len + 7) / 8); + } +} + +/** + * Read from SPI hardware data buffer by buffer ID (address) + * + * @param hw Beginning address of the peripheral registers + * @param byte_id Start ID (address) of the hardware buffer to be read + * @param data Address of a buffer to read data from hardware data buffer + * @param len Length to read, in bytes. + */ +static inline void spi_ll_read_buffer_byte(spi_dev_t *hw, int byte_id, uint8_t *out_data, int len) +{ + while (len > 0) { + uint32_t word = hw->data_buf[byte_id / 4]; + int offset = byte_id % 4; + int copy_len = 4 - offset; + if (copy_len > len) copy_len = len; + + memcpy(out_data, ((uint8_t *)&word) + offset, copy_len); + byte_id += copy_len; + out_data += copy_len; + len -= copy_len; + } +} + +/*------------------------------------------------------------------------------ + * Configs: mode + *----------------------------------------------------------------------------*/ +/** + * Enable/disable the postive-cs feature. + * + * @param hw Beginning address of the peripheral registers. + * @param cs One of the CS (0-2) to enable/disable the feature. + * @param pos_cs True to enable the feature, otherwise disable (default). + */ +static inline void spi_ll_master_set_pos_cs(spi_dev_t *hw, int cs, uint32_t pos_cs) +{ + if (pos_cs) { + hw->misc.master_cs_pol |= (1 << cs); + } else { + hw->misc.master_cs_pol &= ~(1 << cs); + } +} + +/** + * Enable/disable the LSBFIRST feature for TX data. + * + * @param hw Beginning address of the peripheral registers. + * @param lsbfirst True if LSB of TX data to be sent first, otherwise MSB is sent first (default). + */ +static inline void spi_ll_set_tx_lsbfirst(spi_dev_t *hw, bool lsbfirst) +{ + hw->ctrl.wr_bit_order = lsbfirst; +} + +/** + * Enable/disable the LSBFIRST feature for RX data. + * + * @param hw Beginning address of the peripheral registers. + * @param lsbfirst True if first bit received as LSB, otherwise as MSB (default). + */ +static inline void spi_ll_set_rx_lsbfirst(spi_dev_t *hw, bool lsbfirst) +{ + hw->ctrl.rd_bit_order = lsbfirst; +} + +/** + * Set SPI mode for the peripheral as master. + * + * @param hw Beginning address of the peripheral registers. + * @param mode SPI mode to work at, 0-3. + */ +static inline void spi_ll_master_set_mode(spi_dev_t *hw, uint8_t mode) +{ + //Configure polarity + if (mode == 0) { + hw->misc.ck_idle_edge = 0; + hw->user.ck_out_edge = 0; + } else if (mode == 1) { + hw->misc.ck_idle_edge = 0; + hw->user.ck_out_edge = 1; + } else if (mode == 2) { + hw->misc.ck_idle_edge = 1; + hw->user.ck_out_edge = 1; + } else if (mode == 3) { + hw->misc.ck_idle_edge = 1; + hw->user.ck_out_edge = 0; + } +} + +/** + * Set SPI mode for the peripheral as slave. + * + * @param hw Beginning address of the peripheral registers. + * @param mode SPI mode to work at, 0-3. + */ +static inline void spi_ll_slave_set_mode(spi_dev_t *hw, const int mode, bool dma_used) +{ + if (mode == 0) { + hw->misc.ck_idle_edge = 0; + hw->user.rsck_i_edge = 0; + hw->user.tsck_i_edge = 0; + hw->slave.clk_mode_13 = 0; + } else if (mode == 1) { + hw->misc.ck_idle_edge = 0; + hw->user.rsck_i_edge = 1; + hw->user.tsck_i_edge = 1; + hw->slave.clk_mode_13 = 1; + } else if (mode == 2) { + hw->misc.ck_idle_edge = 1; + hw->user.rsck_i_edge = 1; + hw->user.tsck_i_edge = 1; + hw->slave.clk_mode_13 = 0; + } else if (mode == 3) { + hw->misc.ck_idle_edge = 1; + hw->user.rsck_i_edge = 0; + hw->user.tsck_i_edge = 0; + hw->slave.clk_mode_13 = 1; + } + hw->slave.rsck_data_out = 0; +} + +/** + * Set SPI to work in full duplex or half duplex mode. + * + * @param hw Beginning address of the peripheral registers. + * @param half_duplex True to work in half duplex mode, otherwise in full duplex mode. + */ +static inline void spi_ll_set_half_duplex(spi_dev_t *hw, bool half_duplex) +{ + hw->user.doutdin = !half_duplex; +} + +/** + * Set SPI to work in SIO mode or not. + * + * SIO is a mode which MOSI and MISO share a line. The device MUST work in half-duplexmode. + * + * @param hw Beginning address of the peripheral registers. + * @param sio_mode True to work in SIO mode, otherwise false. + */ +static inline void spi_ll_set_sio_mode(spi_dev_t *hw, int sio_mode) +{ + hw->user.sio = sio_mode; +} + +/** + * Configure the io mode for the master to work at. + * + * @param hw Beginning address of the peripheral registers. + * @param io_mode IO mode to work at, see ``spi_ll_io_mode_t``. + */ +static inline void spi_ll_master_set_io_mode(spi_dev_t *hw, spi_ll_io_mode_t io_mode) +{ + if (io_mode == SPI_LL_IO_MODE_DIO || io_mode == SPI_LL_IO_MODE_DUAL) { + hw->ctrl.fcmd_dual = (io_mode == SPI_LL_IO_MODE_DIO) ? 1 : 0; + hw->ctrl.faddr_dual = (io_mode == SPI_LL_IO_MODE_DIO) ? 1 : 0; + hw->ctrl.fread_dual = 1; + hw->user.fwrite_dual = 1; + hw->ctrl.fcmd_quad = 0; + hw->ctrl.faddr_quad = 0; + hw->ctrl.fread_quad = 0; + hw->user.fwrite_quad = 0; + } else if (io_mode == SPI_LL_IO_MODE_QIO || io_mode == SPI_LL_IO_MODE_QUAD) { + hw->ctrl.fcmd_quad = (io_mode == SPI_LL_IO_MODE_QIO) ? 1 : 0; + hw->ctrl.faddr_quad = (io_mode == SPI_LL_IO_MODE_QIO) ? 1 : 0; + hw->ctrl.fread_quad = 1; + hw->user.fwrite_quad = 1; + hw->ctrl.fcmd_dual = 0; + hw->ctrl.faddr_dual = 0; + hw->ctrl.fread_dual = 0; + hw->user.fwrite_dual = 0; + } else { + hw->ctrl.fcmd_dual = 0; + hw->ctrl.faddr_dual = 0; + hw->ctrl.fread_dual = 0; + hw->user.fwrite_dual = 0; + hw->ctrl.fcmd_quad = 0; + hw->ctrl.faddr_quad = 0; + hw->ctrl.fread_quad = 0; + hw->user.fwrite_quad = 0; + } +} + +/** + * Set the SPI slave to work in segment transaction mode + * + * @param hw Beginning address of the peripheral registers. + * @param seg_trans True to work in seg mode, otherwise false. + */ +static inline void spi_ll_slave_set_seg_mode(spi_dev_t *hw, bool seg_trans) +{ + hw->dma_conf.dma_seg_trans_en = seg_trans; + hw->dma_conf.rx_eof_en = seg_trans; +} + +/** + * Select one of the CS to use in current transaction. + * + * @param hw Beginning address of the peripheral registers. + * @param cs_id The cs to use, 0-2, otherwise none of them is used. + */ +static inline void spi_ll_master_select_cs(spi_dev_t *hw, int cs_id) +{ + hw->misc.cs0_dis = (cs_id == 0) ? 0 : 1; + hw->misc.cs1_dis = (cs_id == 1) ? 0 : 1; + hw->misc.cs2_dis = (cs_id == 2) ? 0 : 1; + hw->misc.cs3_dis = (cs_id == 3) ? 0 : 1; + hw->misc.cs4_dis = (cs_id == 4) ? 0 : 1; + hw->misc.cs5_dis = (cs_id == 5) ? 0 : 1; +} + +/*------------------------------------------------------------------------------ + * Configs: parameters + *----------------------------------------------------------------------------*/ +/** + * Set the clock for master by stored value. + * + * @param hw Beginning address of the peripheral registers. + * @param val Stored clock configuration calculated before (by ``spi_ll_cal_clock``). + */ +static inline void spi_ll_master_set_clock_by_reg(spi_dev_t *hw, const spi_ll_clock_val_t *val) +{ + hw->clock.val = *(uint32_t *)val; +} + +/** + * Get the frequency of given dividers. Don't use in app. + * + * @param fapb APB clock of the system. + * @param pre Pre devider. + * @param n Main divider. + * + * @return Frequency of given dividers. + */ +static inline int spi_ll_freq_for_pre_n(int fapb, int pre, int n) +{ + return (fapb / (pre * n)); +} + +/** + * Calculate the nearest frequency avaliable for master. + * + * @param fapb APB clock of the system. + * @param hz Frequncy desired. + * @param duty_cycle Duty cycle desired. + * @param out_reg Output address to store the calculated clock configurations for the return frequency. + * + * @return Actual (nearest) frequency. + */ +static inline int spi_ll_master_cal_clock(int fapb, int hz, int duty_cycle, spi_ll_clock_val_t *out_reg) +{ + typeof(GPSPI2.clock) reg; + int eff_clk; + + //In hw, n, h and l are 1-64, pre is 1-8K. Value written to register is one lower than used value. + if (hz > ((fapb / 4) * 3)) { + //Using Fapb directly will give us the best result here. + reg.clkcnt_l = 0; + reg.clkcnt_h = 0; + reg.clkcnt_n = 0; + reg.clkdiv_pre = 0; + reg.clk_equ_sysclk = 1; + eff_clk = fapb; + } else { + //For best duty cycle resolution, we want n to be as close to 32 as possible, but + //we also need a pre/n combo that gets us as close as possible to the intended freq. + //To do this, we bruteforce n and calculate the best pre to go along with that. + //If there's a choice between pre/n combos that give the same result, use the one + //with the higher n. + int pre, n, h, l; + int bestn = -1; + int bestpre = -1; + int besterr = 0; + int errval; + for (n = 2; n <= 64; n++) { //Start at 2: we need to be able to set h/l so we have at least one high and one low pulse. + //Effectively, this does pre=round((fapb/n)/hz). + pre = ((fapb / n) + (hz / 2)) / hz; + if (pre <= 0) { + pre = 1; + } + if (pre > 16) { + pre = 16; + } + errval = abs(spi_ll_freq_for_pre_n(fapb, pre, n) - hz); + if (bestn == -1 || errval <= besterr) { + besterr = errval; + bestn = n; + bestpre = pre; + } + } + + n = bestn; + pre = bestpre; + l = n; + //This effectively does round((duty_cycle*n)/256) + h = (duty_cycle * n + 127) / 256; + if (h <= 0) { + h = 1; + } + + reg.clk_equ_sysclk = 0; + reg.clkcnt_n = n - 1; + reg.clkdiv_pre = pre - 1; + reg.clkcnt_h = h - 1; + reg.clkcnt_l = l - 1; + eff_clk = spi_ll_freq_for_pre_n(fapb, pre, n); + } + if (out_reg != NULL) { + *(uint32_t *)out_reg = reg.val; + } + return eff_clk; +} + +/** + * Calculate and set clock for SPI master according to desired parameters. + * + * This takes long, suggest to calculate the configuration during + * initialization by ``spi_ll_master_cal_clock`` and store the result, then + * configure the clock by stored value when used by + * ``spi_ll_msater_set_clock_by_reg``. + * + * @param hw Beginning address of the peripheral registers. + * @param fapb APB clock of the system. + * @param hz Frequncy desired. + * @param duty_cycle Duty cycle desired. + * + * @return Actual frequency that is used. + */ +static inline int spi_ll_master_set_clock(spi_dev_t *hw, int fapb, int hz, int duty_cycle) +{ + spi_ll_clock_val_t reg_val; + int freq = spi_ll_master_cal_clock(fapb, hz, duty_cycle, ®_val); + spi_ll_master_set_clock_by_reg(hw, ®_val); + return freq; +} + +/** + * Set the mosi delay after the output edge to the signal. (Preview) + * + * The delay mode/num is a Espressif conception, may change in the new chips. + * + * @param hw Beginning address of the peripheral registers. + * @param delay_mode Delay mode, see TRM. + * @param delay_num APB clocks to delay. + */ +static inline void spi_ll_set_mosi_delay(spi_dev_t *hw, int delay_mode, int delay_num) +{ +} + +/** + * Set the miso delay applied to the input signal before the internal peripheral. (Preview) + * + * The delay mode/num is a Espressif conception, may change in the new chips. + * + * @param hw Beginning address of the peripheral registers. + * @param delay_mode Delay mode, see TRM. + * @param delay_num APB clocks to delay. + */ +static inline void spi_ll_set_miso_delay(spi_dev_t *hw, int delay_mode, int delay_num) +{ +} + +/** + * Set the delay of SPI clocks before the CS inactive edge after the last SPI clock. + * + * @param hw Beginning address of the peripheral registers. + * @param hold Delay of SPI clocks after the last clock, 0 to disable the hold phase. + */ +static inline void spi_ll_master_set_cs_hold(spi_dev_t *hw, int hold) +{ + hw->user1.cs_hold_time = hold - 1; + hw->user.cs_hold = hold ? 1 : 0; +} + +/** + * Set the delay of SPI clocks before the first SPI clock after the CS active edge. + * + * Note ESP32 doesn't support to use this feature when command/address phases + * are used in full duplex mode. + * + * @param hw Beginning address of the peripheral registers. + * @param setup Delay of SPI clocks after the CS active edge, 0 to disable the setup phase. + */ +static inline void spi_ll_master_set_cs_setup(spi_dev_t *hw, uint8_t setup) +{ + hw->user1.cs_setup_time = setup - 1; + hw->user.cs_setup = setup ? 1 : 0; +} + +/*------------------------------------------------------------------------------ + * Configs: data + *----------------------------------------------------------------------------*/ +/** + * Set the output length (master). + * This should be called before master setting MISO(input) length + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen output length, in bits. + */ +static inline void spi_ll_set_mosi_bitlen(spi_dev_t *hw, size_t bitlen) +{ + if (bitlen > 0) { + hw->ms_dlen.ms_data_bitlen = bitlen - 1; + } +} + +/** + * Set the input length (master). + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen input length, in bits. + */ +static inline void spi_ll_set_miso_bitlen(spi_dev_t *hw, size_t bitlen) +{ + if (bitlen > 0) { + hw->ms_dlen.ms_data_bitlen = bitlen - 1; + } +} + +/** + * Set the maximum input length (slave). + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen Input length, in bits. + */ +static inline void spi_ll_slave_set_rx_bitlen(spi_dev_t *hw, size_t bitlen) +{ + spi_ll_set_mosi_bitlen(hw, bitlen); +} + +/** + * Set the maximum output length (slave). + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen Output length, in bits. + */ +static inline void spi_ll_slave_set_tx_bitlen(spi_dev_t *hw, size_t bitlen) +{ + spi_ll_set_mosi_bitlen(hw, bitlen); +} + +/** + * Set the length of command phase. + * + * When in 4-bit mode, the SPI cycles of the phase will be shorter. E.g. 16-bit + * command phases takes 4 cycles in 4-bit mode. + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen Length of command phase, in bits. 0 to disable the command phase. + */ +static inline void spi_ll_set_command_bitlen(spi_dev_t *hw, int bitlen) +{ + hw->user2.usr_command_bitlen = bitlen - 1; + hw->user.usr_command = bitlen ? 1 : 0; +} + +/** + * Set the length of address phase. + * + * When in 4-bit mode, the SPI cycles of the phase will be shorter. E.g. 16-bit + * address phases takes 4 cycles in 4-bit mode. + * + * @param hw Beginning address of the peripheral registers. + * @param bitlen Length of address phase, in bits. 0 to disable the address phase. + */ +static inline void spi_ll_set_addr_bitlen(spi_dev_t *hw, int bitlen) +{ + hw->user1.usr_addr_bitlen = bitlen - 1; + hw->user.usr_addr = bitlen ? 1 : 0; +} + +/** + * Set the address value in an intuitive way. + * + * The length and lsbfirst is required to shift and swap the address to the right place. + * + * @param hw Beginning address of the peripheral registers. + * @param address Address to set + * @param addrlen Length of the address phase + * @param lsbfirst Whether the LSB first feature is enabled. + */ +static inline void spi_ll_set_address(spi_dev_t *hw, uint64_t addr, int addrlen, uint32_t lsbfirst) +{ + if (lsbfirst) { + /* The output address start from the LSB of the highest byte, i.e. + * addr[24] -> addr[31] + * ... + * addr[0] -> addr[7] + * So swap the byte order to let the LSB sent first. + */ + addr = HAL_SWAP32(addr); + //otherwise only addr register is sent + hw->addr = addr; + } else { + // shift the address to MSB of addr register. + // output address will be sent from MSB to LSB of addr register + hw->addr = addr << (32 - addrlen); + } +} + +/** + * Set the command value in an intuitive way. + * + * The length and lsbfirst is required to shift and swap the command to the right place. + * + * @param hw Beginning command of the peripheral registers. + * @param command Command to set + * @param addrlen Length of the command phase + * @param lsbfirst Whether the LSB first feature is enabled. + */ +static inline void spi_ll_set_command(spi_dev_t *hw, uint16_t cmd, int cmdlen, bool lsbfirst) +{ + if (lsbfirst) { + // The output command start from bit0 to bit 15, kept as is. + hw->user2.usr_command_value = cmd; + } else { + /* Output command will be sent from bit 7 to 0 of command_value, and + * then bit 15 to 8 of the same register field. Shift and swap to send + * more straightly. + */ + hw->user2.usr_command_value = HAL_SPI_SWAP_DATA_TX(cmd, cmdlen); + } +} + +/** + * Set dummy clocks to output before RX phase (master), or clocks to skip + * before the data phase and after the address phase (slave). + * + * Note this phase is also used to compensate RX timing in half duplex mode. + * + * @param hw Beginning address of the peripheral registers. + * @param dummy_n Dummy cycles used. 0 to disable the dummy phase. + */ +static inline void spi_ll_set_dummy(spi_dev_t *hw, int dummy_n) +{ + hw->user.usr_dummy = dummy_n ? 1 : 0; + hw->user1.usr_dummy_cyclelen = dummy_n - 1; +} + +/** + * Enable/disable the RX data phase. + * + * @param hw Beginning address of the peripheral registers. + * @param enable True if RX phase exist, otherwise false. + */ +static inline void spi_ll_enable_miso(spi_dev_t *hw, int enable) +{ + hw->user.usr_miso = enable; +} + +/** + * Enable/disable the TX data phase. + * + * @param hw Beginning address of the peripheral registers. + * @param enable True if TX phase exist, otherwise false. + */ +static inline void spi_ll_enable_mosi(spi_dev_t *hw, int enable) +{ + hw->user.usr_mosi = enable; +} + +/** + * Get the received bit length of the slave. + * + * @param hw Beginning address of the peripheral registers. + * + * @return Received bits of the slave. + */ +static inline uint32_t spi_ll_slave_get_rcv_bitlen(spi_dev_t *hw) +{ + return hw->slave1.data_bitlen; +} + +/*------------------------------------------------------------------------------ + * Interrupts + *----------------------------------------------------------------------------*/ +//helper macros to generate code for each interrupts +#define FOR_EACH_ITEM(op, list) do { list(op) } while(0) +#define INTR_LIST(item) \ + item(SPI_LL_INTR_TRANS_DONE, dma_int_ena.trans_done, dma_int_raw.trans_done, dma_int_clr.trans_done=1) \ + item(SPI_LL_INTR_RDBUF, dma_int_ena.rd_buf_done, dma_int_raw.rd_buf_done, dma_int_clr.rd_buf_done=1) \ + item(SPI_LL_INTR_WRBUF, dma_int_ena.wr_buf_done, dma_int_raw.wr_buf_done, dma_int_clr.wr_buf_done=1) \ + item(SPI_LL_INTR_RDDMA, dma_int_ena.rd_dma_done, dma_int_raw.rd_dma_done, dma_int_clr.rd_dma_done=1) \ + item(SPI_LL_INTR_WRDMA, dma_int_ena.wr_dma_done, dma_int_raw.wr_dma_done, dma_int_clr.wr_dma_done=1) \ + item(SPI_LL_INTR_SEG_DONE, dma_int_ena.dma_seg_trans_done, dma_int_raw.dma_seg_trans_done, dma_int_clr.dma_seg_trans_done=1) \ + item(SPI_LL_INTR_CMD7, dma_int_ena.cmd7, dma_int_raw.cmd7, dma_int_clr.cmd7=1) \ + item(SPI_LL_INTR_CMD8, dma_int_ena.cmd8, dma_int_raw.cmd8, dma_int_clr.cmd8=1) \ + item(SPI_LL_INTR_CMD9, dma_int_ena.cmd9, dma_int_raw.cmd9, dma_int_clr.cmd9=1) \ + item(SPI_LL_INTR_CMDA, dma_int_ena.cmda, dma_int_raw.cmda, dma_int_clr.cmda=1) + + +static inline void spi_ll_enable_intr(spi_dev_t* hw, spi_ll_intr_t intr_mask) +{ +#define ENA_INTR(intr_bit, en_reg, ...) if (intr_mask & (intr_bit)) hw->en_reg = 1; + FOR_EACH_ITEM(ENA_INTR, INTR_LIST); +#undef ENA_INTR +} + +static inline void spi_ll_disable_intr(spi_dev_t* hw, spi_ll_intr_t intr_mask) +{ +#define DIS_INTR(intr_bit, en_reg, ...) if (intr_mask & (intr_bit)) hw->en_reg = 0; + FOR_EACH_ITEM(DIS_INTR, INTR_LIST); +#undef DIS_INTR +} + +static inline void spi_ll_set_intr(spi_dev_t* hw, spi_ll_intr_t intr_mask) +{ +#define SET_INTR(intr_bit, _, st_reg, ...) if (intr_mask & (intr_bit)) hw->st_reg = 1; + FOR_EACH_ITEM(SET_INTR, INTR_LIST); +#undef SET_INTR +} + +static inline void spi_ll_clear_intr(spi_dev_t* hw, spi_ll_intr_t intr_mask) +{ +#define CLR_INTR(intr_bit, _, __, clr_op) if (intr_mask & (intr_bit)) hw->clr_op; + FOR_EACH_ITEM(CLR_INTR, INTR_LIST); +#undef CLR_INTR +} + +static inline bool spi_ll_get_intr(spi_dev_t* hw, spi_ll_intr_t intr_mask) +{ +#define GET_INTR(intr_bit, _, st_reg, ...) if (intr_mask & (intr_bit) && hw->st_reg) return true; + FOR_EACH_ITEM(GET_INTR, INTR_LIST); + return false; +#undef GET_INTR +} + +#undef FOR_EACH_ITEM +#undef INTR_LIST + +/** + * Disable the trans_done interrupt. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_disable_int(spi_dev_t *hw) +{ + hw->dma_int_ena.trans_done = 0; +} + +/** + * Clear the trans_done interrupt. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_clear_int_stat(spi_dev_t *hw) +{ + hw->dma_int_raw.trans_done = 0; +} + +/** + * Set the trans_done interrupt. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_set_int_stat(spi_dev_t *hw) +{ + hw->dma_int_raw.trans_done = 1; +} + +/** + * Enable the trans_done interrupt. + * + * @param hw Beginning address of the peripheral registers. + */ +static inline void spi_ll_enable_int(spi_dev_t *hw) +{ + hw->dma_int_ena.trans_done = 1; +} + +/*------------------------------------------------------------------------------ + * Slave HD + *----------------------------------------------------------------------------*/ +static inline void spi_ll_slave_hd_set_len_cond(spi_dev_t* hw, spi_ll_trans_len_cond_t cond_mask) +{ + hw->slave.rdbuf_bitlen_en = (cond_mask & SPI_LL_TRANS_LEN_COND_RDBUF) ? 1 : 0; + hw->slave.wrbuf_bitlen_en = (cond_mask & SPI_LL_TRANS_LEN_COND_WRBUF) ? 1 : 0; + hw->slave.rddma_bitlen_en = (cond_mask & SPI_LL_TRANS_LEN_COND_RDDMA) ? 1 : 0; + hw->slave.wrdma_bitlen_en = (cond_mask & SPI_LL_TRANS_LEN_COND_WRDMA) ? 1 : 0; +} + +static inline int spi_ll_slave_get_rx_byte_len(spi_dev_t* hw) +{ + return hw->slave1.data_bitlen / 8; +} + +static inline uint32_t spi_ll_slave_hd_get_last_addr(spi_dev_t* hw) +{ + return hw->slave1.last_addr; +} + +#undef SPI_LL_RST_MASK +#undef SPI_LL_UNUSED_INT_MASK + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spimem_flash_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spimem_flash_ll.h new file mode 100644 index 00000000..e2db0800 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/spimem_flash_ll.h @@ -0,0 +1,554 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The ll is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +// The Lowlevel layer for SPI Flash + +#pragma once + +#include +#include // For MIN/MAX +#include +#include + +#include "soc/spi_periph.h" +#include "hal/spi_types.h" +#include "hal/spi_flash_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define spimem_flash_ll_get_hw(host_id) (((host_id)==SPI1_HOST ? &SPIMEM1 : NULL )) +#define spimem_flash_ll_hw_get_id(dev) ((dev) == (void*)&SPIMEM1? SPI1_HOST: -1) + +typedef typeof(SPIMEM1.clock) spimem_flash_ll_clock_reg_t; + +//Supported clock register values +#define SPIMEM_FLASH_LL_CLKREG_VAL_5MHZ ((spimem_flash_ll_clock_reg_t){.val=0x000F070F}) ///< Clock set to 5 MHz +#define SPIMEM_FLASH_LL_CLKREG_VAL_10MHZ ((spimem_flash_ll_clock_reg_t){.val=0x00070307}) ///< Clock set to 10 MHz +#define SPIMEM_FLASH_LL_CLKREG_VAL_20MHZ ((spimem_flash_ll_clock_reg_t){.val=0x00030103}) ///< Clock set to 20 MHz +#define SPIMEM_FLASH_LL_CLKREG_VAL_26MHZ ((spimem_flash_ll_clock_reg_t){.val=0x00020002}) ///< Clock set to 26 MHz +#define SPIMEM_FLASH_LL_CLKREG_VAL_40MHZ ((spimem_flash_ll_clock_reg_t){.val=0x00010001}) ///< Clock set to 40 MHz +#define SPIMEM_FLASH_LL_CLKREG_VAL_80MHZ ((spimem_flash_ll_clock_reg_t){.val=0x80000000}) ///< Clock set to 80 MHz + +/*------------------------------------------------------------------------------ + * Control + *----------------------------------------------------------------------------*/ +/** + * Reset peripheral registers before configuration and starting control + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_reset(spi_mem_dev_t *dev) +{ + dev->user.val = 0; + dev->ctrl.val = 0; +} + +/** + * Check whether the previous operation is done. + * + * @param dev Beginning address of the peripheral registers. + * + * @return true if last command is done, otherwise false. + */ +static inline bool spimem_flash_ll_cmd_is_done(const spi_mem_dev_t *dev) +{ + return (dev->cmd.val == 0); +} + +/** + * Erase the flash chip. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_erase_chip(spi_mem_dev_t *dev) +{ + dev->cmd.flash_ce = 1; +} + +/** + * Erase the sector, the address should be set by spimem_flash_ll_set_address. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_erase_sector(spi_mem_dev_t *dev) +{ + dev->ctrl.val = 0; + dev->cmd.flash_se = 1; +} + +/** + * Erase the block, the address should be set by spimem_flash_ll_set_address. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_erase_block(spi_mem_dev_t *dev) +{ + dev->cmd.flash_be = 1; +} + +/** + * Suspend erase/program operation. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_suspend(spi_mem_dev_t *dev) +{ + dev->flash_sus_ctrl.flash_pes = 1; +} + +/** + * Resume suspended erase/program operation. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_resume(spi_mem_dev_t *dev) +{ + dev->flash_sus_ctrl.flash_per = 1; +} + +/** + * Initialize auto suspend mode, and esp32c3 doesn't support disable auto-suspend. + * + * @param dev Beginning address of the peripheral registers. + * @param auto_sus Enable/disable Flash Auto-Suspend. + */ +static inline void spimem_flash_ll_auto_suspend_init(spi_mem_dev_t *dev, bool auto_sus) +{ + dev->flash_sus_ctrl.flash_pes_en = auto_sus; +} + +/** + * Initialize auto resume mode + * + * @param dev Beginning address of the peripheral registers. + * @param auto_res Enable/Disable Flash Auto-Resume. + * + */ +static inline void spimem_flash_ll_auto_resume_init(spi_mem_dev_t *dev, bool auto_res) +{ + dev->flash_sus_ctrl.pes_per_en = auto_res; +} + +/** + * Setup the flash suspend command, may vary from chips to chips. + * + * @param dev Beginning address of the peripheral registers. + * @param sus_cmd Flash suspend command. + * + */ +static inline void spimem_flash_ll_suspend_cmd_setup(spi_mem_dev_t *dev, uint32_t sus_cmd) +{ + dev->flash_sus_cmd.flash_pes_command = sus_cmd; +} + +/** + * Setup the flash resume command, may vary from chips to chips. + * + * @param dev Beginning address of the peripheral registers. + * @param res_cmd Flash resume command. + * + */ +static inline void spimem_flash_ll_resume_cmd_setup(spi_mem_dev_t *dev, uint32_t res_cmd) +{ + dev->flash_sus_cmd.flash_per_command = res_cmd; +} + +/** + * Setup the flash read suspend status command, may vary from chips to chips. + * + * @param dev Beginning address of the peripheral registers. + * @param pesr_cmd Flash read suspend status command. + * + */ +static inline void spimem_flash_ll_rd_sus_cmd_setup(spi_mem_dev_t *dev, uint32_t pesr_cmd) +{ + dev->flash_sus_cmd.wait_pesr_command = pesr_cmd; +} + +/** + * Setup to check SUS/SUS1/SUS2 to ensure the suspend status of flashs. + * + * @param dev Beginning address of the peripheral registers. + * @param sus_check_sus_en 1: enable, 0: disable. + * + */ +static inline void spimem_flash_ll_sus_check_sus_setup(spi_mem_dev_t *dev, bool sus_check_sus_en) +{ + dev->flash_sus_ctrl.sus_timeout_cnt = 5; + dev->flash_sus_ctrl.pes_end_en = sus_check_sus_en; +} + +/** + * Setup to check SUS/SUS1/SUS2 to ensure the resume status of flashs. + * + * @param dev Beginning address of the peripheral registers. + * @param sus_check_sus_en 1: enable, 0: disable. + * + */ +static inline void spimem_flash_ll_res_check_sus_setup(spi_mem_dev_t *dev, bool res_check_sus_en) +{ + dev->flash_sus_ctrl.sus_timeout_cnt = 5; + dev->flash_sus_ctrl.per_end_en = res_check_sus_en; +} + +/** + * Set 8 bit command to read suspend status + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_set_read_sus_status(spi_mem_dev_t *dev, uint32_t sus_conf) +{ + dev->flash_sus_ctrl.frd_sus_2b = 0; + dev->flash_sus_ctrl.pesr_end_msk = sus_conf; +} + +/** + * Initialize auto wait idle mode + * + * @param dev Beginning address of the peripheral registers. + * @param auto_waiti Enable/disable auto wait-idle function + */ +static inline void spimem_flash_ll_auto_wait_idle_init(spi_mem_dev_t *dev, bool auto_waiti) +{ + dev->flash_waiti_ctrl.waiti_cmd = 0x05; + dev->flash_sus_ctrl.flash_per_wait_en = auto_waiti; + dev->flash_sus_ctrl.flash_pes_wait_en = auto_waiti; +} + +/** + * Return the suspend status of erase or program operations. + * + * @param dev Beginning address of the peripheral registers. + * + * @return true if suspended, otherwise false. + */ +static inline bool spimem_flash_ll_sus_status(spi_mem_dev_t *dev) +{ + return dev->sus_status.flash_sus; +} + +/** + * Enable/disable write protection for the flash chip. + * + * @param dev Beginning address of the peripheral registers. + * @param wp true to enable the protection, false to disable (write enable). + */ +static inline void spimem_flash_ll_set_write_protect(spi_mem_dev_t *dev, bool wp) +{ + if (wp) { + dev->cmd.flash_wrdi = 1; + } else { + dev->cmd.flash_wren = 1; + } +} + +/** + * Get the read data from the buffer after ``spimem_flash_ll_read`` is done. + * + * @param dev Beginning address of the peripheral registers. + * @param buffer Buffer to hold the output data + * @param read_len Length to get out of the buffer + */ +static inline void spimem_flash_ll_get_buffer_data(spi_mem_dev_t *dev, void *buffer, uint32_t read_len) +{ + if (((intptr_t)buffer % 4 == 0) && (read_len % 4 == 0)) { + // If everything is word-aligned, do a faster memcpy + memcpy(buffer, (void *)dev->data_buf, read_len); + } else { + // Otherwise, slow(er) path copies word by word + int copy_len = read_len; + for (int i = 0; i < (read_len + 3) / 4; i++) { + int word_len = MIN(sizeof(uint32_t), copy_len); + uint32_t word = dev->data_buf[i]; + memcpy(buffer, &word, word_len); + buffer = (void *)((intptr_t)buffer + word_len); + copy_len -= word_len; + } + } +} + +/** + * Set the data to be written in the data buffer. + * + * @param dev Beginning address of the peripheral registers. + * @param buffer Buffer holding the data + * @param length Length of data in bytes. + */ +static inline void spimem_flash_ll_set_buffer_data(spi_mem_dev_t *dev, const void *buffer, uint32_t length) +{ + // Load data registers, word at a time + int num_words = (length + 3) / 4; + for (int i = 0; i < num_words; i++) { + uint32_t word = 0; + uint32_t word_len = MIN(length, sizeof(word)); + memcpy(&word, buffer, word_len); + dev->data_buf[i] = word; + length -= word_len; + buffer = (void *)((intptr_t)buffer + word_len); + } +} + + +/** + * Program a page of the flash chip. Call ``spimem_flash_ll_set_address`` before + * this to set the address to program. + * + * @param dev Beginning address of the peripheral registers. + * @param buffer Buffer holding the data to program + * @param length Length to program. + */ +static inline void spimem_flash_ll_program_page(spi_mem_dev_t *dev, const void *buffer, uint32_t length) +{ + dev->user.usr_dummy = 0; + spimem_flash_ll_set_buffer_data(dev, buffer, length); + dev->cmd.flash_pp = 1; +} + +/** + * Trigger a user defined transaction. All phases, including command, address, dummy, and the data phases, + * should be configured before this is called. + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_user_start(spi_mem_dev_t *dev) +{ + dev->cmd.usr = 1; +} + +/** + * Check whether the host is idle to perform new commands. + * + * @param dev Beginning address of the peripheral registers. + * + * @return true if the host is idle, otherwise false + */ +static inline bool spimem_flash_ll_host_idle(const spi_mem_dev_t *dev) +{ + return dev->fsm.spi0_mst_st == 0; +} + +/** + * Set phases for user-defined transaction to read + * + * @param dev Beginning address of the peripheral registers. + */ +static inline void spimem_flash_ll_read_phase(spi_mem_dev_t *dev) +{ + typeof (dev->user) user = { + .usr_command = 1, + .usr_mosi = 0, + .usr_miso = 1, + .usr_addr = 1, + }; + dev->user = user; +} +/*------------------------------------------------------------------------------ + * Configs + *----------------------------------------------------------------------------*/ +/** + * Select which pin to use for the flash + * + * @param dev Beginning address of the peripheral registers. + * @param pin Pin ID to use, 0-2. Set to other values to disable all the CS pins. + */ +static inline void spimem_flash_ll_set_cs_pin(spi_mem_dev_t *dev, int pin) +{ + dev->misc.cs0_dis = (pin == 0) ? 0 : 1; + dev->misc.cs1_dis = (pin == 1) ? 0 : 1; +} + +/** + * Set the read io mode. + * + * @param dev Beginning address of the peripheral registers. + * @param read_mode I/O mode to use in the following transactions. + */ +static inline void spimem_flash_ll_set_read_mode(spi_mem_dev_t *dev, esp_flash_io_mode_t read_mode) +{ + typeof (dev->ctrl) ctrl = dev->ctrl; + ctrl.val &= ~(SPI_MEM_FREAD_QIO_M | SPI_MEM_FREAD_QUAD_M | SPI_MEM_FREAD_DIO_M | SPI_MEM_FREAD_DUAL_M); + ctrl.val |= SPI_MEM_FASTRD_MODE_M; + switch (read_mode) { + case SPI_FLASH_FASTRD: + //the default option + break; + case SPI_FLASH_QIO: + ctrl.fread_qio = 1; + break; + case SPI_FLASH_QOUT: + ctrl.fread_quad = 1; + break; + case SPI_FLASH_DIO: + ctrl.fread_dio = 1; + break; + case SPI_FLASH_DOUT: + ctrl.fread_dual = 1; + break; + case SPI_FLASH_SLOWRD: + ctrl.fastrd_mode = 0; + break; + default: + abort(); + } + dev->ctrl = ctrl; +} + +/** + * Set clock frequency to work at. + * + * @param dev Beginning address of the peripheral registers. + * @param clock_val pointer to the clock value to set + */ +static inline void spimem_flash_ll_set_clock(spi_mem_dev_t *dev, spimem_flash_ll_clock_reg_t *clock_val) +{ + dev->clock = *clock_val; +} + +/** + * Set the input length, in bits. + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of input, in bits. + */ +static inline void spimem_flash_ll_set_miso_bitlen(spi_mem_dev_t *dev, uint32_t bitlen) +{ + dev->user.usr_miso = bitlen > 0; + dev->miso_dlen.usr_miso_bit_len = bitlen ? (bitlen - 1) : 0; +} + +/** + * Set the output length, in bits (not including command, address and dummy + * phases) + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of output, in bits. + */ +static inline void spimem_flash_ll_set_mosi_bitlen(spi_mem_dev_t *dev, uint32_t bitlen) +{ + dev->user.usr_mosi = bitlen > 0; + dev->mosi_dlen.usr_mosi_bit_len = bitlen ? (bitlen - 1) : 0; +} + +/** + * Set the command. + * + * @param dev Beginning address of the peripheral registers. + * @param command Command to send + * @param bitlen Length of the command + */ +static inline void spimem_flash_ll_set_command(spi_mem_dev_t *dev, uint32_t command, uint32_t bitlen) +{ + dev->user.usr_command = 1; + typeof(dev->user2) user2 = { + .usr_command_value = command, + .usr_command_bitlen = (bitlen - 1), + }; + dev->user2 = user2; +} + +/** + * Get the address length that is set in register, in bits. + * + * @param dev Beginning address of the peripheral registers. + * + */ +static inline int spimem_flash_ll_get_addr_bitlen(spi_mem_dev_t *dev) +{ + return dev->user.usr_addr ? dev->user1.usr_addr_bitlen + 1 : 0; +} + +/** + * Set the address length to send, in bits. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param bitlen Length of the address, in bits + */ +static inline void spimem_flash_ll_set_addr_bitlen(spi_mem_dev_t *dev, uint32_t bitlen) +{ + dev->user1.usr_addr_bitlen = (bitlen - 1); + dev->user.usr_addr = bitlen ? 1 : 0; +} + +/** + * Set the address to send. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param addr Address to send + */ +static inline void spimem_flash_ll_set_address(spi_mem_dev_t *dev, uint32_t addr) +{ + dev->addr = addr; +} + +/** + * Set the address to send in user mode. Should be called before commands that requires the address e.g. erase sector, read, write... + * + * @param dev Beginning address of the peripheral registers. + * @param addr Address to send + */ +static inline void spimem_flash_ll_set_usr_address(spi_mem_dev_t *dev, uint32_t addr, uint32_t bitlen) +{ + (void)bitlen; + spimem_flash_ll_set_address(dev, addr); +} + +/** + * Set the length of dummy cycles. + * + * @param dev Beginning address of the peripheral registers. + * @param dummy_n Cycles of dummy phases + */ +static inline void spimem_flash_ll_set_dummy(spi_mem_dev_t *dev, uint32_t dummy_n) +{ + dev->user.usr_dummy = dummy_n ? 1 : 0; + dev->user1.usr_dummy_cyclelen = dummy_n - 1; +} + +/** + * Set D/Q output level during dummy phase + * + * @param dev Beginning address of the peripheral registers. + * @param out_en whether to enable IO output for dummy phase + * @param out_level dummy output level + */ +static inline void spimem_flash_ll_set_dummy_out(spi_mem_dev_t *dev, uint32_t out_en, uint32_t out_lev) +{ + dev->ctrl.fdummy_out = out_en; + dev->ctrl.q_pol = out_lev; + dev->ctrl.d_pol = out_lev; +} + +/** + * Set CS hold time. + * + * @param dev Beginning address of the peripheral registers. + * @param hold_n CS hold time config used by the host. + */ +static inline void spimem_flash_ll_set_hold(spi_mem_dev_t *dev, uint32_t hold_n) +{ + dev->ctrl2.cs_hold_time = hold_n - 1; + dev->user.cs_hold = (hold_n > 0? 1: 0); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/systimer_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/systimer_ll.h new file mode 100644 index 00000000..f0dab94c --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/systimer_ll.h @@ -0,0 +1,153 @@ +// Copyright 2020 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. +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/soc.h" +#include "soc/systimer_reg.h" + +// All these functions get invoked either from ISR or HAL that linked to IRAM. +// Always inline these functions even no gcc optimization is applied. + +/*******************counter*************************/ + +__attribute__((always_inline)) static inline void systimer_ll_enable_clock(void) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, SYS_TIMER_CLK_EN); +} + +__attribute__((always_inline)) static inline void systimer_ll_enable_counter(uint32_t counter_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (30 - counter_id)); +} + +__attribute__((always_inline)) static inline void systimer_ll_counter_can_stall_by_cpu(uint32_t counter_id, uint32_t cpu_id, bool can) +{ + if (can) { + REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << ((28 - counter_id * 2) - cpu_id)); + } else { + REG_CLR_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << ((28 - counter_id * 2) - cpu_id)); + } +} + +__attribute__((always_inline)) static inline void systimer_ll_counter_snapshot(uint32_t counter_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_UNIT0_OP_REG + 4 * counter_id, 1 << 30); +} + +__attribute__((always_inline)) static inline bool systimer_ll_is_counter_value_valid(uint32_t counter_id) +{ + return REG_GET_BIT(SYS_TIMER_SYSTIMER_UNIT0_OP_REG + 4 * counter_id, 1 << 29); +} + +__attribute__((always_inline)) static inline void systimer_ll_set_counter_value(uint32_t counter_id, uint64_t value) +{ + REG_WRITE(SYS_TIMER_SYSTIMER_UNIT0_LOAD_LO_REG + 8 * counter_id, value & 0xFFFFFFFF); + REG_WRITE(SYS_TIMER_SYSTIMER_UNIT0_LOAD_HI_REG, (value >> 32) & 0xFFFFF); +} + +__attribute__((always_inline)) static inline uint32_t systimer_ll_get_counter_value_low(uint32_t counter_id) +{ + return REG_READ(SYS_TIMER_SYSTIMER_UNIT0_VALUE_LO_REG + 8 * counter_id); +} + +__attribute__((always_inline)) static inline uint32_t systimer_ll_get_counter_value_high(uint32_t counter_id) +{ + return REG_READ(SYS_TIMER_SYSTIMER_UNIT0_VALUE_HI_REG + 8 * counter_id); +} + +__attribute__((always_inline)) static inline void systimer_ll_apply_counter_value(uint32_t counter_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_UNIT0_LOAD_REG + 4 * counter_id, SYS_TIMER_TIMER_UNIT0_LOAD); +} + +/*******************alarm*************************/ + +__attribute__((always_inline)) static inline void systimer_ll_set_alarm_target(uint32_t alarm_id, uint64_t value) +{ + REG_WRITE(SYS_TIMER_SYSTIMER_TARGET0_LO_REG + alarm_id * 8, value & 0xFFFFFFFF); + REG_WRITE(SYS_TIMER_SYSTIMER_TARGET0_HI_REG + alarm_id * 8, (value >> 32) & 0xFFFFF); +} + +__attribute__((always_inline)) static inline uint64_t systimer_ll_get_alarm_target(uint32_t alarm_id) +{ + return ((uint64_t) REG_READ(SYS_TIMER_SYSTIMER_TARGET0_HI_REG + alarm_id * 8) << 32) \ + | REG_READ(SYS_TIMER_SYSTIMER_TARGET0_LO_REG + alarm_id * 8); +} + +__attribute__((always_inline)) static inline void systimer_ll_connect_alarm_counter(uint32_t alarm_id, uint32_t counter_id) +{ + REG_SET_FIELD(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + 4 * alarm_id, SYS_TIMER_TARGET0_TIMER_UNIT_SEL, counter_id); +} + +__attribute__((always_inline)) static inline void systimer_ll_enable_alarm_oneshot(uint32_t alarm_id) +{ + REG_CLR_BIT(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD_MODE); +} + +__attribute__((always_inline)) static inline void systimer_ll_enable_alarm_period(uint32_t alarm_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD_MODE); +} + +__attribute__((always_inline)) static inline void systimer_ll_set_alarm_period(uint32_t alarm_id, uint32_t period) +{ + REG_SET_FIELD(SYS_TIMER_SYSTIMER_TARGET0_CONF_REG + alarm_id * 4, SYS_TIMER_TARGET0_PERIOD, period); +} + +__attribute__((always_inline)) static inline void systimer_ll_apply_alarm_value(uint32_t alarm_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_COMP0_LOAD_REG + alarm_id * 4, SYS_TIMER_TIMER_COMP0_LOAD); +} + +__attribute__((always_inline)) static inline void systimer_ll_disable_alarm(uint32_t alarm_id) +{ + REG_CLR_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (24 - alarm_id)); +} + +__attribute__((always_inline)) static inline void systimer_ll_enable_alarm(uint32_t alarm_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_CONF_REG, 1 << (24 - alarm_id)); +} + +/*******************interrupt*************************/ + +__attribute__((always_inline)) static inline void systimer_ll_enable_alarm_int(uint32_t alarm_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_INT_ENA_REG, 1 << alarm_id); +} + +__attribute__((always_inline)) static inline void systimer_ll_disable_alarm_int(uint32_t alarm_id) +{ + REG_CLR_BIT(SYS_TIMER_SYSTIMER_INT_ENA_REG, 1 << alarm_id); +} + +__attribute__((always_inline)) static inline bool systimer_ll_is_alarm_int_fired(uint32_t alarm_id) +{ + return REG_GET_BIT(SYS_TIMER_SYSTIMER_INT_RAW_REG, 1 << alarm_id); +} + +__attribute__((always_inline)) static inline void systimer_ll_clear_alarm_int(uint32_t alarm_id) +{ + REG_SET_BIT(SYS_TIMER_SYSTIMER_INT_CLR_REG, 1 << alarm_id); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/timer_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/timer_ll.h new file mode 100644 index 00000000..f3880b9a --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/timer_ll.h @@ -0,0 +1,430 @@ +// Copyright 2020 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. + +// The LL layer for Timer Group register operations. +// Note that most of the register operations in this layer are non-atomic operations. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "hal/timer_types.h" +#include "soc/timer_periph.h" + +_Static_assert(TIMER_INTR_T0 == TIMG_T0_INT_CLR, "Add mapping to LL interrupt handling, since it's no longer naturally compatible with the timer_intr_t"); +_Static_assert(TIMER_INTR_WDT == TIMG_WDT_INT_CLR, "Add mapping to LL interrupt handling, since it's no longer naturally compatible with the timer_intr_t"); + +typedef struct { + timg_dev_t *dev; + timer_idx_t idx; +} timer_ll_context_t; + +// Get timer group instance with giving group number +#define TIMER_LL_GET_HW(num) ((num == 0) ? (&TIMERG0) : (&TIMERG1)) + +/** + * @brief Set timer clock prescale value + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param divider Prescale value + * + * @return None + */ +static inline void timer_ll_set_divider(timg_dev_t *hw, timer_idx_t timer_num, uint32_t divider) +{ + assert(divider >= 2 && divider <= 65536); + if (divider >= 65536) { + divider = 0; + } + int timer_en = hw->hw_timer[timer_num].config.enable; + hw->hw_timer[timer_num].config.enable = 0; + hw->hw_timer[timer_num].config.divcnt_rst = 1; + hw->hw_timer[timer_num].config.divider = divider; + hw->hw_timer[timer_num].config.enable = timer_en; +} + +/** + * @brief Get timer clock prescale value + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param divider Pointer to accept the prescale value + * + * @return None + */ +static inline void timer_ll_get_divider(timg_dev_t *hw, timer_idx_t timer_num, uint32_t *divider) +{ + uint32_t d = hw->hw_timer[timer_num].config.divider; + if (d == 0) { + d = 65536; + } else if (d == 1) { + d = 2; + } + *divider = d; +} + +/** + * @brief Load counter value into time-base counter + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param load_val Counter value + * + * @return None + */ +static inline void timer_ll_set_counter_value(timg_dev_t *hw, timer_idx_t timer_num, uint64_t load_val) +{ + hw->hw_timer[timer_num].load_high.load_hi = (uint32_t) (load_val >> 32); + hw->hw_timer[timer_num].load_low = (uint32_t) load_val; + hw->hw_timer[timer_num].reload = 1; +} + +/** + * @brief Get counter value from time-base counter + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param timer_val Pointer to accept the counter value + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_get_counter_value(timg_dev_t *hw, timer_idx_t timer_num, uint64_t *timer_val) +{ + hw->hw_timer[timer_num].update.update = 1; + while (hw->hw_timer[timer_num].update.update) {} + *timer_val = ((uint64_t) hw->hw_timer[timer_num].cnt_high.hi << 32) | (hw->hw_timer[timer_num].cnt_low); +} + +/** + * @brief Set counter mode, include increment mode and decrement mode. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param increase_en True to increment mode, fasle to decrement mode + * + * @return None + */ +static inline void timer_ll_set_counter_increase(timg_dev_t *hw, timer_idx_t timer_num, bool increase_en) +{ + hw->hw_timer[timer_num].config.increase = increase_en; +} + +/** + * @brief Get counter mode, include increment mode and decrement mode. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Increment mode + * - false Decrement mode + */ +static inline bool timer_ll_get_counter_increase(timg_dev_t *hw, timer_idx_t timer_num) +{ + return hw->hw_timer[timer_num].config.increase; +} + +/** + * @brief Set counter status, enable or disable counter. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param counter_en True to enable counter, false to disable counter + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_set_counter_enable(timg_dev_t *hw, timer_idx_t timer_num, bool counter_en) +{ + hw->hw_timer[timer_num].config.enable = counter_en; +} + +/** + * @brief Get counter status. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Enable counter + * - false Disable conuter + */ +static inline bool timer_ll_get_counter_enable(timg_dev_t *hw, timer_idx_t timer_num) +{ + return hw->hw_timer[timer_num].config.enable; +} + +/** + * @brief Set auto reload mode. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param auto_reload_en True to enable auto reload mode, flase to disable auto reload mode + * + * @return None + */ +static inline void timer_ll_set_auto_reload(timg_dev_t *hw, timer_idx_t timer_num, bool auto_reload_en) +{ + hw->hw_timer[timer_num].config.autoreload = auto_reload_en; +} + +/** + * @brief Get auto reload mode. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Enable auto reload mode + * - false Disable auto reload mode + */ +FORCE_INLINE_ATTR bool timer_ll_get_auto_reload(timg_dev_t *hw, timer_idx_t timer_num) +{ + return hw->hw_timer[timer_num].config.autoreload; +} + +/** + * @brief Set the counter value to trigger the alarm. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param alarm_value Counter value to trigger the alarm + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_set_alarm_value(timg_dev_t *hw, timer_idx_t timer_num, uint64_t alarm_value) +{ + hw->hw_timer[timer_num].alarm_high.alarm_hi = (uint32_t) (alarm_value >> 32); + hw->hw_timer[timer_num].alarm_low = (uint32_t) alarm_value; +} + +/** + * @brief Get the counter value to trigger the alarm. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param alarm_value Pointer to accept the counter value to trigger the alarm + * + * @return None + */ +static inline void timer_ll_get_alarm_value(timg_dev_t *hw, timer_idx_t timer_num, uint64_t *alarm_value) +{ + *alarm_value = ((uint64_t) hw->hw_timer[timer_num].alarm_high.alarm_hi << 32) | (hw->hw_timer[timer_num].alarm_low); +} + +/** + * @brief Set the alarm status, enable or disable the alarm. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param alarm_en True to enable alarm, false to disable alarm + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_set_alarm_enable(timg_dev_t *hw, timer_idx_t timer_num, bool alarm_en) +{ + hw->hw_timer[timer_num].config.alarm_en = alarm_en; +} + +/** + * @brief Get the alarm status. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Enable alarm + * - false Disable alarm + */ +static inline bool timer_ll_get_alarm_enable(timg_dev_t *hw, timer_idx_t timer_num) +{ + return hw->hw_timer[timer_num].config.alarm_en; +} + +/** + * @brief Enable timer interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_intr_enable(timg_dev_t *hw, timer_idx_t timer_num) +{ + hw->int_ena.val |= BIT(timer_num); +} + +/** + * @brief Disable timer interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_intr_disable(timg_dev_t *hw, timer_idx_t timer_num) +{ + hw->int_ena.val &= (~BIT(timer_num)); +} + +/** + * @brief Disable timer interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_clear_intr_status(timg_dev_t *hw, timer_idx_t timer_num) +{ + hw->int_clr.val |= BIT(timer_num); +} + +/** + * @brief Get interrupt status. + * + * @param hw Beginning address of the peripheral registers. + * @param intr_status Interrupt status + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_get_intr_status(timg_dev_t *hw, uint32_t *intr_status) +{ + *intr_status = hw->int_st.val & 0x01; +} + +/** + * @brief Get interrupt raw status. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param intr_raw_status Interrupt raw status + * + * @return None + */ +FORCE_INLINE_ATTR void timer_ll_get_intr_raw_status(timer_group_t group_num, uint32_t *intr_raw_status) +{ + timg_dev_t *hw = TIMER_LL_GET_HW(group_num); + *intr_raw_status = hw->int_raw.val & 0x01; +} + +/** + * @brief Set the level interrupt status, enable or disable the level interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param level_int_en True to enable level interrupt, false to disable level interrupt + * + * @return None + */ +static inline void timer_ll_set_level_int_enable(timg_dev_t *hw, timer_idx_t timer_num, bool level_int_en) +{ + // Only "level" interrupts are supported on this target +} + +/** + * @brief Get the level interrupt status. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Enable level interrupt + * - false Disable level interrupt + */ +static inline bool timer_ll_get_level_int_enable(timg_dev_t *hw, timer_idx_t timer_num) +{ + // Only "level" interrupts are supported on this target + return true; +} + +/** + * @brief Set the edge interrupt status, enable or disable the edge interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * @param edge_int_en True to enable edge interrupt, false to disable edge interrupt + * + * @return None + */ +static inline void timer_ll_set_edge_int_enable(timg_dev_t *hw, timer_idx_t timer_num, bool edge_int_en) +{ + // edge interrupt is not supported on C3 +} + +/** + * @brief Get the edge interrupt status. + * + * @param hw Beginning address of the peripheral registers. + * @param timer_num The timer number + * + * @return + * - true Enable edge interrupt + * - false Disable edge interrupt + */ +static inline bool timer_ll_get_edge_int_enable(timg_dev_t *hw, timer_idx_t timer_num) +{ + // edge interrupt is not supported on C3 + return false; +} + +/** + * @brief Get interrupt status register address. + * + * @param hw Beginning address of the peripheral registers. + * + * @return uint32_t Interrupt status register address + */ +static inline uint32_t timer_ll_get_intr_status_reg(timg_dev_t *hw) +{ + return (uint32_t) & (hw->int_st.val); +} + +static inline uint32_t timer_ll_get_intr_mask_bit(timg_dev_t *hw, timer_idx_t timer_num) +{ + return (1U << timer_num); +} + +/** + * @brief Set clock source. + * + * @param hal Context of the HAL layer + * @param use_xtal_en True to use XTAL clock, flase to use APB clock + * + * @return None + */ +static inline void timer_ll_set_use_xtal(timg_dev_t *hw, timer_idx_t timer_num, bool use_xtal_en) +{ + hw->hw_timer[timer_num].config.use_xtal = use_xtal_en; +} + +/** + * @brief Get clock source. + * + * @param hal Context of the HAL layer + * + * @return + * - true Use XTAL clock + * - false Use APB clock + */ +static inline bool timer_ll_get_use_xtal(timg_dev_t *hw, timer_idx_t timer_num) +{ + return hw->hw_timer[timer_num].config.use_xtal; +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/twai_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/twai_ll.h new file mode 100644 index 00000000..6c9ae1b9 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/twai_ll.h @@ -0,0 +1,667 @@ +// Copyright 2021 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. + +/******************************************************************************* + * NOTICE + * The ll is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The Lowlevel layer for TWAI + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "hal/twai_types.h" +#include "soc/twai_periph.h" + +/* ------------------------- Defines and Typedefs --------------------------- */ + +#define TWAI_LL_STATUS_RBS (0x1 << 0) //Receive Buffer Status +#define TWAI_LL_STATUS_DOS (0x1 << 1) //Data Overrun Status +#define TWAI_LL_STATUS_TBS (0x1 << 2) //Transmit Buffer Status +#define TWAI_LL_STATUS_TCS (0x1 << 3) //Transmission Complete Status +#define TWAI_LL_STATUS_RS (0x1 << 4) //Receive Status +#define TWAI_LL_STATUS_TS (0x1 << 5) //Transmit Status +#define TWAI_LL_STATUS_ES (0x1 << 6) //Error Status +#define TWAI_LL_STATUS_BS (0x1 << 7) //Bus Status +#define TWAI_LL_STATUS_MS (0x1 << 8) //Miss Status + +#define TWAI_LL_INTR_RI (0x1 << 0) //Receive Interrupt +#define TWAI_LL_INTR_TI (0x1 << 1) //Transmit Interrupt +#define TWAI_LL_INTR_EI (0x1 << 2) //Error Interrupt +//Data overrun interrupt not supported in SW due to HW peculiarities +#define TWAI_LL_INTR_EPI (0x1 << 5) //Error Passive Interrupt +#define TWAI_LL_INTR_ALI (0x1 << 6) //Arbitration Lost Interrupt +#define TWAI_LL_INTR_BEI (0x1 << 7) //Bus Error Interrupt + +/* + * The following frame structure has an NEARLY identical bit field layout to + * each byte of the TX buffer. This allows for formatting and parsing frames to + * be done outside of time critical regions (i.e., ISRs). All the ISR needs to + * do is to copy byte by byte to/from the TX/RX buffer. The two reserved bits in + * TX buffer are used in the frame structure to store the self_reception and + * single_shot flags which in turn indicate the type of transmission to execute. + */ +typedef union { + struct { + struct { + uint8_t dlc: 4; //Data length code (0 to 8) of the frame + uint8_t self_reception: 1; //This frame should be transmitted using self reception command + uint8_t single_shot: 1; //This frame should be transmitted using single shot command + uint8_t rtr: 1; //This frame is a remote transmission request + uint8_t frame_format: 1; //Format of the frame (1 = extended, 0 = standard) + }; + union { + struct { + uint8_t id[2]; //11 bit standard frame identifier + uint8_t data[8]; //Data bytes (0 to 8) + uint8_t reserved8[2]; + } standard; + struct { + uint8_t id[4]; //29 bit extended frame identifier + uint8_t data[8]; //Data bytes (0 to 8) + } extended; + }; + }; + uint8_t bytes[13]; +} __attribute__((packed)) twai_ll_frame_buffer_t; + +_Static_assert(sizeof(twai_ll_frame_buffer_t) == 13, "TX/RX buffer type should be 13 bytes"); + +/* ---------------------------- Mode Register ------------------------------- */ + +/** + * @brief Enter reset mode + * + * When in reset mode, the TWAI controller is effectively disconnected from the + * TWAI bus and will not participate in any bus activates. Reset mode is required + * in order to write the majority of configuration registers. + * + * @param hw Start address of the TWAI registers + * + * @note Reset mode is automatically entered on BUS OFF condition + */ +static inline void twai_ll_enter_reset_mode(twai_dev_t *hw) +{ + hw->mode_reg.rm = 1; +} + +/** + * @brief Exit reset mode + * + * When not in reset mode, the TWAI controller will take part in bus activities + * (e.g., send/receive/acknowledge messages and error frames) depending on the + * operating mode. + * + * @param hw Start address of the TWAI registers + * + * @note Reset mode must be exit to initiate BUS OFF recovery + */ +static inline void twai_ll_exit_reset_mode(twai_dev_t *hw) +{ + hw->mode_reg.rm = 0; +} + +/** + * @brief Check if in reset mode + * @param hw Start address of the TWAI registers + * @return true if in reset mode + */ +static inline bool twai_ll_is_in_reset_mode(twai_dev_t *hw) +{ + return hw->mode_reg.rm; +} + +/** + * @brief Set operating mode of TWAI controller + * + * @param hw Start address of the TWAI registers + * @param mode Operating mode + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_mode(twai_dev_t *hw, twai_mode_t mode) +{ + if (mode == TWAI_MODE_NORMAL) { //Normal Operating mode + hw->mode_reg.lom = 0; + hw->mode_reg.stm = 0; + } else if (mode == TWAI_MODE_NO_ACK) { //Self Test Mode (No Ack) + hw->mode_reg.lom = 0; + hw->mode_reg.stm = 1; + } else if (mode == TWAI_MODE_LISTEN_ONLY) { //Listen Only Mode + hw->mode_reg.lom = 1; + hw->mode_reg.stm = 0; + } +} + +/* --------------------------- Command Register ----------------------------- */ + +/** + * @brief Set TX command + * + * Setting the TX command will cause the TWAI controller to attempt to transmit + * the frame stored in the TX buffer. The TX buffer will be occupied (i.e., + * locked) until TX completes. + * + * @param hw Start address of the TWAI registers + * + * @note Transmit commands should be called last (i.e., after handling buffer + * release and clear data overrun) in order to prevent the other commands + * overwriting this latched TX bit with 0. + */ +static inline void twai_ll_set_cmd_tx(twai_dev_t *hw) +{ + hw->command_reg.tr = 1; +} + +/** + * @brief Set single shot TX command + * + * Similar to setting TX command, but the TWAI controller will not automatically + * retry transmission upon an error (e.g., due to an acknowledgement error). + * + * @param hw Start address of the TWAI registers + * + * @note Transmit commands should be called last (i.e., after handling buffer + * release and clear data overrun) in order to prevent the other commands + * overwriting this latched TX bit with 0. + */ +static inline void twai_ll_set_cmd_tx_single_shot(twai_dev_t *hw) +{ + hw->command_reg.val = 0x03; //Set command_reg.tr and command_reg.at simultaneously for single shot transmittion request +} + +/** + * @brief Aborts TX + * + * Frames awaiting TX will be aborted. Frames already being TX are not aborted. + * Transmission Complete Status bit is automatically set to 1. + * Similar to setting TX command, but the TWAI controller will not automatically + * retry transmission upon an error (e.g., due to acknowledge error). + * + * @param hw Start address of the TWAI registers + * + * @note Transmit commands should be called last (i.e., after handling buffer + * release and clear data overrun) in order to prevent the other commands + * overwriting this latched TX bit with 0. + */ +static inline void twai_ll_set_cmd_abort_tx(twai_dev_t *hw) +{ + hw->command_reg.at = 1; +} + +/** + * @brief Release RX buffer + * + * Rotates RX buffer to the next frame in the RX FIFO. + * + * @param hw Start address of the TWAI registers + */ +static inline void twai_ll_set_cmd_release_rx_buffer(twai_dev_t *hw) +{ + hw->command_reg.rrb = 1; +} + +/** + * @brief Clear data overrun + * + * Clears the data overrun status bit + * + * @param hw Start address of the TWAI registers + */ +static inline void twai_ll_set_cmd_clear_data_overrun(twai_dev_t *hw) +{ + hw->command_reg.cdo = 1; +} + +/** + * @brief Set self reception single shot command + * + * Similar to setting TX command, but the TWAI controller also simultaneously + * receive the transmitted frame and is generally used for self testing + * purposes. The TWAI controller will not ACK the received message, so consider + * using the NO_ACK operating mode. + * + * @param hw Start address of the TWAI registers + * + * @note Transmit commands should be called last (i.e., after handling buffer + * release and clear data overrun) in order to prevent the other commands + * overwriting this latched TX bit with 0. + */ +static inline void twai_ll_set_cmd_self_rx_request(twai_dev_t *hw) +{ + hw->command_reg.srr = 1; +} + +/** + * @brief Set self reception request command + * + * Similar to setting the self reception request, but the TWAI controller will + * not automatically retry transmission upon an error (e.g., due to and + * acknowledgement error). + * + * @param hw Start address of the TWAI registers + * + * @note Transmit commands should be called last (i.e., after handling buffer + * release and clear data overrun) in order to prevent the other commands + * overwriting this latched TX bit with 0. + */ +static inline void twai_ll_set_cmd_self_rx_single_shot(twai_dev_t *hw) +{ + hw->command_reg.val = 0x12; //Set command_reg.srr and command_reg.at simultaneously for single shot self reception request +} + +/* --------------------------- Status Register ------------------------------ */ + +/** + * @brief Get all status bits + * + * @param hw Start address of the TWAI registers + * @return Status bits + */ +static inline uint32_t twai_ll_get_status(twai_dev_t *hw) +{ + return hw->status_reg.val; +} + +/** + * @brief Check if RX FIFO overrun status bit is set + * + * @param hw Start address of the TWAI registers + * @return Overrun status bit + */ +static inline bool twai_ll_is_fifo_overrun(twai_dev_t *hw) +{ + return hw->status_reg.dos; +} + +/** + * @brief Check if previously TX was successful + * + * @param hw Start address of the TWAI registers + * @return Whether previous TX was successful + */ +static inline bool twai_ll_is_last_tx_successful(twai_dev_t *hw) +{ + return hw->status_reg.tcs; +} + +/* -------------------------- Interrupt Register ---------------------------- */ + +/** + * @brief Get currently set interrupts + * + * Reading the interrupt registers will automatically clear all interrupts + * except for the Receive Interrupt. + * + * @param hw Start address of the TWAI registers + * @return Bit mask of set interrupts + */ +static inline uint32_t twai_ll_get_and_clear_intrs(twai_dev_t *hw) +{ + return hw->interrupt_reg.val; +} + +/* ----------------------- Interrupt Enable Register ------------------------ */ + +/** + * @brief Set which interrupts are enabled + * + * @param hw Start address of the TWAI registers + * @param Bit mask of interrupts to enable + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_enabled_intrs(twai_dev_t *hw, uint32_t intr_mask) +{ + hw->interrupt_enable_reg.val = intr_mask; +} + +/* ------------------------ Bus Timing Registers --------------------------- */ + +/** + * @brief Set bus timing + * + * @param hw Start address of the TWAI registers + * @param brp Baud Rate Prescaler + * @param sjw Synchronization Jump Width + * @param tseg1 Timing Segment 1 + * @param tseg2 Timing Segment 2 + * @param triple_sampling Triple Sampling enable/disable + * + * @note Must be called in reset mode + * @note ESP32C3 brp can be any even number between 2 to 32768 + */ +static inline void twai_ll_set_bus_timing(twai_dev_t *hw, uint32_t brp, uint32_t sjw, uint32_t tseg1, uint32_t tseg2, bool triple_sampling) +{ + hw->bus_timing_0_reg.brp = (brp / 2) - 1; + hw->bus_timing_0_reg.sjw = sjw - 1; + hw->bus_timing_1_reg.tseg1 = tseg1 - 1; + hw->bus_timing_1_reg.tseg2 = tseg2 - 1; + hw->bus_timing_1_reg.sam = triple_sampling; +} + +/* ----------------------------- ALC Register ------------------------------- */ + +/** + * @brief Clear Arbitration Lost Capture Register + * + * Reading the ALC register rearms the Arbitration Lost Interrupt + * + * @param hw Start address of the TWAI registers + */ +static inline void twai_ll_clear_arb_lost_cap(twai_dev_t *hw) +{ + (void)hw->arbitration_lost_captue_reg.val; +} + +/* ----------------------------- ECC Register ------------------------------- */ + +/** + * @brief Clear Error Code Capture register + * + * Reading the ECC register rearms the Bus Error Interrupt + * + * @param hw Start address of the TWAI registers + */ +static inline void twai_ll_clear_err_code_cap(twai_dev_t *hw) +{ + (void)hw->error_code_capture_reg.val; +} + +/* ----------------------------- EWL Register ------------------------------- */ + +/** + * @brief Set Error Warning Limit + * + * @param hw Start address of the TWAI registers + * @param ewl Error Warning Limit + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_err_warn_lim(twai_dev_t *hw, uint32_t ewl) +{ + hw->error_warning_limit_reg.ewl = ewl; +} + +/** + * @brief Get Error Warning Limit + * + * @param hw Start address of the TWAI registers + * @return Error Warning Limit + */ +static inline uint32_t twai_ll_get_err_warn_lim(twai_dev_t *hw) +{ + return hw->error_warning_limit_reg.val; +} + +/* ------------------------ RX Error Count Register ------------------------- */ + +/** + * @brief Get RX Error Counter + * + * @param hw Start address of the TWAI registers + * @return REC value + * + * @note REC is not frozen in reset mode. Listen only mode will freeze it. A BUS + * OFF condition automatically sets the REC to 0. + */ +static inline uint32_t twai_ll_get_rec(twai_dev_t *hw) +{ + return hw->rx_error_counter_reg.val; +} + +/** + * @brief Set RX Error Counter + * + * @param hw Start address of the TWAI registers + * @param rec REC value + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_rec(twai_dev_t *hw, uint32_t rec) +{ + hw->rx_error_counter_reg.rxerr = rec; +} + +/* ------------------------ TX Error Count Register ------------------------- */ + +/** + * @brief Get TX Error Counter + * + * @param hw Start address of the TWAI registers + * @return TEC value + * + * @note A BUS OFF condition will automatically set this to 128 + */ +static inline uint32_t twai_ll_get_tec(twai_dev_t *hw) +{ + return hw->tx_error_counter_reg.val; +} + +/** + * @brief Set TX Error Counter + * + * @param hw Start address of the TWAI registers + * @param tec TEC value + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_tec(twai_dev_t *hw, uint32_t tec) +{ + hw->tx_error_counter_reg.txerr = tec; +} + +/* ---------------------- Acceptance Filter Registers ----------------------- */ + +/** + * @brief Set Acceptance Filter + * @param hw Start address of the TWAI registers + * @param code Acceptance Code + * @param mask Acceptance Mask + * @param single_filter Whether to enable single filter mode + * + * @note Must be called in reset mode + */ +static inline void twai_ll_set_acc_filter(twai_dev_t* hw, uint32_t code, uint32_t mask, bool single_filter) +{ + uint32_t code_swapped = __builtin_bswap32(code); + uint32_t mask_swapped = __builtin_bswap32(mask); + for (int i = 0; i < 4; i++) { + hw->acceptance_filter.acr[i].byte = ((code_swapped >> (i * 8)) & 0xFF); + hw->acceptance_filter.amr[i].byte = ((mask_swapped >> (i * 8)) & 0xFF); + } + hw->mode_reg.afm = single_filter; +} + +/* ------------------------- TX/RX Buffer Registers ------------------------- */ + +/** + * @brief Copy a formatted TWAI frame into TX buffer for transmission + * + * @param hw Start address of the TWAI registers + * @param tx_frame Pointer to formatted frame + * + * @note Call twai_ll_format_frame_buffer() to format a frame + */ +static inline void twai_ll_set_tx_buffer(twai_dev_t *hw, twai_ll_frame_buffer_t *tx_frame) +{ + //Copy formatted frame into TX buffer + for (int i = 0; i < 13; i++) { + hw->tx_rx_buffer[i].val = tx_frame->bytes[i]; + } +} + +/** + * @brief Copy a received frame from the RX buffer for parsing + * + * @param hw Start address of the TWAI registers + * @param rx_frame Pointer to store formatted frame + * + * @note Call twai_ll_prase_frame_buffer() to parse the formatted frame + */ +static inline void twai_ll_get_rx_buffer(twai_dev_t *hw, twai_ll_frame_buffer_t *rx_frame) +{ + //Copy RX buffer registers into frame + for (int i = 0; i < 13; i++) { + rx_frame->bytes[i] = hw->tx_rx_buffer[i].byte; + } +} + +/** + * @brief Format contents of a TWAI frame into layout of TX Buffer + * + * This function encodes a message into a frame structure. The frame structure + * has an identical layout to the TX buffer, allowing the frame structure to be + * directly copied into TX buffer. + * + * @param[in] 11bit or 29bit ID + * @param[in] dlc Data length code + * @param[in] data Pointer to an 8 byte array containing data. NULL if no data + * @param[in] format Type of TWAI frame + * @param[in] single_shot Frame will not be retransmitted on failure + * @param[in] self_rx Frame will also be simultaneously received + * @param[out] tx_frame Pointer to store formatted frame + */ +static inline void twai_ll_format_frame_buffer(uint32_t id, uint8_t dlc, const uint8_t *data, + uint32_t flags, twai_ll_frame_buffer_t *tx_frame) +{ + bool is_extd = flags & TWAI_MSG_FLAG_EXTD; + bool is_rtr = flags & TWAI_MSG_FLAG_RTR; + + //Set frame information + tx_frame->dlc = dlc; + tx_frame->frame_format = is_extd; + tx_frame->rtr = is_rtr; + tx_frame->self_reception = (flags & TWAI_MSG_FLAG_SELF) ? 1 : 0; + tx_frame->single_shot = (flags & TWAI_MSG_FLAG_SS) ? 1 : 0; + + //Set ID. The ID registers are big endian and left aligned, therefore a bswap will be required + if (is_extd) { + uint32_t id_temp = __builtin_bswap32((id & TWAI_EXTD_ID_MASK) << 3); //((id << 3) >> 8*(3-i)) + for (int i = 0; i < 4; i++) { + tx_frame->extended.id[i] = (id_temp >> (8 * i)) & 0xFF; + } + } else { + uint32_t id_temp = __builtin_bswap16((id & TWAI_STD_ID_MASK) << 5); //((id << 5) >> 8*(1-i)) + for (int i = 0; i < 2; i++) { + tx_frame->standard.id[i] = (id_temp >> (8 * i)) & 0xFF; + } + } + + uint8_t *data_buffer = (is_extd) ? tx_frame->extended.data : tx_frame->standard.data; + if (!is_rtr) { //Only copy data if the frame is a data frame (i.e not a remote frame) + for (int i = 0; (i < dlc) && (i < TWAI_FRAME_MAX_DLC); i++) { + data_buffer[i] = data[i]; + } + } +} + +/** + * @brief Parse formatted TWAI frame (RX Buffer Layout) into its constituent contents + * + * @param[in] rx_frame Pointer to formatted frame + * @param[out] id 11 or 29bit ID + * @param[out] dlc Data length code + * @param[out] data Data. Left over bytes set to 0. + * @param[out] format Type of TWAI frame + */ +static inline void twai_ll_prase_frame_buffer(twai_ll_frame_buffer_t *rx_frame, uint32_t *id, uint8_t *dlc, + uint8_t *data, uint32_t *flags) +{ + //Copy frame information + *dlc = rx_frame->dlc; + uint32_t flags_temp = 0; + flags_temp |= (rx_frame->frame_format) ? TWAI_MSG_FLAG_EXTD : 0; + flags_temp |= (rx_frame->rtr) ? TWAI_MSG_FLAG_RTR : 0; + flags_temp |= (rx_frame->dlc > TWAI_FRAME_MAX_DLC) ? TWAI_MSG_FLAG_DLC_NON_COMP : 0; + *flags = flags_temp; + + //Copy ID. The ID registers are big endian and left aligned, therefore a bswap will be required + if (rx_frame->frame_format) { + uint32_t id_temp = 0; + for (int i = 0; i < 4; i++) { + id_temp |= rx_frame->extended.id[i] << (8 * i); + } + id_temp = __builtin_bswap32(id_temp) >> 3; //((byte[i] << 8*(3-i)) >> 3) + *id = id_temp & TWAI_EXTD_ID_MASK; + } else { + uint32_t id_temp = 0; + for (int i = 0; i < 2; i++) { + id_temp |= rx_frame->standard.id[i] << (8 * i); + } + id_temp = __builtin_bswap16(id_temp) >> 5; //((byte[i] << 8*(1-i)) >> 5) + *id = id_temp & TWAI_STD_ID_MASK; + } + + uint8_t *data_buffer = (rx_frame->frame_format) ? rx_frame->extended.data : rx_frame->standard.data; + //Only copy data if the frame is a data frame (i.e. not a remote frame) + int data_length = (rx_frame->rtr) ? 0 : ((rx_frame->dlc > TWAI_FRAME_MAX_DLC) ? TWAI_FRAME_MAX_DLC : rx_frame->dlc); + for (int i = 0; i < data_length; i++) { + data[i] = data_buffer[i]; + } + //Set remaining bytes of data to 0 + for (int i = data_length; i < TWAI_FRAME_MAX_DLC; i++) { + data[i] = 0; + } +} + +/* ----------------------- RX Message Count Register ------------------------ */ + +/** + * @brief Get RX Message Counter + * + * @param hw Start address of the TWAI registers + * @return RX Message Counter + */ +static inline uint32_t twai_ll_get_rx_msg_count(twai_dev_t *hw) +{ + return hw->rx_message_counter_reg.val; +} + +/* ------------------------- Clock Divider Register ------------------------- */ + +/** + * @brief Set CLKOUT Divider and enable/disable + * + * Configure CLKOUT. CLKOUT is a pre-scaled version of APB CLK. Divider can be + * 1, or any even number from 2 to 490. Set the divider to 0 to disable CLKOUT. + * + * @param hw Start address of the TWAI registers + * @param divider Divider for CLKOUT (any even number from 2 to 490). Set to 0 to disable CLKOUT + */ +static inline void twai_ll_set_clkout(twai_dev_t *hw, uint32_t divider) +{ + if (divider >= 2 && divider <= 490) { + hw->clock_divider_reg.co = 0; + hw->clock_divider_reg.cd = (divider / 2) - 1; + } else if (divider == 1) { + //Setting the divider reg to max value (255) means a divider of 1 + hw->clock_divider_reg.co = 0; + hw->clock_divider_reg.cd = 255; + } else { + hw->clock_divider_reg.co = 1; + hw->clock_divider_reg.cd = 0; + } +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uart_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uart_ll.h new file mode 100644 index 00000000..931134f7 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uart_ll.h @@ -0,0 +1,934 @@ +// Copyright 2020 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. + +// The LL layer for UART register operations. +// Note that most of the register operations in this layer are non-atomic operations. + + +#pragma once +#include "hal/uart_types.h" +#include "soc/uart_periph.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// The default fifo depth +#define UART_LL_FIFO_DEF_LEN (SOC_UART_FIFO_LEN) +// Get UART hardware instance with giving uart num +#define UART_LL_GET_HW(num) (((num) == 0) ? (&UART0) : (&UART1)) + +#define UART_LL_MIN_WAKEUP_THRESH (2) +#define UART_LL_INTR_MASK (0x7ffff) //All interrupt mask + +// Define UART interrupts +typedef enum { + UART_INTR_RXFIFO_FULL = (0x1 << 0), + UART_INTR_TXFIFO_EMPTY = (0x1 << 1), + UART_INTR_PARITY_ERR = (0x1 << 2), + UART_INTR_FRAM_ERR = (0x1 << 3), + UART_INTR_RXFIFO_OVF = (0x1 << 4), + UART_INTR_DSR_CHG = (0x1 << 5), + UART_INTR_CTS_CHG = (0x1 << 6), + UART_INTR_BRK_DET = (0x1 << 7), + UART_INTR_RXFIFO_TOUT = (0x1 << 8), + UART_INTR_SW_XON = (0x1 << 9), + UART_INTR_SW_XOFF = (0x1 << 10), + UART_INTR_GLITCH_DET = (0x1 << 11), + UART_INTR_TX_BRK_DONE = (0x1 << 12), + UART_INTR_TX_BRK_IDLE = (0x1 << 13), + UART_INTR_TX_DONE = (0x1 << 14), + UART_INTR_RS485_PARITY_ERR = (0x1 << 15), + UART_INTR_RS485_FRM_ERR = (0x1 << 16), + UART_INTR_RS485_CLASH = (0x1 << 17), + UART_INTR_CMD_CHAR_DET = (0x1 << 18), +} uart_intr_t; + +static inline void uart_ll_reset_core(uart_dev_t *hw) { + hw->clk_conf.rst_core = 1; + hw->clk_conf.rst_core = 0; +} + +static inline void uart_ll_sclk_enable(uart_dev_t *hw) { + hw->clk_conf.sclk_en = 1; + hw->clk_conf.rx_sclk_en = 1; + hw->clk_conf.tx_sclk_en = 1; +} + +static inline void uart_ll_sclk_disable(uart_dev_t *hw) { + hw->clk_conf.sclk_en = 0; + hw->clk_conf.rx_sclk_en = 0; + hw->clk_conf.tx_sclk_en = 0; +} + +/** + * @brief Set the UART source clock. + * + * @param hw Beginning address of the peripheral registers. + * @param source_clk The UART source clock. The source clock can be APB clock, RTC clock or XTAL clock. + * If the source clock is RTC/XTAL, the UART can still work when the APB changes. + * + * @return None. + */ +static inline void uart_ll_set_sclk(uart_dev_t *hw, uart_sclk_t source_clk) +{ + switch (source_clk) { + default: + case UART_SCLK_APB: + hw->clk_conf.sclk_sel = 1; + break; + case UART_SCLK_RTC: + hw->clk_conf.sclk_sel = 2; + break; + case UART_SCLK_XTAL: + hw->clk_conf.sclk_sel = 3; + break; + } +} + +/** + * @brief Get the UART source clock type. + * + * @param hw Beginning address of the peripheral registers. + * @param source_clk The pointer to accept the UART source clock type. + * + * @return None. + */ +static inline void uart_ll_get_sclk(uart_dev_t *hw, uart_sclk_t *source_clk) +{ + switch (hw->clk_conf.sclk_sel) { + default: + case 1: + *source_clk = UART_SCLK_APB; + break; + case 2: + *source_clk = UART_SCLK_RTC; + break; + case 3: + *source_clk = UART_SCLK_XTAL; + break; + } +} + +/** + * @brief Get the UART source clock frequency. + * + * @param hw Beginning address of the peripheral registers. + * + * @return Current source clock frequency + */ +static inline uint32_t uart_ll_get_sclk_freq(uart_dev_t *hw) +{ + switch (hw->clk_conf.sclk_sel) { + default: + case 1: + return APB_CLK_FREQ; + case 2: + return RTC_CLK_FREQ; + case 3: + return XTAL_CLK_FREQ; + } +} + +/** + * @brief Configure the baud-rate. + * + * @param hw Beginning address of the peripheral registers. + * @param baud The baud rate to be set. + * + * @return None + */ +static inline void uart_ll_set_baudrate(uart_dev_t *hw, uint32_t baud) +{ +#define DIV_UP(a, b) (((a) + (b) - 1) / (b)) + uint32_t sclk_freq = uart_ll_get_sclk_freq(hw); + const uint32_t max_div = BIT(12) - 1; // UART divider integer part only has 12 bits + int sclk_div = DIV_UP(sclk_freq, max_div * baud); + + uint32_t clk_div = ((sclk_freq) << 4) / (baud * sclk_div); + // The baud rate configuration register is divided into + // an integer part and a fractional part. + hw->clk_div.div_int = clk_div >> 4; + hw->clk_div.div_frag = clk_div & 0xf; + hw->clk_conf.sclk_div_num = sclk_div - 1; +#undef DIV_UP +} + +/** + * @brief Get the current baud-rate. + * + * @param hw Beginning address of the peripheral registers. + * + * @return The current baudrate + */ +static inline uint32_t uart_ll_get_baudrate(uart_dev_t *hw) +{ + uint32_t sclk_freq = uart_ll_get_sclk_freq(hw); + typeof(hw->clk_div) div_reg = hw->clk_div; + return ((sclk_freq << 4)) / (((div_reg.div_int << 4) | div_reg.div_frag) * (hw->clk_conf.sclk_div_num + 1)); +} + +/** + * @brief Enable the UART interrupt based on the given mask. + * + * @param hw Beginning address of the peripheral registers. + * @param mask The bitmap of the interrupts need to be enabled. + * + * @return None + */ +static inline void uart_ll_ena_intr_mask(uart_dev_t *hw, uint32_t mask) +{ + hw->int_ena.val |= mask; +} + +/** + * @brief Disable the UART interrupt based on the given mask. + * + * @param hw Beginning address of the peripheral registers. + * @param mask The bitmap of the interrupts need to be disabled. + * + * @return None + */ +static inline void uart_ll_disable_intr_mask(uart_dev_t *hw, uint32_t mask) +{ + hw->int_ena.val &= (~mask); +} + +/** + * @brief Get the UART interrupt status. + * + * @param hw Beginning address of the peripheral registers. + * + * @return The UART interrupt status. + */ +static inline uint32_t uart_ll_get_intsts_mask(uart_dev_t *hw) +{ + return hw->int_st.val; +} + +/** + * @brief Clear the UART interrupt status based on the given mask. + * + * @param hw Beginning address of the peripheral registers. + * @param mask The bitmap of the interrupts need to be cleared. + * + * @return None + */ +static inline void uart_ll_clr_intsts_mask(uart_dev_t *hw, uint32_t mask) +{ + hw->int_clr.val = mask; +} + +/** + * @brief Get status of enabled interrupt. + * + * @param hw Beginning address of the peripheral registers. + * + * @return interrupt enable value + */ +static inline uint32_t uart_ll_get_intr_ena_status(uart_dev_t *hw) +{ + return hw->int_ena.val; +} + +/** + * @brief Read the UART rxfifo. + * + * @param hw Beginning address of the peripheral registers. + * @param buf The data buffer. The buffer size should be large than 128 byts. + * @param rd_len The data length needs to be read. + * + * @return None. + */ +static inline void uart_ll_read_rxfifo(uart_dev_t *hw, uint8_t *buf, uint32_t rd_len) +{ + for (int i = 0; i < (int)rd_len; i++) { + buf[i] = hw->ahb_fifo.rw_byte; + } +} + +/** + * @brief Write byte to the UART txfifo. + * + * @param hw Beginning address of the peripheral registers. + * @param buf The data buffer. + * @param wr_len The data length needs to be writen. + * + * @return None + */ +static inline void uart_ll_write_txfifo(uart_dev_t *hw, const uint8_t *buf, uint32_t wr_len) +{ + for (int i = 0; i < (int)wr_len; i++) { + hw->ahb_fifo.rw_byte = buf[i]; + } +} + +/** + * @brief Reset the UART hw rxfifo. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None + */ +static inline void uart_ll_rxfifo_rst(uart_dev_t *hw) +{ + hw->conf0.rxfifo_rst = 1; + hw->conf0.rxfifo_rst = 0; +} + +/** + * @brief Reset the UART hw txfifo. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None + */ +static inline void uart_ll_txfifo_rst(uart_dev_t *hw) +{ + hw->conf0.txfifo_rst = 1; + hw->conf0.txfifo_rst = 0; +} + +/** + * @brief Get the length of readable data in UART rxfifo. + * + * @param hw Beginning address of the peripheral registers. + * + * @return The readable data length in rxfifo. + */ +static inline uint32_t uart_ll_get_rxfifo_len(uart_dev_t *hw) +{ + return hw->status.rxfifo_cnt; +} + +/** + * @brief Get the writable data length of UART txfifo. + * + * @param hw Beginning address of the peripheral registers. + * + * @return The data length of txfifo can be written. + */ +static inline uint32_t uart_ll_get_txfifo_len(uart_dev_t *hw) +{ + return UART_LL_FIFO_DEF_LEN - hw->status.txfifo_cnt; +} + +/** + * @brief Configure the UART stop bit. + * + * @param hw Beginning address of the peripheral registers. + * @param stop_bit The stop bit number to be set. + * + * @return None. + */ +static inline void uart_ll_set_stop_bits(uart_dev_t *hw, uart_stop_bits_t stop_bit) +{ + hw->conf0.stop_bit_num = stop_bit; +} + +/** + * @brief Get the configuration of the UART stop bit. + * + * @param hw Beginning address of the peripheral registers. + * @param stop_bit The pointer to accept the stop bit configuration + * + * @return None. + */ +static inline void uart_ll_get_stop_bits(uart_dev_t *hw, uart_stop_bits_t *stop_bit) +{ + *stop_bit = hw->conf0.stop_bit_num; +} + +/** + * @brief Configure the UART parity check mode. + * + * @param hw Beginning address of the peripheral registers. + * @param parity_mode The parity check mode to be set. + * + * @return None. + */ +static inline void uart_ll_set_parity(uart_dev_t *hw, uart_parity_t parity_mode) +{ + if (parity_mode != UART_PARITY_DISABLE) { + hw->conf0.parity = parity_mode & 0x1; + } + hw->conf0.parity_en = (parity_mode >> 1) & 0x1; +} + +/** + * @brief Get the UART parity check mode configuration. + * + * @param hw Beginning address of the peripheral registers. + * @param parity_mode The pointer to accept the parity check mode configuration. + * + * @return None. + */ +static inline void uart_ll_get_parity(uart_dev_t *hw, uart_parity_t *parity_mode) +{ + if (hw->conf0.parity_en) { + *parity_mode = 0X2 | hw->conf0.parity; + } else { + *parity_mode = UART_PARITY_DISABLE; + } +} + +/** + * @brief Set the UART rxfifo full threshold value. When the data in rxfifo is more than the threshold value, + * it will produce rxfifo_full_int_raw interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param full_thrhd The full threshold value of the rxfifo. `full_thrhd` should be less than `UART_LL_FIFO_DEF_LEN`. + * + * @return None. + */ +static inline void uart_ll_set_rxfifo_full_thr(uart_dev_t *hw, uint16_t full_thrhd) +{ + hw->conf1.rxfifo_full_thrhd = full_thrhd; +} + +/** + * @brief Set the txfifo empty threshold. when the data length in txfifo is less than threshold value, + * it will produce txfifo_empty_int_raw interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param empty_thrhd The empty threshold of txfifo. + * + * @return None. + */ +static inline void uart_ll_set_txfifo_empty_thr(uart_dev_t *hw, uint16_t empty_thrhd) +{ + hw->conf1.txfifo_empty_thrhd = empty_thrhd; +} + +/** + * @brief Set the UART rx-idle threshold value. when receiver takes more time than rx_idle_thrhd to receive a byte data, + * it will produce frame end signal for uhci to stop receiving data. + * + * @param hw Beginning address of the peripheral registers. + * @param rx_idle_thr The rx-idle threshold to be set. + * + * @return None. + */ +static inline void uart_ll_set_rx_idle_thr(uart_dev_t *hw, uint32_t rx_idle_thr) +{ + hw->idle_conf.rx_idle_thrhd = rx_idle_thr; +} + +/** + * @brief Configure the duration time between transfers. + * + * @param hw Beginning address of the peripheral registers. + * @param idle_num the duration time between transfers. + * + * @return None. + */ +static inline void uart_ll_set_tx_idle_num(uart_dev_t *hw, uint32_t idle_num) +{ + hw->idle_conf.tx_idle_num = idle_num; +} + +/** + * @brief Configure the transmiter to send break chars. + * + * @param hw Beginning address of the peripheral registers. + * @param break_num The number of the break chars need to be send. + * + * @return None. + */ +static inline void uart_ll_tx_break(uart_dev_t *hw, uint32_t break_num) +{ + if (break_num > 0) { + hw->txbrk_conf.tx_brk_num = break_num; + hw->conf0.txd_brk = 1; + } else { + hw->conf0.txd_brk = 0; + } +} + +/** + * @brief Configure the UART hardware flow control. + * + * @param hw Beginning address of the peripheral registers. + * @param flow_ctrl The hw flow control configuration. + * @param rx_thrs The rx flow control signal will be active if the data length in rxfifo is more than this value. + * + * @return None. + */ +static inline void uart_ll_set_hw_flow_ctrl(uart_dev_t *hw, uart_hw_flowcontrol_t flow_ctrl, uint32_t rx_thrs) +{ + //only when UART_HW_FLOWCTRL_RTS is set , will the rx_thresh value be set. + if (flow_ctrl & UART_HW_FLOWCTRL_RTS) { + hw->mem_conf.rx_flow_thrhd = rx_thrs; + hw->conf1.rx_flow_en = 1; + } else { + hw->conf1.rx_flow_en = 0; + } + if (flow_ctrl & UART_HW_FLOWCTRL_CTS) { + hw->conf0.tx_flow_en = 1; + } else { + hw->conf0.tx_flow_en = 0; + } +} + +/** + * @brief Configure the hardware flow control. + * + * @param hw Beginning address of the peripheral registers. + * @param flow_ctrl A pointer to accept the hw flow control configuration. + * + * @return None. + */ +static inline void uart_ll_get_hw_flow_ctrl(uart_dev_t *hw, uart_hw_flowcontrol_t *flow_ctrl) +{ + *flow_ctrl = UART_HW_FLOWCTRL_DISABLE; + if (hw->conf1.rx_flow_en) { + *flow_ctrl |= UART_HW_FLOWCTRL_RTS; + } + if (hw->conf0.tx_flow_en) { + *flow_ctrl |= UART_HW_FLOWCTRL_CTS; + } +} + +/** + * @brief Configure the software flow control. + * + * @param hw Beginning address of the peripheral registers. + * @param flow_ctrl The UART sofware flow control settings. + * @param sw_flow_ctrl_en Set true to enable software flow control, otherwise set it false. + * + * @return None. + */ +static inline void uart_ll_set_sw_flow_ctrl(uart_dev_t *hw, uart_sw_flowctrl_t *flow_ctrl, bool sw_flow_ctrl_en) +{ + if (sw_flow_ctrl_en) { + hw->flow_conf.xonoff_del = 1; + hw->flow_conf.sw_flow_con_en = 1; + hw->swfc_conf1.xon_threshold = flow_ctrl->xon_thrd; + hw->swfc_conf0.xoff_threshold = flow_ctrl->xoff_thrd; + hw->swfc_conf1.xon_char = flow_ctrl->xon_char; + hw->swfc_conf0.xoff_char = flow_ctrl->xoff_char; + } else { + hw->flow_conf.sw_flow_con_en = 0; + hw->flow_conf.xonoff_del = 0; + } +} + +/** + * @brief Configure the AT cmd char. When the receiver receives a continuous AT cmd char, it will produce at_cmd_char_det interrupt. + * + * @param hw Beginning address of the peripheral registers. + * @param cmd_char The AT cmd char configuration.The configuration member is: + * - cmd_char The AT cmd character + * - char_num The number of received AT cmd char must be equal to or greater than this value + * - gap_tout The interval between each AT cmd char, when the duration is less than this value, it will not take this data as AT cmd char + * - pre_idle The idle time before the first AT cmd char, when the duration is less than this value, it will not take the previous data as the last AT cmd char + * - post_idle The idle time after the last AT cmd char, when the duration is less than this value, it will not take this data as the first AT cmd char + * + * @return None. + */ +static inline void uart_ll_set_at_cmd_char(uart_dev_t *hw, uart_at_cmd_t *cmd_char) +{ + hw->at_cmd_char.data = cmd_char->cmd_char; + hw->at_cmd_char.char_num = cmd_char->char_num; + hw->at_cmd_postcnt.post_idle_num = cmd_char->post_idle; + hw->at_cmd_precnt.pre_idle_num = cmd_char->pre_idle; + hw->at_cmd_gaptout.rx_gap_tout = cmd_char->gap_tout; +} + +/** + * @brief Set the UART data bit mode. + * + * @param hw Beginning address of the peripheral registers. + * @param data_bit The data bit mode to be set. + * + * @return None. + */ +static inline void uart_ll_set_data_bit_num(uart_dev_t *hw, uart_word_length_t data_bit) +{ + hw->conf0.bit_num = data_bit; +} + +/** + * @brief Set the rts active level. + * + * @param hw Beginning address of the peripheral registers. + * @param level The rts active level, 0 or 1. + * + * @return None. + */ +static inline void uart_ll_set_rts_active_level(uart_dev_t *hw, int level) +{ + hw->conf0.sw_rts = level & 0x1; +} + +/** + * @brief Set the dtr active level. + * + * @param hw Beginning address of the peripheral registers. + * @param level The dtr active level, 0 or 1. + * + * @return None. + */ +static inline void uart_ll_set_dtr_active_level(uart_dev_t *hw, int level) +{ + hw->conf0.sw_dtr = level & 0x1; +} + +/** + * @brief Set the UART wakeup threshold. + * + * @param hw Beginning address of the peripheral registers. + * @param wakeup_thrd The wakeup threshold value to be set. When the input rx edge changes more than this value, + * the UART will active from light sleeping mode. + * + * @return None. + */ +static inline void uart_ll_set_wakeup_thrd(uart_dev_t *hw, uint32_t wakeup_thrd) +{ + hw->sleep_conf.active_threshold = wakeup_thrd - UART_LL_MIN_WAKEUP_THRESH; +} + +/** + * @brief Configure the UART work in normal mode. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None. + */ +static inline void uart_ll_set_mode_normal(uart_dev_t *hw) +{ + hw->rs485_conf.en = 0; + hw->rs485_conf.tx_rx_en = 0; + hw->rs485_conf.rx_busy_tx_en = 0; + hw->conf0.irda_en = 0; +} + +/** + * @brief Configure the UART work in rs485_app_ctrl mode. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None. + */ +static inline void uart_ll_set_mode_rs485_app_ctrl(uart_dev_t *hw) +{ + // Application software control, remove echo + hw->rs485_conf.rx_busy_tx_en = 1; + hw->conf0.irda_en = 0; + hw->conf0.sw_rts = 0; + hw->conf0.irda_en = 0; + hw->rs485_conf.dl0_en = 1; + hw->rs485_conf.dl1_en = 1; + hw->rs485_conf.en = 1; +} + +/** + * @brief Configure the UART work in rs485_half_duplex mode. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None. + */ +static inline void uart_ll_set_mode_rs485_half_duplex(uart_dev_t *hw) +{ + // Enable receiver, sw_rts = 1 generates low level on RTS pin + hw->conf0.sw_rts = 1; + // Half duplex mode + hw->rs485_conf.tx_rx_en = 0; + // Setting this bit will allow data to be transmitted while receiving data(full-duplex mode). + // But note that this full-duplex mode has no conflict detection function + hw->rs485_conf.rx_busy_tx_en = 0; + hw->conf0.irda_en = 0; + hw->rs485_conf.dl0_en = 1; + hw->rs485_conf.dl1_en = 1; + hw->rs485_conf.en = 1; +} + +/** + * @brief Configure the UART work in collision_detect mode. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None. + */ +static inline void uart_ll_set_mode_collision_detect(uart_dev_t *hw) +{ + hw->conf0.irda_en = 0; + // Enable full-duplex mode + hw->rs485_conf.tx_rx_en = 1; + // Transmitter should send data when the receiver is busy, + hw->rs485_conf.rx_busy_tx_en = 1; + hw->rs485_conf.dl0_en = 1; + hw->rs485_conf.dl1_en = 1; + hw->conf0.sw_rts = 0; + hw->rs485_conf.en = 1; +} + +/** + * @brief Configure the UART work in irda mode. + * + * @param hw Beginning address of the peripheral registers. + * + * @return None. + */ +static inline void uart_ll_set_mode_irda(uart_dev_t *hw) +{ + hw->rs485_conf.en = 0; + hw->rs485_conf.tx_rx_en = 0; + hw->rs485_conf.rx_busy_tx_en = 0; + hw->conf0.sw_rts = 0; + hw->conf0.irda_en = 1; +} + +/** + * @brief Set uart mode. + * + * @param hw Beginning address of the peripheral registers. + * @param mode The UART mode to be set. + * + * @return None. + */ +static inline void uart_ll_set_mode(uart_dev_t *hw, uart_mode_t mode) +{ + switch (mode) { + default: + case UART_MODE_UART: + uart_ll_set_mode_normal(hw); + break; + case UART_MODE_RS485_COLLISION_DETECT: + uart_ll_set_mode_collision_detect(hw); + break; + case UART_MODE_RS485_APP_CTRL: + uart_ll_set_mode_rs485_app_ctrl(hw); + break; + case UART_MODE_RS485_HALF_DUPLEX: + uart_ll_set_mode_rs485_half_duplex(hw); + break; + case UART_MODE_IRDA: + uart_ll_set_mode_irda(hw); + break; + } +} + +/** + * @brief Get the UART AT cmd char configuration. + * + * @param hw Beginning address of the peripheral registers. + * @param cmd_char The Pointer to accept value of UART AT cmd char. + * @param char_num Pointer to accept the repeat number of UART AT cmd char. + * + * @return None. + */ +static inline void uart_ll_get_at_cmd_char(uart_dev_t *hw, uint8_t *cmd_char, uint8_t *char_num) +{ + *cmd_char = hw->at_cmd_char.data; + *char_num = hw->at_cmd_char.char_num; +} + +/** + * @brief Get the UART wakeup threshold value. + * + * @param hw Beginning address of the peripheral registers. + * + * @return The UART wakeup threshold value. + */ +static inline uint32_t uart_ll_get_wakeup_thrd(uart_dev_t *hw) +{ + return hw->sleep_conf.active_threshold + UART_LL_MIN_WAKEUP_THRESH; +} + +/** + * @brief Get the UART data bit configuration. + * + * @param hw Beginning address of the peripheral registers. + * @param data_bit The pointer to accept the UART data bit configuration. + * + * @return The bit mode. + */ +static inline void uart_ll_get_data_bit_num(uart_dev_t *hw, uart_word_length_t *data_bit) +{ + *data_bit = hw->conf0.bit_num; +} + +/** + * @brief Check if the UART sending state machine is in the IDLE state. + * + * @param hw Beginning address of the peripheral registers. + * + * @return True if the state machine is in the IDLE state, otherwise false is returned. + */ +static inline bool uart_ll_is_tx_idle(uart_dev_t *hw) +{ + return ((hw->status.txfifo_cnt == 0) && (hw->fsm_status.st_utx_out == 0)); +} + +/** + * @brief Check if the UART rts flow control is enabled. + * + * @param hw Beginning address of the peripheral registers. + * + * @return True if hw rts flow control is enabled, otherwise false is returned. + */ +static inline bool uart_ll_is_hw_rts_en(uart_dev_t *hw) +{ + return hw->conf1.rx_flow_en; +} + +/** + * @brief Check if the UART cts flow control is enabled. + * + * @param hw Beginning address of the peripheral registers. + * + * @return True if hw cts flow control is enabled, otherwise false is returned. + */ +static inline bool uart_ll_is_hw_cts_en(uart_dev_t *hw) +{ + return hw->conf0.tx_flow_en; +} + +/** + * @brief Configure TX signal loop back to RX module, just for the testing purposes + * + * @param hw Beginning address of the peripheral registers. + * @param loop_back_en Set ture to enable the loop back function, else set it false. + * + * @return None + */ +static inline void uart_ll_set_loop_back(uart_dev_t *hw, bool loop_back_en) +{ + hw->conf0.loopback = loop_back_en; +} + +static inline void uart_ll_xon_force_on(uart_dev_t *hw, bool always_on) +{ + hw->flow_conf.force_xon = 1; + if(!always_on) { + hw->flow_conf.force_xon = 0; + } +} + +/** + * @brief Inverse the UART signal with the given mask. + * + * @param hw Beginning address of the peripheral registers. + * @param inv_mask The UART signal bitmap needs to be inversed. + * Use the ORred mask of `uart_signal_inv_t`; + * + * @return None. + */ +static inline void uart_ll_inverse_signal(uart_dev_t *hw, uint32_t inv_mask) +{ + typeof(hw->conf0) conf0_reg = hw->conf0; + conf0_reg.irda_tx_inv = (inv_mask & UART_SIGNAL_IRDA_TX_INV) ? 1 : 0; + conf0_reg.irda_rx_inv = (inv_mask & UART_SIGNAL_IRDA_RX_INV) ? 1 : 0; + conf0_reg.rxd_inv = (inv_mask & UART_SIGNAL_RXD_INV) ? 1 : 0; + conf0_reg.cts_inv = (inv_mask & UART_SIGNAL_CTS_INV) ? 1 : 0; + conf0_reg.dsr_inv = (inv_mask & UART_SIGNAL_DSR_INV) ? 1 : 0; + conf0_reg.txd_inv = (inv_mask & UART_SIGNAL_TXD_INV) ? 1 : 0; + conf0_reg.rts_inv = (inv_mask & UART_SIGNAL_RTS_INV) ? 1 : 0; + conf0_reg.dtr_inv = (inv_mask & UART_SIGNAL_DTR_INV) ? 1 : 0; + hw->conf0.val = conf0_reg.val; +} + +/** + * @brief Configure the timeout value for receiver receiving a byte, and enable rx timeout function. + * + * @param hw Beginning address of the peripheral registers. + * @param tout_thrd The timeout value as UART bit time. The rx timeout function will be disabled if `tout_thrd == 0`. + * + * @return None. + */ +static inline void uart_ll_set_rx_tout(uart_dev_t *hw, uint16_t tout_thrd) +{ + uint16_t tout_val = tout_thrd; + if(tout_thrd > 0) { + hw->mem_conf.rx_tout_thrhd = tout_val; + hw->conf1.rx_tout_en = 1; + } else { + hw->conf1.rx_tout_en = 0; + } +} + +/** + * @brief Get the timeout value for receiver receiving a byte. + * + * @param hw Beginning address of the peripheral registers. + * + * @return tout_thr The timeout threshold value. If timeout feature is disabled returns 0. + */ +static inline uint16_t uart_ll_get_rx_tout_thr(uart_dev_t *hw) +{ + uint16_t tout_thrd = 0; + if(hw->conf1.rx_tout_en > 0) { + tout_thrd = hw->mem_conf.rx_tout_thrhd; + } + return tout_thrd; +} + +/** + * @brief Get UART maximum timeout threshold. + * + * @param hw Beginning address of the peripheral registers. + * + * @return maximum timeout threshold. + */ +static inline uint16_t uart_ll_max_tout_thrd(uart_dev_t *hw) +{ + return UART_RX_TOUT_THRHD_V; +} + +/** + * @brief Force UART xoff. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return None. + */ +static inline void uart_ll_force_xoff(uart_port_t uart_num) +{ + REG_CLR_BIT(UART_FLOW_CONF_REG(uart_num), UART_FORCE_XON); + REG_SET_BIT(UART_FLOW_CONF_REG(uart_num), UART_SW_FLOW_CON_EN | UART_FORCE_XOFF); + REG_SET_BIT(UART_ID_REG(uart_num), UART_UPDATE); +} + +/** + * @brief Force UART xon. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return None. + */ +static inline void uart_ll_force_xon(uart_port_t uart_num) +{ + REG_CLR_BIT(UART_FLOW_CONF_REG(uart_num), UART_FORCE_XOFF); + REG_SET_BIT(UART_FLOW_CONF_REG(uart_num), UART_FORCE_XON); + REG_CLR_BIT(UART_FLOW_CONF_REG(uart_num), UART_SW_FLOW_CON_EN | UART_FORCE_XON); + REG_SET_BIT(UART_ID_REG(uart_num), UART_UPDATE); +} + +/** + * @brief Get UART final state machine status. + * + * @param uart_num UART port number, the max port number is (UART_NUM_MAX -1). + * + * @return UART module FSM status. + */ +static inline uint32_t uart_ll_get_fsm_status(uart_port_t uart_num) +{ + return REG_GET_FIELD(UART_FSM_STATUS_REG(uart_num), UART_ST_UTX_OUT); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uhci_ll.h b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uhci_ll.h new file mode 100644 index 00000000..1566d0b0 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/esp32c3/include/hal/uhci_ll.h @@ -0,0 +1,174 @@ +// Copyright 2020 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. + +// The LL layer for UHCI register operations. +// Note that most of the register operations in this layer are non-atomic operations. + + +#pragma once +#include +#include "uhci_types.h" +#include "soc/uhci_struct.h" +#include "soc/gdma_struct.h" + +#define UHCI_DMA_INDEX 0 + +#define UHCI_LL_GET_HW(num) (((num) == 0) ? (&UHCI0) : (NULL)) + +static inline void uhci_ll_init(uhci_dev_t *hw) +{ + typeof(hw->conf0) conf0_reg; + hw->conf0.clk_en = 1; + conf0_reg.val = 0; + conf0_reg.clk_en = 1; + hw->conf0.val = conf0_reg.val; + hw->conf1.val = 0; +} + +static inline void uhci_ll_attach_uart_port(uhci_dev_t *hw, int uart_num) +{ + abort(); // TODO ESP32-C3 IDF-2117 +} + +static inline void uhci_ll_set_seper_chr(uhci_dev_t *hw, uhci_seper_chr_t *seper_char) +{ + if (seper_char->sub_chr_en) { + typeof(hw->esc_conf0) esc_conf0_reg = hw->esc_conf0; + esc_conf0_reg.seper_char = seper_char->seper_chr; + esc_conf0_reg.seper_esc_char0 = seper_char->sub_chr1; + esc_conf0_reg.seper_esc_char1 = seper_char->sub_chr2; + hw->esc_conf0.val = esc_conf0_reg.val; + hw->escape_conf.tx_c0_esc_en = 1; + hw->escape_conf.rx_c0_esc_en = 1; + } else { + hw->escape_conf.tx_c0_esc_en = 0; + hw->escape_conf.rx_c0_esc_en = 0; + } +} + +static inline void uhci_ll_get_seper_chr(uhci_dev_t *hw, uhci_seper_chr_t *seper_chr) +{ + (void)hw; + (void)seper_chr; +} + +static inline void uhci_ll_set_swflow_ctrl_sub_chr(uhci_dev_t *hw, uhci_swflow_ctrl_sub_chr_t *sub_ctr) +{ + typeof(hw->escape_conf) escape_conf_reg = hw->escape_conf; + if (sub_ctr->flow_en == 1) { + typeof(hw->esc_conf2) esc_conf2_reg = hw->esc_conf2; + typeof(hw->esc_conf3) esc_conf3_reg = hw->esc_conf3; + esc_conf2_reg.seq1 = sub_ctr->xon_chr; + esc_conf2_reg.seq1_char0 = sub_ctr->xon_sub1; + esc_conf2_reg.seq1_char1 = sub_ctr->xon_sub2; + esc_conf3_reg.seq2 = sub_ctr->xoff_chr; + esc_conf3_reg.seq2_char0 = sub_ctr->xoff_sub1; + esc_conf3_reg.seq2_char1 = sub_ctr->xoff_sub2; + escape_conf_reg.tx_11_esc_en = 1; + escape_conf_reg.tx_13_esc_en = 1; + escape_conf_reg.rx_11_esc_en = 1; + escape_conf_reg.rx_13_esc_en = 1; + hw->esc_conf2.val = esc_conf2_reg.val; + hw->esc_conf3.val = esc_conf3_reg.val; + } else { + escape_conf_reg.tx_11_esc_en = 0; + escape_conf_reg.tx_13_esc_en = 0; + escape_conf_reg.rx_11_esc_en = 0; + escape_conf_reg.rx_13_esc_en = 0; + } + hw->escape_conf.val = escape_conf_reg.val; +} + +static inline void uhci_ll_dma_in_reset(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].in.in_conf0.in_rst = 1; + GDMA.channel[UHCI_DMA_INDEX].in.in_conf0.in_rst = 0; +} + +static inline void uhci_ll_dma_out_reset(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].out.out_conf0.out_rst = 1; + GDMA.channel[UHCI_DMA_INDEX].out.out_conf0.out_rst = 0; +} + +static inline void uhci_ll_enable_intr(uhci_dev_t *hw, uint32_t intr_mask) +{ + hw->int_ena.val |= intr_mask; +} + +static inline void uhci_ll_disable_intr(uhci_dev_t *hw, uint32_t intr_mask) +{ + hw->int_ena.val &= (~intr_mask); +} + +static inline void uhci_ll_clear_intr(uhci_dev_t *hw, uint32_t intr_mask) +{ + hw->int_clr.val = intr_mask; +} + +static inline uint32_t uhci_ll_get_intr(uhci_dev_t *hw) +{ + return hw->int_st.val; +} + +static inline void uhci_ll_set_rx_dma(uhci_dev_t *hw, uint32_t addr) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].in.in_link.addr = addr; +} + +static inline void uhci_ll_set_tx_dma(uhci_dev_t *hw, uint32_t addr) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].out.out_link.addr = addr; +} + +static inline void uhci_ll_rx_dma_start(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].in.in_link.start = 1; +} + +static inline void uhci_ll_tx_dma_start(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].out.out_link.start = 1; +} + +static inline void uhci_ll_rx_dma_stop(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].in.in_link.stop = 1; +} + +static inline void uhci_ll_tx_dma_stop(uhci_dev_t *hw) +{ + (void)hw; + GDMA.channel[UHCI_DMA_INDEX].out.out_link.stop = 1; +} + +static inline void uhci_ll_set_eof_mode(uhci_dev_t *hw, uint32_t eof_mode) +{ + if (eof_mode & UHCI_RX_BREAK_CHR_EOF) { + hw->conf0.uart_rx_brk_eof_en = 1; + } + if (eof_mode & UHCI_RX_IDLE_EOF) { + hw->conf0.uart_idle_eof_en = 1; + } + if (eof_mode & UHCI_RX_LEN_EOF) { + hw->conf0.len_eof_en = 1; + } +} diff --git a/tools/sdk/esp32c3/include/hal/include/hal/adc_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/adc_hal.h new file mode 100644 index 00000000..06f2e624 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/adc_hal.h @@ -0,0 +1,383 @@ +#pragma once + +#include "soc/soc_caps.h" +#include "hal/adc_types.h" +#include "hal/adc_ll.h" +#include "esp_err.h" + +#if CONFIG_IDF_TARGET_ESP32C3 +#include "soc/gdma_struct.h" +#include "hal/gdma_ll.h" +#include "hal/dma_types.h" +#include "hal/adc_ll.h" +#include "hal/dma_types.h" +#include "esp_err.h" + +//For ADC module, each conversion contains 4 bytes +#define ADC_HAL_DATA_LEN_PER_CONV 4 + +/** + * @brief Enum for DMA descriptor status + */ +typedef enum adc_hal_dma_desc_status_t { + ADC_HAL_DMA_DESC_VALID = 0, ///< This DMA descriptor is written by HW already + ADC_HAL_DMA_DESC_WAITING = 1, ///< This DMA descriptor is not written by HW yet + ADC_HAL_DMA_DESC_NULL = 2 ///< This DMA descriptor is NULL +} adc_hal_dma_desc_status_t; + +/** + * @brief Configuration of the HAL + */ +typedef struct adc_hal_config_t { + uint32_t desc_max_num; ///< Number of the descriptors linked once + uint32_t dma_chan; ///< DMA channel to be used + uint32_t eof_num; ///< Bytes between 2 in_suc_eof interrupts +} adc_hal_config_t; + +/** + * @brief Context of the HAL + */ +typedef struct adc_hal_context_t { + /**< this needs to be malloced by the driver layer first */ + dma_descriptor_t *rx_desc; ///< DMA descriptors + + /**< these will be assigned by hal layer itself */ + gdma_dev_t *dev; ///< GDMA address + dma_descriptor_t desc_dummy_head; ///< Dummy DMA descriptor for ``cur_desc_ptr`` to start + dma_descriptor_t *cur_desc_ptr; ///< Pointer to the current descriptor + + /**< these need to be configured by `adc_hal_config_t` via driver layer*/ + uint32_t desc_max_num; ///< Number of the descriptors linked once + uint32_t dma_chan; ///< DMA channel to be used + uint32_t eof_num; ///< Words between 2 in_suc_eof interrupts +} adc_hal_context_t; +#endif + +/*--------------------------------------------------------------- + Common setting +---------------------------------------------------------------*/ +/** + * ADC module initialization. + */ +void adc_hal_init(void); + +/** + * Set ADC module power management. + * + * @prarm manage Set ADC power status. + */ +#define adc_hal_set_power_manage(manage) adc_ll_set_power_manage(manage) + +/** + * ADC module clock division factor setting. ADC clock devided from APB clock. + * + * @prarm div Division factor. + */ +#define adc_hal_digi_set_clk_div(div) adc_ll_digi_set_clk_div(div) + +#if !CONFIG_IDF_TARGET_ESP32C3 +/** + * ADC SAR clock division factor setting. ADC SAR clock devided from `RTC_FAST_CLK`. + * + * @prarm div Division factor. + */ +#define adc_hal_set_sar_clk_div(adc_n, div) adc_ll_set_sar_clk_div(adc_n, div) + +/** + * Set ADC module controller. + * There are five SAR ADC controllers: + * Two digital controller: Continuous conversion mode (DMA). High performance with multiple channel scan modes; + * Two RTC controller: Single conversion modes (Polling). For low power purpose working during deep sleep; + * the other is dedicated for Power detect (PWDET / PKDET), Only support ADC2. + * + * @prarm adc_n ADC unit. + * @prarm ctrl ADC controller. + */ +#define adc_hal_set_controller(adc_n, ctrl) adc_ll_set_controller(adc_n, ctrl) +#endif //#if !CONFIG_IDF_TARGET_ESP32C3 + +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 +/** + * Get the attenuation of a particular channel on ADCn. + * + * @param adc_n ADC unit. + * @param channel ADCn channel number. + * @return atten The attenuation option. + */ +#define adc_hal_get_atten(adc_n, channel) adc_ll_get_atten(adc_n, channel) +#endif + +#if CONFIG_IDF_TARGET_ESP32 +/** + * Close ADC AMP module if don't use it for power save. + */ +#define adc_hal_amp_disable() adc_ll_amp_disable() +#endif + +/*--------------------------------------------------------------- + PWDET(Power detect) controller setting +---------------------------------------------------------------*/ + +/** + * Set adc cct for PWDET controller. + * + * @note Capacitor tuning of the PA power monitor. cct set to the same value with PHY. + * @prarm cct Range: 0 ~ 7. + */ +#define adc_hal_pwdet_set_cct(cct) adc_ll_pwdet_set_cct(cct) + +/** + * Get adc cct for PWDET controller. + * + * @note Capacitor tuning of the PA power monitor. cct set to the same value with PHY. + * @return cct Range: 0 ~ 7. + */ +#define adc_hal_pwdet_get_cct() adc_ll_pwdet_get_cct() + +/*--------------------------------------------------------------- + RTC controller setting +---------------------------------------------------------------*/ +#if !CONFIG_IDF_TARGET_ESP32C3 +/** + * Set adc output data format for RTC controller. + * + * @prarm adc_n ADC unit. + * @prarm bits Output data bits width option. + */ +#define adc_hal_rtc_set_output_format(adc_n, bits) adc_ll_rtc_set_output_format(adc_n, bits) + +/** + * ADC module output data invert or not. + * + * @prarm adc_n ADC unit. + */ +#define adc_hal_rtc_output_invert(adc_n, inv_en) adc_ll_rtc_output_invert(adc_n, inv_en) +#endif //#if !CONFIG_IDF_TARGET_ESP32C3 + +/** + * Enable/disable the output of ADCn's internal reference voltage to one of ADC2's channels. + * + * This function routes the internal reference voltage of ADCn to one of + * ADC2's channels. This reference voltage can then be manually measured + * for calibration purposes. + * + * @note ESP32 only supports output of ADC2's internal reference voltage. + * @param[in] adc ADC unit select + * @param[in] channel ADC2 channel number + * @param[in] en Enable/disable the reference voltage output + */ +#define adc_hal_vref_output(adc, channel, en) adc_ll_vref_output(adc, channel, en) + +/*--------------------------------------------------------------- + Digital controller setting +---------------------------------------------------------------*/ +/** + * Digital controller deinitialization. + */ +void adc_hal_digi_deinit(void); + +/** + * Setting the digital controller. + * + * @param cfg Pointer to digital controller paramter. + */ +void adc_hal_digi_controller_config(const adc_digi_config_t *cfg); + +/** + * Reset the pattern table pointer, then take the measurement rule from table header in next measurement. + * + * @param adc_n ADC unit. + */ +#define adc_hal_digi_clear_pattern_table(adc_n) adc_ll_digi_clear_pattern_table(adc_n) + +/*--------------------------------------------------------------- + ADC Single Read +---------------------------------------------------------------*/ +#if !CONFIG_IDF_TARGET_ESP32C3 +/** + * Set the attenuation of a particular channel on ADCn. + * + * @note For any given channel, this function must be called before the first time conversion. + * + * The default ADC full-scale voltage is 1.1V. To read higher voltages (up to the pin maximum voltage, + * usually 3.3V) requires setting >0dB signal attenuation for that ADC channel. + * + * When VDD_A is 3.3V: + * + * - 0dB attenuaton (ADC_ATTEN_DB_0) gives full-scale voltage 1.1V + * - 2.5dB attenuation (ADC_ATTEN_DB_2_5) gives full-scale voltage 1.5V + * - 6dB attenuation (ADC_ATTEN_DB_6) gives full-scale voltage 2.2V + * - 11dB attenuation (ADC_ATTEN_DB_11) gives full-scale voltage 3.9V (see note below) + * + * @note The full-scale voltage is the voltage corresponding to a maximum reading (depending on ADC1 configured + * bit width, this value is: 4095 for 12-bits, 2047 for 11-bits, 1023 for 10-bits, 511 for 9 bits.) + * + * @note At 11dB attenuation the maximum voltage is limited by VDD_A, not the full scale voltage. + * + * Due to ADC characteristics, most accurate results are obtained within the following approximate voltage ranges: + * + * - 0dB attenuaton (ADC_ATTEN_DB_0) between 100 and 950mV + * - 2.5dB attenuation (ADC_ATTEN_DB_2_5) between 100 and 1250mV + * - 6dB attenuation (ADC_ATTEN_DB_6) between 150 to 1750mV + * - 11dB attenuation (ADC_ATTEN_DB_11) between 150 to 2450mV + * + * For maximum accuracy, use the ADC calibration APIs and measure voltages within these recommended ranges. + * + * @param adc_n ADC unit. + * @param channel ADCn channel number. + * @param atten ADC attenuation. See ``adc_atten_t`` + */ +#define adc_hal_set_atten(adc_n, channel, atten) adc_ll_set_atten(adc_n, channel, atten) + +#else // CONFIG_IDF_TARGET_ESP32C3 +/** + * Set the attenuation for ADC to single read + * + * @note All ADC units and channels will share the setting. So PLEASE DO save your attenuations and reset them by calling this API again in your driver + * + * @param adc_n Not used, leave here for chip version compatibility + * @param channel Not used, leave here for chip version compatibility + * @param atten ADC attenuation. See ``adc_atten_t`` + */ +#define adc_hal_set_atten(adc_n, channel, atten) adc_ll_onetime_set_atten(atten) +#endif + +/** + * Start an ADC conversion and get the converted value. + * + * @note It may be block to wait conversion finish. + * + * @param adc_n ADC unit. + * @param channel ADC channel number. + * @param[out] out_raw ADC converted result + * + * @return + * - ESP_OK: The value is valid. + * - ESP_ERR_INVALID_STATE: The value is invalid. + */ +esp_err_t adc_hal_convert(adc_ll_num_t adc_n, int channel, int *out_raw); + +/*--------------------------------------------------------------- + ADC calibration setting +---------------------------------------------------------------*/ +#if SOC_ADC_HW_CALIBRATION_V1 +// ESP32-S2 and C3 support HW offset calibration. + +/** + * @brief Initialize default parameter for the calibration block. + * + * @param adc_n ADC index numer + */ +void adc_hal_calibration_init(adc_ll_num_t adc_n); + +/** + * Set the calibration result (initial data) to ADC. + * + * @note Different ADC units and different attenuation options use different calibration data (initial data). + * + * @param adc_n ADC index number. + * @param param the calibration parameter to configure + */ +void adc_hal_set_calibration_param(adc_ll_num_t adc_n, uint32_t param); + +/** + * Calibrate the ADC using internal connections. + * + * @note Different ADC units and different attenuation options use different calibration data (initial data). + * + * @param adc_n ADC index number. + * @param channel adc channel number. + * @param atten The attenuation for the channel + * @param internal_gnd true: Disconnect from the IO port and use the internal GND as the calibration voltage. + * false: Use IO external voltage as calibration voltage. + * + * @return + * - The calibration result (initial data) to ADC, use `adc_hal_set_calibration_param` to set. + */ +uint32_t adc_hal_self_calibration(adc_ll_num_t adc_n, adc_channel_t channel, adc_atten_t atten, bool internal_gnd); + +#endif //SOC_ADC_HW_CALIBRATION_V1 + +#if CONFIG_IDF_TARGET_ESP32C3 +/*--------------------------------------------------------------- + DMA setting +---------------------------------------------------------------*/ +/** + * @brief Initialize the hal context + * + * @param hal Context of the HAL + * @param config Configuration of the HAL + */ +void adc_hal_context_config(adc_hal_context_t *hal, const adc_hal_config_t *config); + +/** + * @brief Initialize the HW + * + * @param hal Context of the HAL + */ +void adc_hal_digi_init(adc_hal_context_t *hal); + +/** + * @brief Reset ADC / DMA fifo + * + * @param hal Context of the HAL + */ +void adc_hal_fifo_reset(adc_hal_context_t *hal); + +/** + * @brief Start DMA + * + * @param hal Context of the HAL + * @param data_buf Pointer to the data buffer, the length should be multiple of ``desc_max_num`` and ``eof_num`` in ``adc_hal_context_t`` + */ +void adc_hal_digi_rxdma_start(adc_hal_context_t *hal, uint8_t *data_buf); + +/** + * @brief Start ADC + * + * @param hal Context of the HAL + */ +void adc_hal_digi_start(adc_hal_context_t *hal); + +/** + * @brief Get the ADC reading result + * + * @param hal Context of the HAL + * @param eof_desc_addr The last descriptor that is finished by HW. Should be got from DMA + * @param[out] cur_desc The descriptor with ADC reading result (from the 1st one to the last one (``eof_desc_addr``)) + * + * @return See ``adc_hal_dma_desc_status_t`` + */ +adc_hal_dma_desc_status_t adc_hal_get_reading_result(adc_hal_context_t *hal, const intptr_t eof_desc_addr, dma_descriptor_t **cur_desc); + +/** + * @brief Stop DMA + * + * @param hal Context of the HAL + */ +void adc_hal_digi_rxdma_stop(adc_hal_context_t *hal); + +/** + * @brief Clear interrupt + * + * @param hal Context of the HAL + * @param mask mask of the interrupt + */ +void adc_hal_digi_clr_intr(adc_hal_context_t *hal, uint32_t mask); + +/** + * @brief Enable interrupt + * + * @param hal Context of the HAL + * @param mask mask of the interrupt + */ +void adc_hal_digi_dis_intr(adc_hal_context_t *hal, uint32_t mask); + +/** + * @brief Stop ADC + * + * @param hal Context of the HAL + */ +void adc_hal_digi_stop(adc_hal_context_t *hal); + +#endif //#if CONFIG_IDF_TARGET_ESP32C3 diff --git a/tools/sdk/esp32c3/include/hal/include/hal/adc_types.h b/tools/sdk/esp32c3/include/hal/include/hal/adc_types.h new file mode 100644 index 00000000..be0f3c67 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/adc_types.h @@ -0,0 +1,441 @@ +// Copyright 2020 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. +#pragma once + +#include +#include +#include "sdkconfig.h" +#include "soc/soc_caps.h" +#include "esp_attr.h" + +/** + * @brief ADC unit enumeration. + * + * @note For ADC digital controller (DMA mode), ESP32 doesn't support `ADC_UNIT_2`, `ADC_UNIT_BOTH`, `ADC_UNIT_ALTER`. + */ +typedef enum { + ADC_UNIT_1 = 1, /*!< SAR ADC 1. */ + ADC_UNIT_2 = 2, /*!< SAR ADC 2. */ + ADC_UNIT_BOTH = 3, /*!< SAR ADC 1 and 2. */ + ADC_UNIT_ALTER = 7, /*!< SAR ADC 1 and 2 alternative mode. */ + ADC_UNIT_MAX, +} adc_unit_t; + +/** + * @brief ADC channels handle. See ``adc1_channel_t``, ``adc2_channel_t``. + * + * @note For ESP32 ADC1, don't use `ADC_CHANNEL_8`, `ADC_CHANNEL_9`. See ``adc1_channel_t``. + */ +typedef enum { + ADC_CHANNEL_0 = 0, /*!< ADC channel */ + ADC_CHANNEL_1, /*!< ADC channel */ + ADC_CHANNEL_2, /*!< ADC channel */ + ADC_CHANNEL_3, /*!< ADC channel */ + ADC_CHANNEL_4, /*!< ADC channel */ + ADC_CHANNEL_5, /*!< ADC channel */ + ADC_CHANNEL_6, /*!< ADC channel */ + ADC_CHANNEL_7, /*!< ADC channel */ + ADC_CHANNEL_8, /*!< ADC channel */ + ADC_CHANNEL_9, /*!< ADC channel */ + ADC_CHANNEL_MAX, +} adc_channel_t; + +/** + * @brief ADC attenuation parameter. Different parameters determine the range of the ADC. See ``adc1_config_channel_atten``. + */ +typedef enum { + ADC_ATTEN_DB_0 = 0, /*! ADC_CHANNEL_MAX), The data is invalid. */ + } type1; /*! ADC_CHANNEL_MAX), The data is invalid. */ + uint16_t unit: 1; /*! ADC_CHANNEL_MAX), The data is invalid. */ + uint32_t unit: 1; /*! threshold, Generates monitor interrupt. + * MONITOR_LOW: If ADC_OUT < threshold, Generates monitor interrupt. + */ +typedef enum { +#if CONFIG_IDF_TARGET_ESP32C3 + ADC_DIGI_MONITOR_DIS = 0, /*! threshold, Generates monitor interrupt. */ +#else + ADC_DIGI_MONITOR_HIGH = 0, /*! threshold, Generates monitor interrupt. */ + ADC_DIGI_MONITOR_LOW, /*! +#include +#include "soc/soc_caps.h" +#include "hal/aes_types.h" +#include "hal/aes_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @brief Sets the key used for AES encryption/decryption + * + * @param key pointer to the key + * @param key_bytes number of bytes in key + * @param mode key mode, 0 : decrypt, 1: encrypt + * + * @return uint8_t number of key bytes written to hardware, used for fault injection check + */ +uint8_t aes_hal_setkey(const uint8_t *key, size_t key_bytes, int mode); + +/** + * @brief encrypts/decrypts a single block + * + * @param input_block input block, size of AES_BLOCK_BYTES + * @param output_block output block, size of AES_BLOCK_BYTES + */ +void aes_hal_transform_block(const void *input_block, void *output_block); + +#if SOC_AES_SUPPORT_DMA +/** + * @brief Inits the AES mode of operation + * + * @param mode mode of operation, e.g. CTR or CBC + */ +void aes_hal_mode_init(esp_aes_mode_t mode); + +/** + * @brief Sets the initialization vector for the transform + * + * @note The same IV must never be reused with the same key + * + * @param iv the initialization vector, length = IV_BYTES (16 bytes) + */ +void aes_hal_set_iv(const uint8_t *iv); + +/** + * @brief Reads the initialization vector + * + * @param iv initialization vector read from HW, length = IV_BYTES (16 bytes) + */ +void aes_hal_read_iv(uint8_t *iv); + +/** + * @brief Busy waits until the AES operation is done + * + * @param output pointer to inlink descriptor + */ +void aes_hal_wait_done(void); + +/** + * @brief Starts an already configured AES DMA transform + * + * @param num_blocks Number of blocks to transform + */ +void aes_hal_transform_dma_start(size_t num_blocks); + +/** + * @brief Finish up a AES DMA conversion, release DMA + * + */ +void aes_hal_transform_dma_finish(void); + +/** + * @brief Enable or disable transform completed interrupt + * + * @param enable true to enable, false to disable. + */ +#define aes_hal_interrupt_enable(enable) aes_ll_interrupt_enable(enable) + +/** + * @brief Clears the interrupt + * + */ +#define aes_hal_interrupt_clear() aes_ll_interrupt_clear() + +#if SOC_AES_SUPPORT_GCM +/** + * @brief Calculates the Hash sub-key H0 needed to start AES-GCM + * + * @param gcm_hash the Hash sub-key H0 output + */ +void aes_hal_gcm_calc_hash(uint8_t *gcm_hash); + +/** + * @brief Initializes the AES hardware for AES-GCM + * + * @param aad_num_blocks the number of Additional Authenticated Data (AAD) blocks + * @param num_valid_bit the number of effective bits of incomplete blocks in plaintext/cipertext + */ +void aes_hal_gcm_init(size_t aad_num_blocks, size_t num_valid_bit); + +/** + * @brief Starts a AES-GCM transform + * + * @param num_blocks Number of blocks to transform + */ +void aes_hal_transform_dma_gcm_start(size_t num_blocks); + +/** + * @brief Sets the J0 value, for more information see the GCM subchapter in the TRM + * + * @note Only affects AES-GCM + * + * @param j0 J0 value + */ +#define aes_hal_gcm_set_j0(j0) aes_ll_gcm_set_j0(j0) + +/** + * @brief Read the tag after a AES-GCM transform + * + * @param tag Pointer to where to store the result + * @param tag_length number of bytes to read into tag + */ +void aes_hal_gcm_read_tag(uint8_t *tag, size_t tag_len); + +#endif //SOC_AES_SUPPORT_GCM + +#endif //SOC_AES_SUPPORT_DMA + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/aes_types.h b/tools/sdk/esp32c3/include/hal/include/hal/aes_types.h new file mode 100644 index 00000000..e12d510c --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/aes_types.h @@ -0,0 +1,48 @@ +// Copyright 2020 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. +#pragma once + +/* padlock.c and aesni.c rely on these values! */ +#define ESP_AES_ENCRYPT 1 +#define ESP_AES_DECRYPT 0 + + +/* DMA AES working modes*/ +typedef enum { + ESP_AES_BLOCK_MODE_ECB = 0, + ESP_AES_BLOCK_MODE_CBC, + ESP_AES_BLOCK_MODE_OFB, + ESP_AES_BLOCK_MODE_CTR, + ESP_AES_BLOCK_MODE_CFB8, + ESP_AES_BLOCK_MODE_CFB128, + ESP_AES_BLOCK_MODE_GCM, + ESP_AES_BLOCK_MODE_MAX, +} esp_aes_mode_t; + +/* Number of bytes in an AES block */ +#define AES_BLOCK_BYTES (16) +/* Number of words in an AES block */ +#define AES_BLOCK_WORDS (4) +/* Number of bytes in an IV */ +#define IV_BYTES (16) +/* Number of words in an IV */ +#define IV_WORDS (4) +/* Number of bytes in a GCM tag block */ +#define TAG_BYTES (16) +/* Number of words in a GCM tag block */ +#define TAG_WORDS (4) + +#define AES_128_KEY_BYTES (128/8) +#define AES_192_KEY_BYTES (192/8) +#define AES_256_KEY_BYTES (256/8) diff --git a/tools/sdk/esp32c3/include/hal/include/hal/brownout_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/brownout_hal.h new file mode 100644 index 00000000..b56823b3 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/brownout_hal.h @@ -0,0 +1,48 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include "soc/soc_caps.h" + +typedef struct { + uint8_t threshold; + bool enabled; + bool reset_enabled; + bool flash_power_down; + bool rf_power_down; +} brownout_hal_config_t; + +void brownout_hal_config(const brownout_hal_config_t *cfg); + +void brownout_hal_intr_enable(bool enable); + +void brownout_hal_intr_clear(void); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/cpu_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/cpu_hal.h new file mode 100644 index 00000000..e6b7c62d --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/cpu_hal.h @@ -0,0 +1,132 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include + +#include "esp_err.h" + +#include "soc/soc_caps.h" +#include "hal/cpu_types.h" +#include "hal/cpu_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Return the ID of the core currently executing this code. + * + * @return core id [0..SOC_CPU_CORES_NUM - 1] + */ +#define cpu_hal_get_core_id() cpu_ll_get_core_id() + +/** + * Get the current value of the stack pointer. + * + * @return the current stack pointer + */ +#define cpu_hal_get_sp() cpu_ll_get_sp() + +/** + * Get the current value of the internal counter that increments + * every processor-clock cycle. + * + * @return cycle count; returns 0 if not supported + */ +#define cpu_hal_get_cycle_count() cpu_ll_get_cycle_count() + +/** + * Set the given value into the internal counter that increments + * every processor-clock cycle. + */ +#define cpu_hal_set_cycle_count(val) cpu_ll_set_cycle_count(val) + +/** + * Check if some form of debugger is attached to CPU. + * + * @return true debugger is attached + * @return false no debugger is attached/ no support for debuggers + */ +#define cpu_hal_is_debugger_attached() cpu_ll_is_debugger_attached() + +/** + * Init HW loop status. + */ +#define cpu_hal_init_hwloop() cpu_ll_init_hwloop() + +/** + * Trigger a call to debugger. + */ +#define cpu_hal_break() cpu_ll_break() + +/** + * Wait for interrupt. + */ +#define cpu_hal_waiti() cpu_ll_waiti() + +#if SOC_CPU_BREAKPOINTS_NUM > 0 + +/** + * Set and enable breakpoint at an instruction address. + * + * @note Overwrites previously set breakpoint with same breakpoint ID. + * + * @param id breakpoint to set [0..SOC_CPU_BREAKPOINTS_NUM - 1] + * @param addr address to set a breakpoint on + */ +void cpu_hal_set_breakpoint(int id, const void* addr); + +/** + * Clear and disable breakpoint. + * + * @param id breakpoint to clear [0..SOC_CPU_BREAKPOINTS_NUM - 1] + */ +void cpu_hal_clear_breakpoint(int id); + +#endif // SOC_CPU_BREAKPOINTS_NUM > 0 + +#if SOC_CPU_WATCHPOINTS_NUM > 0 + +/** + * Set and enable a watchpoint, specifying the memory range and trigger operation. + * + * @param id watchpoint to set [0..SOC_CPU_WATCHPOINTS_NUM - 1] + * @param addr starting address + * @param size number of bytes from starting address to watch + * @param trigger operation on specified memory range that triggers the watchpoint (read, write, read/write) + */ +void cpu_hal_set_watchpoint(int id, const void* addr, size_t size, watchpoint_trigger_t trigger); + +/** + * Clear and disable watchpoint. + * + * @param id watchpoint to clear [0..SOC_CPU_WATCHPOINTS_NUM - 1] + */ +void cpu_hal_clear_watchpoint(int id); + +#endif // SOC_CPU_WATCHPOINTS_NUM > 0 + +/** + * Set exception vector table base address. + * + * @param base address to move the exception vector table to + */ +void cpu_hal_set_vecbase(const void* base); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/cpu_types.h b/tools/sdk/esp32c3/include/hal/include/hal/cpu_types.h new file mode 100644 index 00000000..d61a47c9 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/cpu_types.h @@ -0,0 +1,21 @@ +// Copyright 2020 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. + +#pragma once + +typedef enum { + WATCHPOINT_TRIGGER_ON_RO, // on read + WATCHPOINT_TRIGGER_ON_WO, // on write + WATCHPOINT_TRIGGER_ON_RW // on either read or write +} watchpoint_trigger_t; diff --git a/tools/sdk/esp32c3/include/hal/include/hal/dac_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/dac_hal.h new file mode 100644 index 00000000..aeecf485 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/dac_hal.h @@ -0,0 +1,80 @@ +// Copyright 2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#include "hal/dac_ll.h" +#include "hal/hal_defs.h" +#include + +/** + * Power on dac module and start output voltage. + * + * @note Before powering up, make sure the DAC PAD is set to RTC PAD and floating status. + * @param channel DAC channel num. + */ +#define dac_hal_power_on(channel) dac_ll_power_on(channel) + +/** + * Power done dac module and stop output voltage. + * + * @param channel DAC channel num. + */ +#define dac_hal_power_down(channel) dac_ll_power_down(channel) + +/** + * Enable/disable the synchronization operation function of ADC1 and DAC. + * + * @note If enabled(default), ADC RTC controller sampling will cause the DAC channel output voltage. + * + * @param enable Enable or disable adc and dac synchronization function. + */ +#define dac_hal_rtc_sync_by_adc(enable) dac_ll_rtc_sync_by_adc(enable) + +/** + * Output voltage with value (8 bit). + * + * @param channel DAC channel num. + * @param value Output value. Value range: 0 ~ 255. + * The corresponding range of voltage is 0v ~ VDD3P3_RTC. + */ +#define dac_hal_update_output_value(channel, value) dac_ll_update_output_value(channel, value) + +/** + * Enable cosine wave generator output. + */ +#define dac_hal_cw_generator_enable() dac_ll_cw_generator_enable() + +/** + * Disable cosine wave generator output. + */ +#define dac_hal_cw_generator_disable() dac_ll_cw_generator_disable() + +/** + * Config the cosine wave generator function in DAC module. + * + * @param cw Configuration. + */ +void dac_hal_cw_generator_config(dac_cw_config_t *cw); + +/** + * Enable/disable DAC output data from DMA. + */ +#define dac_hal_digi_enable_dma(enable) dac_ll_digi_enable_dma(enable) diff --git a/tools/sdk/esp32c3/include/hal/include/hal/dac_types.h b/tools/sdk/esp32c3/include/hal/include/hal/dac_types.h new file mode 100644 index 00000000..4fe32226 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/dac_types.h @@ -0,0 +1,67 @@ +#pragma once + +#include "soc/soc_caps.h" +#include "hal/adc_types.h" +#include "sdkconfig.h" + +typedef enum { + DAC_CHANNEL_1 = 0, /*!< DAC channel 1 is GPIO25(ESP32) / GPIO17(ESP32S2) */ + DAC_CHANNEL_2 = 1, /*!< DAC channel 2 is GPIO26(ESP32) / GPIO18(ESP32S2) */ + DAC_CHANNEL_MAX, +} dac_channel_t; + +/** + * @brief The multiple of the amplitude of the cosine wave generator. The max amplitude is VDD3P3_RTC. + */ +typedef enum { + DAC_CW_SCALE_1 = 0x0, /*!< 1/1. Default. */ + DAC_CW_SCALE_2 = 0x1, /*!< 1/2. */ + DAC_CW_SCALE_4 = 0x2, /*!< 1/4. */ + DAC_CW_SCALE_8 = 0x3, /*!< 1/8. */ +} dac_cw_scale_t; + +/** + * @brief Set the phase of the cosine wave generator output. + */ +typedef enum { + DAC_CW_PHASE_0 = 0x2, /*!< Phase shift +0° */ + DAC_CW_PHASE_180 = 0x3, /*!< Phase shift +180° */ +} dac_cw_phase_t; + +/** + * @brief Config the cosine wave generator function in DAC module. + */ +typedef struct { + dac_channel_t en_ch; /*!< Enable the cosine wave generator of DAC channel. */ + dac_cw_scale_t scale; /*!< Set the amplitude of the cosine wave generator output. */ + dac_cw_phase_t phase; /*!< Set the phase of the cosine wave generator output. */ + uint32_t freq; /*!< Set frequency of cosine wave generator output. Range: 130(130Hz) ~ 55000(100KHz). */ + int8_t offset; /*!< Set the voltage value of the DC component of the cosine wave generator output. + Note: Unreasonable settings can cause waveform to be oversaturated. Range: -128 ~ 127. */ +} dac_cw_config_t; + +#if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 + +/** + * @brief DAC digital controller (DMA mode) work mode. + */ +typedef enum { + DAC_CONV_NORMAL, /*!< The data in the DMA buffer is simultaneously output to the enable channel of the DAC. */ + DAC_CONV_ALTER, /*!< The data in the DMA buffer is alternately output to the enable channel of the DAC. */ + DAC_CONV_MAX +} dac_digi_convert_mode_t; + +/** + * @brief DAC digital controller (DMA mode) configuration parameters. + */ +typedef struct { + dac_digi_convert_mode_t mode; /*! + +/** + * @brief Type of DMA descriptor + * + */ +typedef struct dma_descriptor_s { + struct { + uint32_t size : 12; /*!< Buffer size */ + uint32_t length : 12; /*!< Number of valid bytes in the buffer */ + uint32_t reversed24_27 : 4; /*!< Reserved */ + uint32_t err_eof : 1; /*!< Whether the received buffer contains error */ + uint32_t reserved29 : 1; /*!< Reserved */ + uint32_t suc_eof : 1; /*!< Whether the descriptor is the last one in the link */ + uint32_t owner : 1; /*!< Who is allowed to access the buffer that this descriptor points to */ + } dw0; /*!< Descriptor Word 0 */ + void *buffer; /*!< Pointer to the buffer */ + struct dma_descriptor_s *next; /*!< Pointer to the next descriptor (set to NULL if the descriptor is the last one, e.g. suc_eof=1) */ +} dma_descriptor_t; + +_Static_assert(sizeof(dma_descriptor_t) == 12, "dma_descriptor_t should occupy 12 bytes in memory"); + +#define DMA_DESCRIPTOR_BUFFER_OWNER_CPU (0) /*!< DMA buffer is allowed to be accessed by CPU */ +#define DMA_DESCRIPTOR_BUFFER_OWNER_DMA (1) /*!< DMA buffer is allowed to be accessed by DMA engine */ +#define DMA_DESCRIPTOR_BUFFER_MAX_SIZE (4095) /*!< Maximum size of the buffer that can be attached to descriptor */ diff --git a/tools/sdk/esp32c3/include/hal/include/hal/ds_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/ds_hal.h new file mode 100644 index 00000000..fe7d7892 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/ds_hal.h @@ -0,0 +1,112 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use it in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#if CONFIG_IDF_TARGET_ESP32 + #error "ESP32 doesn't have a DS peripheral" +#endif + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The result when checking whether the key to decrypt the RSA parameters is ready. + */ +typedef enum { + DS_KEY_INPUT_OK = 0, /**< The decryption key is ready. */ + DS_NO_KEY_INPUT, /**< Dependent peripheral providing key hasn't been activated. */ + DS_OTHER_WRONG, /**< Dependent peripheral running but problem receiving the key. */ +} ds_key_check_t; + +typedef enum { + DS_SIGNATURE_OK = 0, /**< Signature is valid and can be read. */ + DS_SIGNATURE_PADDING_FAIL = 1, /**< Padding invalid, signature can be read if user wants it. */ + DS_SIGNATURE_MD_FAIL = 2, /**< Message digest check failed, signature invalid. */ + DS_SIGNATURE_PADDING_AND_MD_FAIL = 3, /**< Both padding and MD check failed. */ +} ds_signature_check_t; + +/** + * @brief Start the whole signing process after the input key is ready. + * + * Call this before using any of the functions below. The input key is ready must be ready at this point. + */ +void ds_hal_start(void); + +/** + * @brief Finish the whole signing process. Call this after the signature is read or in case of an error. + */ +void ds_hal_finish(void); + +/** + * @brief Check whether the key input (HMAC on ESP32-C3) is correct. + */ +ds_key_check_t ds_hal_check_decryption_key(void); + +/** + * @brief Write the initialization vector. + */ +void ds_hal_configure_iv(const uint32_t *iv); + +/** + * @brief Write the message which should be signed. + * + * @param msg Pointer to the message. + * @param size Length of signature result in bytes. It is the RSA signature length in bytes. + */ +void ds_hal_write_message(const uint8_t *msg, size_t size); + +/** + * @brief Write the encrypted private key parameters. + */ +void ds_hal_write_private_key_params(const uint8_t *block); + +/** + * @brief Begin signing procedure. + */ +void ds_hal_start_sign(void); + +/** + * @brief Check whether the hardware is busy with an operation. + * + * @return True if the hardware has finished the signing procedure, otherwise false. + */ +bool ds_hal_busy(void); + +/** + * @brief Check and read the signature from the hardware. + * + * @return + * - DS_SIGNATURE_OK if no issue is detected with the signature. + * - DS_SIGNATURE_PADDING_FAIL if the padding of the private key parameters is wrong. + * - DS_SIGNATURE_MD_FAIL if the message digest check failed. This means that the message digest calculated using + * the private key parameters fails, i.e., the integrity of the private key parameters is not protected. + * - DS_SIGNATURE_PADDING_AND_MD_FAIL if both padding and message digest check fail. + */ +ds_signature_check_t ds_hal_read_result(uint8_t *result, size_t size); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/esp_flash_err.h b/tools/sdk/esp32c3/include/hal/include/hal/esp_flash_err.h new file mode 100644 index 00000000..3da8b56d --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/esp_flash_err.h @@ -0,0 +1,48 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * Possible errors returned from esp flash internal functions, these error codes + * should be consistent with esp_err_t codes. But in order to make the source + * files less dependent to esp_err_t, they use the error codes defined in this + * replacable header. This header should ensure the consistency to esp_err_t. + */ + +enum { + /* These codes should be consistent with esp_err_t errors. However, error codes with the same values are not + * allowed in ESP-IDF. This is a workaround in order to not introduce a dependency between the "soc" and + * "esp_common" components. The disadvantage is that the output of esp_err_to_name(ESP_ERR_FLASH_SIZE_NOT_MATCH) + * will be ESP_ERR_INVALID_SIZE. */ + ESP_ERR_FLASH_SIZE_NOT_MATCH = ESP_ERR_INVALID_SIZE, ///< The chip doesn't have enough space for the current partition table + ESP_ERR_FLASH_NO_RESPONSE = ESP_ERR_INVALID_RESPONSE, ///< Chip did not respond to the command, or timed out. +}; + +//The ROM code has already taken 1 and 2, to avoid possible conflicts, start from 3. +#define ESP_ERR_FLASH_NOT_INITIALISED (ESP_ERR_FLASH_BASE+3) ///< esp_flash_chip_t structure not correctly initialised by esp_flash_init(). +#define ESP_ERR_FLASH_UNSUPPORTED_HOST (ESP_ERR_FLASH_BASE+4) ///< Requested operation isn't supported via this host SPI bus (chip->spi field). +#define ESP_ERR_FLASH_UNSUPPORTED_CHIP (ESP_ERR_FLASH_BASE+5) ///< Requested operation isn't supported by this model of SPI flash chip. +#define ESP_ERR_FLASH_PROTECTED (ESP_ERR_FLASH_BASE+6) ///< Write operation failed due to chip's write protection being enabled. + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/gdma_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/gdma_hal.h new file mode 100644 index 00000000..5f83b483 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/gdma_hal.h @@ -0,0 +1,37 @@ +// Copyright 2020 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. + +/******************************************************************************* + * NOTICE + * The HAL is not public api, don't use in application code. + * See readme.md in soc/README.md + ******************************************************************************/ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/gdma_struct.h" + +typedef struct { + gdma_dev_t *dev; +} gdma_hal_context_t; + +void gdma_hal_init(gdma_hal_context_t *hal, int group_id); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/gpio_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/gpio_hal.h new file mode 100644 index 00000000..5a403f52 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/gpio_hal.h @@ -0,0 +1,471 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for GPIO + +#pragma once + +#include "soc/gpio_periph.h" +#include "soc/soc_caps.h" +#include "hal/gpio_ll.h" +#include "hal/gpio_types.h" + +#ifdef CONFIG_LEGACY_INCLUDE_COMMON_HEADERS +#include "soc/rtc_io_reg.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// Get GPIO hardware instance with giving gpio num +#define GPIO_HAL_GET_HW(num) GPIO_LL_GET_HW(num) + +/** + * Context that should be maintained by both the driver and the HAL + */ + +typedef struct { + gpio_dev_t *dev; + uint32_t version; +} gpio_hal_context_t; + +/** + * @brief Enable pull-up on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_pullup_en(hal, gpio_num) gpio_ll_pullup_en((hal)->dev, gpio_num) + +/** + * @brief Disable pull-up on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_pullup_dis(hal, gpio_num) gpio_ll_pullup_dis((hal)->dev, gpio_num) + +/** + * @brief Enable pull-down on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_pulldown_en(hal, gpio_num) gpio_ll_pulldown_en((hal)->dev, gpio_num) + +/** + * @brief Disable pull-down on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_pulldown_dis(hal, gpio_num) gpio_ll_pulldown_dis((hal)->dev, gpio_num) + +/** + * @brief GPIO set interrupt trigger type + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param intr_type Interrupt type, select from gpio_int_type_t + */ +#define gpio_hal_set_intr_type(hal, gpio_num, intr_type) gpio_ll_set_intr_type((hal)->dev, gpio_num, intr_type) + +/** + * @brief Get GPIO interrupt status + * + * @param hal Context of the HAL layer + * @param core_id interrupt core id + * @param status interrupt status + */ +#define gpio_hal_get_intr_status(hal, core_id, status) gpio_ll_get_intr_status((hal)->dev, core_id, status) + +/** + * @brief Get GPIO interrupt status high + * + * @param hal Context of the HAL layer + * @param core_id interrupt core id + * @param status interrupt status high + */ +#define gpio_hal_get_intr_status_high(hal, core_id, status) gpio_ll_get_intr_status_high((hal)->dev, core_id, status) + +/** + * @brief Clear GPIO interrupt status + * + * @param hal Context of the HAL layer + * @param mask interrupt status clear mask + */ +#define gpio_hal_clear_intr_status(hal, mask) gpio_ll_clear_intr_status((hal)->dev, mask) + +/** + * @brief Clear GPIO interrupt status high + * + * @param hal Context of the HAL layer + * @param mask interrupt status high clear mask + */ +#define gpio_hal_clear_intr_status_high(hal, mask) gpio_ll_clear_intr_status_high((hal)->dev, mask) + +/** + * @brief Enable GPIO module interrupt signal + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. If you want to enable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param core_id Interrupt enabled CPU to corresponding ID + */ +void gpio_hal_intr_enable_on_core(gpio_hal_context_t *hal, gpio_num_t gpio_num, uint32_t core_id); + +/** + * @brief Disable GPIO module interrupt signal + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + */ +void gpio_hal_intr_disable(gpio_hal_context_t *hal, gpio_num_t gpio_num); + +/** + * @brief Disable input mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_input_disable(hal, gpio_num) gpio_ll_input_disable((hal)->dev, gpio_num) + +/** + * @brief Enable input mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_input_enable(hal, gpio_num) gpio_ll_input_enable((hal)->dev, gpio_num) + +/** + * @brief Disable output mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_output_disable(hal, gpio_num) gpio_ll_output_disable((hal)->dev, gpio_num) + +/** + * @brief Enable output mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_output_enable(hal, gpio_num) gpio_ll_output_enable((hal)->dev, gpio_num) + +/** + * @brief Disable open-drain mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_od_disable(hal, gpio_num) gpio_ll_od_disable((hal)->dev, gpio_num) + +/** + * @brief Enable open-drain mode on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_od_enable(hal, gpio_num) gpio_ll_od_enable((hal)->dev, gpio_num) + +/** + * @brief GPIO set output level + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16); + * @param level Output level. 0: low ; 1: high + */ +#define gpio_hal_set_level(hal, gpio_num, level) gpio_ll_set_level((hal)->dev, gpio_num, level) + +/** + * @brief GPIO get input level + * + * @warning If the pad is not configured for input (or input and output) the returned value is always 0. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16); + * + * @return + * - 0 the GPIO input level is 0 + * - 1 the GPIO input level is 1 + */ +#define gpio_hal_get_level(hal, gpio_num) gpio_ll_get_level((hal)->dev, gpio_num) + +/** + * @brief Enable GPIO wake-up function. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + */ +#define gpio_hal_wakeup_enable(hal, gpio_num, intr_type) gpio_ll_wakeup_enable((hal)->dev, gpio_num, intr_type) + +/** + * @brief Disable GPIO wake-up function. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_wakeup_disable(hal, gpio_num) gpio_ll_wakeup_disable((hal)->dev, gpio_num) + +/** + * @brief Set GPIO pad drive capability + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Drive capability of the pad + */ +#define gpio_hal_set_drive_capability(hal, gpio_num, strength) gpio_ll_set_drive_capability((hal)->dev, gpio_num, strength) + +/** + * @brief Get GPIO pad drive capability + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number, only support output GPIOs + * @param strength Pointer to accept drive capability of the pad + */ +#define gpio_hal_get_drive_capability(hal, gpio_num, strength) gpio_ll_get_drive_capability((hal)->dev, gpio_num, strength) + +/** + * @brief Enable gpio pad hold function. + * + * The gpio pad hold function works in both input and output modes, but must be output-capable gpios. + * If pad hold enabled: + * in output mode: the output level of the pad will be force locked and can not be changed. + * in input mode: the input value read will not change, regardless the changes of input signal. + * + * The state of digital gpio cannot be held during Deep-sleep, and it will resume the hold function + * when the chip wakes up from Deep-sleep. If the digital gpio also needs to be held during Deep-sleep, + * `gpio_deep_sleep_hold_en` should also be called. + * + * Power down or call gpio_hold_dis will disable this function. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number, only support output GPIOs + */ +#define gpio_hal_hold_en(hal, gpio_num) gpio_ll_hold_en((hal)->dev, gpio_num) + +/** + * @brief Disable gpio pad hold function. + * + * When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output + * the default level if this function is called. If you don't want the level changes, the gpio should be configured to + * a known state before this function is called. + * e.g. + * If you hold gpio18 high during Deep-sleep, after the chip is woken up and `gpio_hold_dis` is called, + * gpio18 will output low level(because gpio18 is input mode by default). If you don't want this behavior, + * you should configure gpio18 as output mode and set it to hight level before calling `gpio_hold_dis`. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number, only support output GPIOs + */ +#define gpio_hal_hold_dis(hal, gpio_num) gpio_ll_hold_dis((hal)->dev, gpio_num) + +/** + * @brief Enable all digital gpio pad hold function during Deep-sleep. + * + * When the chip is in Deep-sleep mode, all digital gpio will hold the state before sleep, and when the chip is woken up, + * the status of digital gpio will not be held. Note that the pad hold feature only works when the chip is in Deep-sleep mode, + * when not in sleep mode, the digital gpio state can be changed even you have called this function. + * + * Power down or call gpio_hold_dis will disable this function, otherwise, the digital gpio hold feature works as long as the chip enter Deep-sleep. + * + * @param hal Context of the HAL layer + */ +#define gpio_hal_deep_sleep_hold_en(hal) gpio_ll_deep_sleep_hold_en((hal)->dev) + +/** + * @brief Disable all digital gpio pad hold function during Deep-sleep. + * + * @param hal Context of the HAL layer + */ +#define gpio_hal_deep_sleep_hold_dis(hal) gpio_ll_deep_sleep_hold_dis((hal)->dev) + +/** + * @brief Set pad input to a peripheral signal through the IOMUX. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number of the pad. + * @param signal_idx Peripheral signal id to input. One of the ``*_IN_IDX`` signals in ``soc/gpio_sig_map.h``. + */ +#define gpio_hal_iomux_in(hal, gpio_num, signal_idx) gpio_ll_iomux_in((hal)->dev, gpio_num, signal_idx) + +/** + * @brief Set peripheral output to an GPIO pad through the IOMUX. + * + * @param hal Context of the HAL layer + * @param gpio_num gpio_num GPIO number of the pad. + * @param func The function number of the peripheral pin to output pin. + * One of the ``FUNC_X_*`` of specified pin (X) in ``soc/io_mux_reg.h``. + * @param oen_inv True if the output enable needs to be inverted, otherwise False. + */ +#define gpio_hal_iomux_out(hal, gpio_num, func, oen_inv) gpio_ll_iomux_out((hal)->dev, gpio_num, func, oen_inv) + +#if SOC_GPIO_SUPPORT_FORCE_HOLD +/** + * @brief Force hold digital and rtc gpio pad. + * @note GPIO force hold, whether the chip in sleep mode or wakeup mode. + * + * @param hal Context of the HAL layer + * */ +#define gpio_hal_force_hold_all(hal) gpio_ll_force_hold_all((hal)->dev) + +/** + * @brief Force unhold digital and rtc gpio pad. + * @note GPIO force unhold, whether the chip in sleep mode or wakeup mode. + * + * @param hal Context of the HAL layer + * */ +#define gpio_hal_force_unhold_all() gpio_ll_force_unhold_all() +#endif + +#if SOC_GPIO_SUPPORT_SLP_SWITCH +/** + * @brief Enable pull-up on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_pullup_en(hal, gpio_num) gpio_ll_sleep_pullup_en((hal)->dev, gpio_num) + +/** + * @brief Disable pull-up on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_pullup_dis(hal, gpio_num) gpio_ll_sleep_pullup_dis((hal)->dev, gpio_num) + +/** + * @brief Enable pull-down on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_pulldown_en(hal, gpio_num) gpio_ll_sleep_pulldown_en((hal)->dev, gpio_num) + +/** + * @brief Disable pull-down on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_pulldown_dis(hal, gpio_num) gpio_ll_sleep_pulldown_dis((hal)->dev, gpio_num) + +/** + * @brief Enable sleep select on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_sel_en(hal, gpio_num) gpio_ll_sleep_sel_en((hal)->dev, gpio_num) + +/** + * @brief Disable sleep select on GPIO. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_sel_dis(hal, gpio_num) gpio_ll_sleep_sel_dis((hal)->dev, gpio_num) + +/** + * @brief Disable input mode on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_input_disable(hal, gpio_num) gpio_ll_sleep_input_disable((hal)->dev, gpio_num) + +/** + * @brief Enable input mode on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_input_enable(hal, gpio_num) gpio_ll_sleep_input_enable((hal)->dev, gpio_num) + +/** + * @brief Disable output mode on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_output_disable(hal, gpio_num) gpio_ll_sleep_output_disable((hal)->dev, gpio_num) + +/** + * @brief Enable output mode on GPIO when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_sleep_output_enable(hal, gpio_num) gpio_ll_sleep_output_enable((hal)->dev, gpio_num) + +#if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL +/** + * @brief Apply slp_pu/slp_pd configuration to fun_pu/fun_pd when system sleep. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. + */ +void gpio_hal_sleep_pupd_config_apply(gpio_hal_context_t *hal, gpio_num_t gpio_num); + +/** + * @brief Restore fun_pu/fun_pd configuration when system wakeup. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. + */ +void gpio_hal_sleep_pupd_config_unapply(gpio_hal_context_t *hal, gpio_num_t gpio_num); +#endif // CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL +#endif //SOC_GPIO_SUPPORT_SLP_SWITCH + +#if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP + +/** + * @brief Enable GPIO deep-sleep wake-up function. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number. + * @param intr_type GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used. + */ +#define gpio_hal_deepsleep_wakeup_enable(hal, gpio_num, intr_type) gpio_ll_deepsleep_wakeup_enable((hal)->dev, gpio_num, intr_type) + +/** + * @brief Disable GPIO deep-sleep wake-up function. + * + * @param hal Context of the HAL layer + * @param gpio_num GPIO number + */ +#define gpio_hal_deepsleep_wakeup_disable(hal, gpio_num) gpio_ll_deepsleep_wakeup_disable((hal)->dev, gpio_num) + +/** + * @brief Judge if the gpio is valid for waking up chip from deep-sleep + * + * @param gpio_num GPIO number + */ +#define gpio_hal_is_valid_deepsleep_wakeup_gpio(gpio_num) (gpio_num <= GPIO_NUM_5) + +#endif //SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/gpio_types.h b/tools/sdk/esp32c3/include/hal/include/hal/gpio_types.h new file mode 100644 index 00000000..2438014a --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/gpio_types.h @@ -0,0 +1,371 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "soc/gpio_periph.h" +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + GPIO_PORT_0 = 0, + GPIO_PORT_MAX, +} gpio_port_t; + +#define GPIO_SEL_0 (BIT(0)) /*!< Pin 0 selected */ +#define GPIO_SEL_1 (BIT(1)) /*!< Pin 1 selected */ +#define GPIO_SEL_2 (BIT(2)) /*!< Pin 2 selected */ +#define GPIO_SEL_3 (BIT(3)) /*!< Pin 3 selected */ +#define GPIO_SEL_4 (BIT(4)) /*!< Pin 4 selected */ +#define GPIO_SEL_5 (BIT(5)) /*!< Pin 5 selected */ +#define GPIO_SEL_6 (BIT(6)) /*!< Pin 6 selected */ +#define GPIO_SEL_7 (BIT(7)) /*!< Pin 7 selected */ +#define GPIO_SEL_8 (BIT(8)) /*!< Pin 8 selected */ +#define GPIO_SEL_9 (BIT(9)) /*!< Pin 9 selected */ +#define GPIO_SEL_10 (BIT(10)) /*!< Pin 10 selected */ +#define GPIO_SEL_11 (BIT(11)) /*!< Pin 11 selected */ +#define GPIO_SEL_12 (BIT(12)) /*!< Pin 12 selected */ +#define GPIO_SEL_13 (BIT(13)) /*!< Pin 13 selected */ +#define GPIO_SEL_14 (BIT(14)) /*!< Pin 14 selected */ +#define GPIO_SEL_15 (BIT(15)) /*!< Pin 15 selected */ +#define GPIO_SEL_16 (BIT(16)) /*!< Pin 16 selected */ +#define GPIO_SEL_17 (BIT(17)) /*!< Pin 17 selected */ +#define GPIO_SEL_18 (BIT(18)) /*!< Pin 18 selected */ +#define GPIO_SEL_19 (BIT(19)) /*!< Pin 19 selected */ +#define GPIO_SEL_20 (BIT(20)) /*!< Pin 20 selected */ +#define GPIO_SEL_21 (BIT(21)) /*!< Pin 21 selected */ +#if CONFIG_IDF_TARGET_ESP32 +#define GPIO_SEL_22 (BIT(22)) /*!< Pin 22 selected */ +#define GPIO_SEL_23 (BIT(23)) /*!< Pin 23 selected */ + +#define GPIO_SEL_25 (BIT(25)) /*!< Pin 25 selected */ +#endif +#define GPIO_SEL_26 (BIT(26)) /*!< Pin 26 selected */ +#define GPIO_SEL_27 (BIT(27)) /*!< Pin 27 selected */ +#define GPIO_SEL_28 (BIT(28)) /*!< Pin 28 selected */ +#define GPIO_SEL_29 (BIT(29)) /*!< Pin 29 selected */ +#define GPIO_SEL_30 (BIT(30)) /*!< Pin 30 selected */ +#define GPIO_SEL_31 (BIT(31)) /*!< Pin 31 selected */ +#define GPIO_SEL_32 ((uint64_t)(((uint64_t)1)<<32)) /*!< Pin 32 selected */ +#define GPIO_SEL_33 ((uint64_t)(((uint64_t)1)<<33)) /*!< Pin 33 selected */ +#define GPIO_SEL_34 ((uint64_t)(((uint64_t)1)<<34)) /*!< Pin 34 selected */ +#define GPIO_SEL_35 ((uint64_t)(((uint64_t)1)<<35)) /*!< Pin 35 selected */ +#define GPIO_SEL_36 ((uint64_t)(((uint64_t)1)<<36)) /*!< Pin 36 selected */ +#define GPIO_SEL_37 ((uint64_t)(((uint64_t)1)<<37)) /*!< Pin 37 selected */ +#define GPIO_SEL_38 ((uint64_t)(((uint64_t)1)<<38)) /*!< Pin 38 selected */ +#define GPIO_SEL_39 ((uint64_t)(((uint64_t)1)<<39)) /*!< Pin 39 selected */ +#if SOC_GPIO_PIN_COUNT > 40 +#define GPIO_SEL_40 ((uint64_t)(((uint64_t)1)<<40)) /*!< Pin 40 selected */ +#define GPIO_SEL_41 ((uint64_t)(((uint64_t)1)<<41)) /*!< Pin 41 selected */ +#define GPIO_SEL_42 ((uint64_t)(((uint64_t)1)<<42)) /*!< Pin 42 selected */ +#define GPIO_SEL_43 ((uint64_t)(((uint64_t)1)<<43)) /*!< Pin 43 selected */ +#define GPIO_SEL_44 ((uint64_t)(((uint64_t)1)<<44)) /*!< Pin 44 selected */ +#define GPIO_SEL_45 ((uint64_t)(((uint64_t)1)<<45)) /*!< Pin 45 selected */ +#define GPIO_SEL_46 ((uint64_t)(((uint64_t)1)<<46)) /*!< Pin 46 selected */ +#endif + +#define GPIO_PIN_REG_0 IO_MUX_GPIO0_REG +#define GPIO_PIN_REG_1 IO_MUX_GPIO1_REG +#define GPIO_PIN_REG_2 IO_MUX_GPIO2_REG +#define GPIO_PIN_REG_3 IO_MUX_GPIO3_REG +#define GPIO_PIN_REG_4 IO_MUX_GPIO4_REG +#define GPIO_PIN_REG_5 IO_MUX_GPIO5_REG +#define GPIO_PIN_REG_6 IO_MUX_GPIO6_REG +#define GPIO_PIN_REG_7 IO_MUX_GPIO7_REG +#define GPIO_PIN_REG_8 IO_MUX_GPIO8_REG +#define GPIO_PIN_REG_9 IO_MUX_GPIO9_REG +#define GPIO_PIN_REG_10 IO_MUX_GPIO10_REG +#define GPIO_PIN_REG_11 IO_MUX_GPIO11_REG +#define GPIO_PIN_REG_12 IO_MUX_GPIO12_REG +#define GPIO_PIN_REG_13 IO_MUX_GPIO13_REG +#define GPIO_PIN_REG_14 IO_MUX_GPIO14_REG +#define GPIO_PIN_REG_15 IO_MUX_GPIO15_REG +#define GPIO_PIN_REG_16 IO_MUX_GPIO16_REG +#define GPIO_PIN_REG_17 IO_MUX_GPIO17_REG +#define GPIO_PIN_REG_18 IO_MUX_GPIO18_REG +#define GPIO_PIN_REG_19 IO_MUX_GPIO19_REG +#define GPIO_PIN_REG_20 IO_MUX_GPIO20_REG +#define GPIO_PIN_REG_21 IO_MUX_GPIO21_REG +#define GPIO_PIN_REG_22 IO_MUX_GPIO22_REG +#define GPIO_PIN_REG_23 IO_MUX_GPIO23_REG +#define GPIO_PIN_REG_24 IO_MUX_GPIO24_REG +#define GPIO_PIN_REG_25 IO_MUX_GPIO25_REG +#define GPIO_PIN_REG_26 IO_MUX_GPIO26_REG +#define GPIO_PIN_REG_27 IO_MUX_GPIO27_REG +#define GPIO_PIN_REG_28 IO_MUX_GPIO28_REG +#define GPIO_PIN_REG_29 IO_MUX_GPIO29_REG +#define GPIO_PIN_REG_30 IO_MUX_GPIO30_REG +#define GPIO_PIN_REG_31 IO_MUX_GPIO31_REG +#define GPIO_PIN_REG_32 IO_MUX_GPIO32_REG +#define GPIO_PIN_REG_33 IO_MUX_GPIO33_REG +#define GPIO_PIN_REG_34 IO_MUX_GPIO34_REG +#define GPIO_PIN_REG_35 IO_MUX_GPIO35_REG +#define GPIO_PIN_REG_36 IO_MUX_GPIO36_REG +#define GPIO_PIN_REG_37 IO_MUX_GPIO37_REG +#define GPIO_PIN_REG_38 IO_MUX_GPIO38_REG +#define GPIO_PIN_REG_39 IO_MUX_GPIO39_REG +#define GPIO_PIN_REG_40 IO_MUX_GPIO40_REG +#define GPIO_PIN_REG_41 IO_MUX_GPIO41_REG +#define GPIO_PIN_REG_42 IO_MUX_GPIO42_REG +#define GPIO_PIN_REG_43 IO_MUX_GPIO43_REG +#define GPIO_PIN_REG_44 IO_MUX_GPIO44_REG +#define GPIO_PIN_REG_45 IO_MUX_GPIO45_REG +#define GPIO_PIN_REG_46 IO_MUX_GPIO46_REG + +#if CONFIG_IDF_TARGET_ESP32 +typedef enum { + GPIO_NUM_NC = -1, /*!< Use to signal not connected to S/W */ + GPIO_NUM_0 = 0, /*!< GPIO0, input and output */ + GPIO_NUM_1 = 1, /*!< GPIO1, input and output */ + GPIO_NUM_2 = 2, /*!< GPIO2, input and output */ + GPIO_NUM_3 = 3, /*!< GPIO3, input and output */ + GPIO_NUM_4 = 4, /*!< GPIO4, input and output */ + GPIO_NUM_5 = 5, /*!< GPIO5, input and output */ + GPIO_NUM_6 = 6, /*!< GPIO6, input and output */ + GPIO_NUM_7 = 7, /*!< GPIO7, input and output */ + GPIO_NUM_8 = 8, /*!< GPIO8, input and output */ + GPIO_NUM_9 = 9, /*!< GPIO9, input and output */ + GPIO_NUM_10 = 10, /*!< GPIO10, input and output */ + GPIO_NUM_11 = 11, /*!< GPIO11, input and output */ + GPIO_NUM_12 = 12, /*!< GPIO12, input and output */ + GPIO_NUM_13 = 13, /*!< GPIO13, input and output */ + GPIO_NUM_14 = 14, /*!< GPIO14, input and output */ + GPIO_NUM_15 = 15, /*!< GPIO15, input and output */ + GPIO_NUM_16 = 16, /*!< GPIO16, input and output */ + GPIO_NUM_17 = 17, /*!< GPIO17, input and output */ + GPIO_NUM_18 = 18, /*!< GPIO18, input and output */ + GPIO_NUM_19 = 19, /*!< GPIO19, input and output */ + GPIO_NUM_20 = 20, /*!< GPIO20, input and output */ + GPIO_NUM_21 = 21, /*!< GPIO21, input and output */ + GPIO_NUM_22 = 22, /*!< GPIO22, input and output */ + GPIO_NUM_23 = 23, /*!< GPIO23, input and output */ + GPIO_NUM_25 = 25, /*!< GPIO25, input and output */ + GPIO_NUM_26 = 26, /*!< GPIO26, input and output */ + GPIO_NUM_27 = 27, /*!< GPIO27, input and output */ + GPIO_NUM_28 = 28, /*!< GPIO28, input and output */ + GPIO_NUM_29 = 29, /*!< GPIO29, input and output */ + GPIO_NUM_30 = 30, /*!< GPIO30, input and output */ + GPIO_NUM_31 = 31, /*!< GPIO31, input and output */ + GPIO_NUM_32 = 32, /*!< GPIO32, input and output */ + GPIO_NUM_33 = 33, /*!< GPIO33, input and output */ + GPIO_NUM_34 = 34, /*!< GPIO34, input mode only */ + GPIO_NUM_35 = 35, /*!< GPIO35, input mode only */ + GPIO_NUM_36 = 36, /*!< GPIO36, input mode only */ + GPIO_NUM_37 = 37, /*!< GPIO37, input mode only */ + GPIO_NUM_38 = 38, /*!< GPIO38, input mode only */ + GPIO_NUM_39 = 39, /*!< GPIO39, input mode only */ + GPIO_NUM_MAX, +/** @endcond */ +} gpio_num_t; +#elif CONFIG_IDF_TARGET_ESP32S2 +typedef enum { + GPIO_NUM_NC = -1, /*!< Use to signal not connected to S/W */ + GPIO_NUM_0 = 0, /*!< GPIO0, input and output */ + GPIO_NUM_1 = 1, /*!< GPIO1, input and output */ + GPIO_NUM_2 = 2, /*!< GPIO2, input and output */ + GPIO_NUM_3 = 3, /*!< GPIO3, input and output */ + GPIO_NUM_4 = 4, /*!< GPIO4, input and output */ + GPIO_NUM_5 = 5, /*!< GPIO5, input and output */ + GPIO_NUM_6 = 6, /*!< GPIO6, input and output */ + GPIO_NUM_7 = 7, /*!< GPIO7, input and output */ + GPIO_NUM_8 = 8, /*!< GPIO8, input and output */ + GPIO_NUM_9 = 9, /*!< GPIO9, input and output */ + GPIO_NUM_10 = 10, /*!< GPIO10, input and output */ + GPIO_NUM_11 = 11, /*!< GPIO11, input and output */ + GPIO_NUM_12 = 12, /*!< GPIO12, input and output */ + GPIO_NUM_13 = 13, /*!< GPIO13, input and output */ + GPIO_NUM_14 = 14, /*!< GPIO14, input and output */ + GPIO_NUM_15 = 15, /*!< GPIO15, input and output */ + GPIO_NUM_16 = 16, /*!< GPIO16, input and output */ + GPIO_NUM_17 = 17, /*!< GPIO17, input and output */ + GPIO_NUM_18 = 18, /*!< GPIO18, input and output */ + GPIO_NUM_19 = 19, /*!< GPIO19, input and output */ + GPIO_NUM_20 = 20, /*!< GPIO20, input and output */ + GPIO_NUM_21 = 21, /*!< GPIO21, input and output */ + GPIO_NUM_26 = 26, /*!< GPIO26, input and output */ + GPIO_NUM_27 = 27, /*!< GPIO27, input and output */ + GPIO_NUM_28 = 28, /*!< GPIO28, input and output */ + GPIO_NUM_29 = 29, /*!< GPIO29, input and output */ + GPIO_NUM_30 = 30, /*!< GPIO30, input and output */ + GPIO_NUM_31 = 31, /*!< GPIO31, input and output */ + GPIO_NUM_32 = 32, /*!< GPIO32, input and output */ + GPIO_NUM_33 = 33, /*!< GPIO33, input and output */ + GPIO_NUM_34 = 34, /*!< GPIO34, input and output */ + GPIO_NUM_35 = 35, /*!< GPIO35, input and output */ + GPIO_NUM_36 = 36, /*!< GPIO36, input and output */ + GPIO_NUM_37 = 37, /*!< GPIO37, input and output */ + GPIO_NUM_38 = 38, /*!< GPIO38, input and output */ + GPIO_NUM_39 = 39, /*!< GPIO39, input and output */ + GPIO_NUM_40 = 40, /*!< GPIO40, input and output */ + GPIO_NUM_41 = 41, /*!< GPIO41, input and output */ + GPIO_NUM_42 = 42, /*!< GPIO42, input and output */ + GPIO_NUM_43 = 43, /*!< GPIO43, input and output */ + GPIO_NUM_44 = 44, /*!< GPIO44, input and output */ + GPIO_NUM_45 = 45, /*!< GPIO45, input and output */ + GPIO_NUM_46 = 46, /*!< GPIO46, input mode only */ + GPIO_NUM_MAX, +/** @endcond */ +} gpio_num_t; +#elif CONFIG_IDF_TARGET_ESP32S3 +typedef enum { + GPIO_NUM_NC = -1, /*!< Use to signal not connected to S/W */ + GPIO_NUM_0 = 0, /*!< GPIO0, input and output */ + GPIO_NUM_1 = 1, /*!< GPIO1, input and output */ + GPIO_NUM_2 = 2, /*!< GPIO2, input and output */ + GPIO_NUM_3 = 3, /*!< GPIO3, input and output */ + GPIO_NUM_4 = 4, /*!< GPIO4, input and output */ + GPIO_NUM_5 = 5, /*!< GPIO5, input and output */ + GPIO_NUM_6 = 6, /*!< GPIO6, input and output */ + GPIO_NUM_7 = 7, /*!< GPIO7, input and output */ + GPIO_NUM_8 = 8, /*!< GPIO8, input and output */ + GPIO_NUM_9 = 9, /*!< GPIO9, input and output */ + GPIO_NUM_10 = 10, /*!< GPIO10, input and output */ + GPIO_NUM_11 = 11, /*!< GPIO11, input and output */ + GPIO_NUM_12 = 12, /*!< GPIO12, input and output */ + GPIO_NUM_13 = 13, /*!< GPIO13, input and output */ + GPIO_NUM_14 = 14, /*!< GPIO14, input and output */ + GPIO_NUM_15 = 15, /*!< GPIO15, input and output */ + GPIO_NUM_16 = 16, /*!< GPIO16, input and output */ + GPIO_NUM_17 = 17, /*!< GPIO17, input and output */ + GPIO_NUM_18 = 18, /*!< GPIO18, input and output */ + GPIO_NUM_19 = 19, /*!< GPIO19, input and output */ + GPIO_NUM_20 = 20, /*!< GPIO20, input and output */ + GPIO_NUM_21 = 21, /*!< GPIO21, input and output */ + GPIO_NUM_26 = 26, /*!< GPIO26, input and output */ + GPIO_NUM_27 = 27, /*!< GPIO27, input and output */ + GPIO_NUM_28 = 28, /*!< GPIO28, input and output */ + GPIO_NUM_29 = 29, /*!< GPIO29, input and output */ + GPIO_NUM_30 = 30, /*!< GPIO30, input and output */ + GPIO_NUM_31 = 31, /*!< GPIO31, input and output */ + GPIO_NUM_32 = 32, /*!< GPIO32, input and output */ + GPIO_NUM_33 = 33, /*!< GPIO33, input and output */ + GPIO_NUM_34 = 34, /*!< GPIO34, input and output */ + GPIO_NUM_35 = 35, /*!< GPIO35, input and output */ + GPIO_NUM_36 = 36, /*!< GPIO36, input and output */ + GPIO_NUM_37 = 37, /*!< GPIO37, input and output */ + GPIO_NUM_38 = 38, /*!< GPIO38, input and output */ + GPIO_NUM_39 = 39, /*!< GPIO39, input and output */ + GPIO_NUM_40 = 40, /*!< GPIO40, input and output */ + GPIO_NUM_41 = 41, /*!< GPIO41, input and output */ + GPIO_NUM_42 = 42, /*!< GPIO42, input and output */ + GPIO_NUM_43 = 43, /*!< GPIO43, input and output */ + GPIO_NUM_44 = 44, /*!< GPIO44, input and output */ + GPIO_NUM_45 = 45, /*!< GPIO45, input and output */ + GPIO_NUM_46 = 46, /*!< GPIO46, input mode only */ + GPIO_NUM_47 = 47, /*!< GPIO47, input and output */ + GPIO_NUM_MAX, +/** @endcond */ +} gpio_num_t; +#elif CONFIG_IDF_TARGET_ESP32C3 +typedef enum { + GPIO_NUM_NC = -1, /*!< Use to signal not connected to S/W */ + GPIO_NUM_0 = 0, /*!< GPIO0, input and output */ + GPIO_NUM_1 = 1, /*!< GPIO1, input and output */ + GPIO_NUM_2 = 2, /*!< GPIO2, input and output */ + GPIO_NUM_3 = 3, /*!< GPIO3, input and output */ + GPIO_NUM_4 = 4, /*!< GPIO4, input and output */ + GPIO_NUM_5 = 5, /*!< GPIO5, input and output */ + GPIO_NUM_6 = 6, /*!< GPIO6, input and output */ + GPIO_NUM_7 = 7, /*!< GPIO7, input and output */ + GPIO_NUM_8 = 8, /*!< GPIO8, input and output */ + GPIO_NUM_9 = 9, /*!< GPIO9, input and output */ + GPIO_NUM_10 = 10, /*!< GPIO10, input and output */ + GPIO_NUM_11 = 11, /*!< GPIO11, input and output */ + GPIO_NUM_12 = 12, /*!< GPIO12, input and output */ + GPIO_NUM_13 = 13, /*!< GPIO13, input and output */ + GPIO_NUM_14 = 14, /*!< GPIO14, input and output */ + GPIO_NUM_15 = 15, /*!< GPIO15, input and output */ + GPIO_NUM_16 = 16, /*!< GPIO16, input and output */ + GPIO_NUM_17 = 17, /*!< GPIO17, input and output */ + GPIO_NUM_18 = 18, /*!< GPIO18, input and output */ + GPIO_NUM_19 = 19, /*!< GPIO19, input and output */ + GPIO_NUM_20 = 20, /*!< GPIO20, input and output */ + GPIO_NUM_21 = 21, /*!< GPIO21, input and output */ + GPIO_NUM_22 = 22, /*!< GPIO22, input and output */ + GPIO_NUM_MAX, +/** @endcond */ +} gpio_num_t; +#endif + +typedef enum { + GPIO_INTR_DISABLE = 0, /*!< Disable GPIO interrupt */ + GPIO_INTR_POSEDGE = 1, /*!< GPIO interrupt type : rising edge */ + GPIO_INTR_NEGEDGE = 2, /*!< GPIO interrupt type : falling edge */ + GPIO_INTR_ANYEDGE = 3, /*!< GPIO interrupt type : both rising and falling edge */ + GPIO_INTR_LOW_LEVEL = 4, /*!< GPIO interrupt type : input low level trigger */ + GPIO_INTR_HIGH_LEVEL = 5, /*!< GPIO interrupt type : input high level trigger */ + GPIO_INTR_MAX, +} gpio_int_type_t; + +/** @cond */ +#define GPIO_MODE_DEF_DISABLE (0) +#define GPIO_MODE_DEF_INPUT (BIT0) ///< bit mask for input +#define GPIO_MODE_DEF_OUTPUT (BIT1) ///< bit mask for output +#define GPIO_MODE_DEF_OD (BIT2) ///< bit mask for OD mode +/** @endcond */ + +typedef enum { + GPIO_MODE_DISABLE = GPIO_MODE_DEF_DISABLE, /*!< GPIO mode : disable input and output */ + GPIO_MODE_INPUT = GPIO_MODE_DEF_INPUT, /*!< GPIO mode : input only */ + GPIO_MODE_OUTPUT = GPIO_MODE_DEF_OUTPUT, /*!< GPIO mode : output only mode */ + GPIO_MODE_OUTPUT_OD = ((GPIO_MODE_DEF_OUTPUT) | (GPIO_MODE_DEF_OD)), /*!< GPIO mode : output only with open-drain mode */ + GPIO_MODE_INPUT_OUTPUT_OD = ((GPIO_MODE_DEF_INPUT) | (GPIO_MODE_DEF_OUTPUT) | (GPIO_MODE_DEF_OD)), /*!< GPIO mode : output and input with open-drain mode*/ + GPIO_MODE_INPUT_OUTPUT = ((GPIO_MODE_DEF_INPUT) | (GPIO_MODE_DEF_OUTPUT)), /*!< GPIO mode : output and input mode */ +} gpio_mode_t; + +typedef enum { + GPIO_PULLUP_DISABLE = 0x0, /*!< Disable GPIO pull-up resistor */ + GPIO_PULLUP_ENABLE = 0x1, /*!< Enable GPIO pull-up resistor */ +} gpio_pullup_t; + +typedef enum { + GPIO_PULLDOWN_DISABLE = 0x0, /*!< Disable GPIO pull-down resistor */ + GPIO_PULLDOWN_ENABLE = 0x1, /*!< Enable GPIO pull-down resistor */ +} gpio_pulldown_t; + +/** + * @brief Configuration parameters of GPIO pad for gpio_config function + */ +typedef struct { + uint64_t pin_bit_mask; /*!< GPIO pin: set with bit mask, each bit maps to a GPIO */ + gpio_mode_t mode; /*!< GPIO mode: set input/output mode */ + gpio_pullup_t pull_up_en; /*!< GPIO pull-up */ + gpio_pulldown_t pull_down_en; /*!< GPIO pull-down */ + gpio_int_type_t intr_type; /*!< GPIO interrupt type */ +} gpio_config_t; + +typedef enum { + GPIO_PULLUP_ONLY, /*!< Pad pull up */ + GPIO_PULLDOWN_ONLY, /*!< Pad pull down */ + GPIO_PULLUP_PULLDOWN, /*!< Pad pull up + pull down*/ + GPIO_FLOATING, /*!< Pad floating */ +} gpio_pull_mode_t; + +typedef enum { + GPIO_DRIVE_CAP_0 = 0, /*!< Pad drive capability: weak */ + GPIO_DRIVE_CAP_1 = 1, /*!< Pad drive capability: stronger */ + GPIO_DRIVE_CAP_2 = 2, /*!< Pad drive capability: medium */ + GPIO_DRIVE_CAP_DEFAULT = 2, /*!< Pad drive capability: medium */ + GPIO_DRIVE_CAP_3 = 3, /*!< Pad drive capability: strongest */ + GPIO_DRIVE_CAP_MAX, +} gpio_drive_cap_t; + +typedef void (*gpio_isr_t)(void *); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/hal_defs.h b/tools/sdk/esp32c3/include/hal/include/hal/hal_defs.h new file mode 100644 index 00000000..f209ac09 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/hal_defs.h @@ -0,0 +1,30 @@ +// Copyright 2010-2018 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. + +#pragma once + +#include "esp_log.h" + +// platform related stuff + +#define HAL_SWAP32(word) __builtin_bswap32(word) +#define HAL_SWAP64(word) __builtin_bswap64(word) + +#define HAL_LOGE(...) ESP_LOGE(__VA_ARGS__) +#define HAL_LOGW(...) ESP_LOGW(__VA_ARGS__) +#define HAL_LOGI(...) ESP_LOGI(__VA_ARGS__) +#define HAL_LOGD(...) ESP_LOGD(__VA_ARGS__) +#define HAL_LOGV(...) ESP_LOGV(__VA_ARGS__) + +#define STATIC_HAL_REG_CHECK(TAG, ENUM, VAL) _Static_assert((ENUM) == (VAL), #TAG" "#ENUM" definition no longer matches register value") diff --git a/tools/sdk/esp32c3/include/hal/include/hal/i2c_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/i2c_hal.h new file mode 100644 index 00000000..cac45a7f --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/i2c_hal.h @@ -0,0 +1,534 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for I2C + +#pragma once +#include "hal/i2c_ll.h" +#include "hal/i2c_types.h" + +/** + * @brief I2C hal Context definition + */ +typedef struct { + i2c_dev_t *dev; + uint32_t version; +} i2c_hal_context_t; + +/** + * @brief Write the I2C rxfifo with the given length + * + * @param hal Context of the HAL layer + * @param wr_data Pointer to data buffer + * @param wr_size Amount of data needs write + * + * @return None + */ +#define i2c_hal_write_txfifo(hal,wr_data,wr_size) i2c_ll_write_txfifo((hal)->dev,wr_data,wr_size) + +/** + * @brief Read the I2C rxfifo with the given length + * + * @param hal Context of the HAL layer + * @param buf Pointer to data buffer + * @param rd_size Amount of data needs read + * + * @return None + */ +#define i2c_hal_read_rxfifo(hal,buf,rd_size) i2c_ll_read_rxfifo((hal)->dev,buf,rd_size) + +/** + * @brief Write I2C cmd register + * + * @param hal Context of the HAL layer + * @param cmd I2C hardware command + * @param cmd_idx The index of the command register, should be less than 16 + * + * @return None + */ +#define i2c_hal_write_cmd_reg(hal,cmd, cmd_idx) i2c_ll_write_cmd_reg((hal)->dev,cmd,cmd_idx) + +/** + * @brief Configure the I2C to triger a trasaction + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define i2c_hal_trans_start(hal) i2c_ll_trans_start((hal)->dev) + +/** + * @brief Enable I2C master RX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define i2c_hal_enable_master_rx_it(hal) i2c_ll_master_enable_rx_it((hal)->dev) + +/** + * @brief Enable I2C master TX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define i2c_hal_enable_master_tx_it(hal) i2c_ll_master_enable_tx_it((hal)->dev) + +/** + * @brief Clear I2C slave TX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define i2c_hal_slave_clr_tx_it(hal) i2c_ll_slave_clr_tx_it((hal)->dev) + +/** + * @brief Clear I2C slave RX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define i2c_hal_slave_clr_rx_it(hal) i2c_ll_slave_clr_rx_it((hal)->dev) + +/** + * @brief Init the I2C master. + * + * @param hal Context of the HAL layer + * @param i2c_num I2C port number + * + * @return None + */ +void i2c_hal_master_init(i2c_hal_context_t *hal, i2c_port_t i2c_num); + +/** + * @brief Init the I2C slave. + * + * @param hal Context of the HAL layer + * @param i2c_num I2C port number + * + * @return None + */ +void i2c_hal_slave_init(i2c_hal_context_t *hal, i2c_port_t i2c_num); + +/** + * @brief Reset the I2C hw txfifo + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_txfifo_rst(i2c_hal_context_t *hal); + +/** + * @brief Reset the I2C hw rxfifo + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_rxfifo_rst(i2c_hal_context_t *hal); + +/** + * @brief Configure the I2C data MSB bit shifted first or LSB bit shifted first. + * + * @param hal Context of the HAL layer + * @param tx_mode Data format of TX + * @param rx_mode Data format of RX + * + * @return None + */ +void i2c_hal_set_data_mode(i2c_hal_context_t *hal, i2c_trans_mode_t tx_mode, i2c_trans_mode_t rx_mode); + +/** + * @brief Configure the I2C hardware filter function. + * + * @param hal Context of the HAL layer + * @param filter_num If the glitch period on the line is less than this value(in APB cycle), it will be filtered out + * If `filter_num == 0`, the filter will be disabled + * + * @return None + */ +void i2c_hal_set_filter(i2c_hal_context_t *hal, uint8_t filter_num); + +/** + * @brief Get the I2C hardware filter configuration + * + * @param hal Context of the HAL layer + * @param filter_num Pointer to accept the hardware filter configuration + * + * @return None + */ +void i2c_hal_get_filter(i2c_hal_context_t *hal, uint8_t *filter_num); + +/** + * @brief Configure the I2C SCL timing + * + * @param hal Context of the HAL layer + * @param hight_period SCL high period + * @param low_period SCL low period + * + * @return None + */ +void i2c_hal_set_scl_timing(i2c_hal_context_t *hal, int hight_period, int low_period); + +/** + * @brief Configure the I2C master SCL frequency + * + * @param hal Context of the HAL layer + * @param src_clk The I2C Source clock frequency + * @param scl_freq The SCL frequency to be set + * + * @return None + */ +void i2c_hal_set_scl_freq(i2c_hal_context_t *hal, uint32_t src_clk, uint32_t scl_freq); + +/** + * @brief Clear the I2C interrupt status with the given mask + * + * @param hal Context of the HAL layer + * @param mask The interrupt bitmap needs to be clearned + * + * @return None + */ +void i2c_hal_clr_intsts_mask(i2c_hal_context_t *hal, uint32_t mask); + +/** + * @brief Enable the I2C interrupt with the given mask + * + * @param hal Context of the HAL layer + * @param mask The interrupt bitmap needs to be enabled + * + * @return None + */ +void i2c_hal_enable_intr_mask(i2c_hal_context_t *hal, uint32_t mask); + +/** + * @brief Disable the I2C interrupt with the given mask + * + * @param hal Context of the HAL layer + * @param mask The interrupt bitmap needs to be disabled + * + * @return None + */ +void i2c_hal_disable_intr_mask(i2c_hal_context_t *hal, uint32_t mask); + +/** + * @brief Configure the I2C memory access mode, FIFO mode or none FIFO mode + * + * @param hal Context of the HAL layer + * @param fifo_mode_en Set true to enable FIFO access mode, else set it false + * + * @return None + */ +void i2c_hal_set_fifo_mode(i2c_hal_context_t *hal, bool fifo_mode_en); + +/** + * @brief Configure the I2C timeout value + * + * @param hal Context of the HAL layer + * @param tout_val the timeout value to be set + * + * @return None + */ +void i2c_hal_set_tout(i2c_hal_context_t *hal, int tout_val); + +/** + * @brief Get the I2C time out configuration + * + * @param tout_val Pointer to accept the timeout configuration + * + * @return None + */ +void i2c_hal_get_tout(i2c_hal_context_t *hal, int *tout_val); + +/** + * @brief Configure the I2C slave address + * + * @param hal Context of the HAL layer + * @param slave_addr Slave address + * @param addr_10bit_en Set true to enable 10-bit slave address mode, Set false to enable 7-bit address mode + * + * @return None + */ +void i2c_hal_set_slave_addr(i2c_hal_context_t *hal, uint16_t slave_addr, bool addr_10bit_en); + +/** + * @brief Configure the I2C stop timing + * + * @param hal Context of the HAL layer + * @param stop_setup The stop condition setup period (in APB cycle) + * @param stop_hold The stop condition hold period (in APB cycle) + * + * @return None + */ +void i2c_hal_set_stop_timing(i2c_hal_context_t *hal, int stop_setup, int stop_hold); + +/** + * @brief Configure the I2C start timing + * + * @param hal Context of the HAL layer + * @param start_setup The start condition setup period (in APB cycle) + * @param start_hold The start condition hold period (in APB cycle) + * + * @return None + */ +void i2c_hal_set_start_timing(i2c_hal_context_t *hal, int start_setup, int start_hold); + +/** + * @brief Configure the I2C sda sample timing + * + * @param hal Context of the HAL layer + * @param sda_sample The SDA sample time (in APB cycle) + * @param sda_hold The SDA hold time (in APB cycle) + * + * @return None + */ +void i2c_hal_set_sda_timing(i2c_hal_context_t *hal, int sda_sample, int sda_hold); + +/** + * @brief Configure the I2C txfifo empty threshold value + * + * @param hal Context of the HAL layer. + * @param empty_thr TxFIFO empty threshold value + * + * @return None + */ +void i2c_hal_set_txfifo_empty_thr(i2c_hal_context_t *hal, uint8_t empty_thr); + +/** + * @brief Configure the I2C rxfifo full threshold value + * + * @param hal Context of the HAL layer + * @param full_thr RxFIFO full threshold value + * + * @return None + */ +void i2c_hal_set_rxfifo_full_thr(i2c_hal_context_t *hal, uint8_t full_thr); + +/** + * @brief Get the I2C interrupt status + * + * @param hal Context of the HAL layer + * @param mask Pointer to accept the interrupt status + * + * @return None + */ +void i2c_hal_get_intsts_mask(i2c_hal_context_t *hal, uint32_t *mask); + +/** + * @brief Check if the I2C bus is busy + * + * @param hal Context of the HAL layer + * + * @return True if the bus is busy, otherwise, fale will be returned + */ +bool i2c_hal_is_bus_busy(i2c_hal_context_t *hal); + +/** + * @brief Get the I2C sda sample timing configuration + * + * @param hal Context of the HAL layer + * @param sample_time Pointer to accept the SDA sample time + * @param hold_time Pointer to accept the SDA hold time + * + * @return None + */ +void i2c_hal_get_sda_timing(i2c_hal_context_t *hal, int *sample_time, int *hold_time); + +/** + * @brief Get the I2C stop timing configuration + * + * @param hal Context of the HAL layer + * @param setup_time Pointer to accept the stop condition setup period + * @param hold_time Pointer to accept the stop condition hold period + * + * @return None + */ +void i2c_hal_get_stop_timing(i2c_hal_context_t *hal, int *setup_time, int *hold_time); + +/** + * @brief Get the I2C scl timing configuration + * + * @param hal Context of the HAL layer + * @param high_period Pointer to accept the scl high period + * @param low_period Pointer to accept the scl low period + * + * @return None + */ +void i2c_hal_get_scl_timing(i2c_hal_context_t *hal, int *high_period, int *low_period); + +/** + * @brief Get the I2C start timing configuration + * + * @param hal Context of the HAL layer + * @param setup_time Pointer to accept the start condition setup period + * @param hold_time Pointer to accept the start condition hold period + * + * @return None + */ +void i2c_hal_get_start_timing(i2c_hal_context_t *hal, int *setup_time, int *hold_time); + +/** + * @brief Check if the I2C is master mode + * + * @param hal Context of the HAL layer + * + * @return True if in master mode, otherwise, false will be returned + */ +bool i2c_hal_is_master_mode(i2c_hal_context_t *hal); + +/** + * @brief Get the rxFIFO readable length + * + * @param hal Context of the HAL layer + * @param len Pointer to accept the rxFIFO readable length + * + * @return None + */ +void i2c_hal_get_rxfifo_cnt(i2c_hal_context_t *hal, uint32_t *len); + +/** + * @brief Set I2C bus timing with the given frequency + * + * @param hal Context of the HAL layer + * @param scl_freq The scl frequency to be set + * @param src_clk Source clock of I2C + * + * @return None + */ +void i2c_hal_set_bus_timing(i2c_hal_context_t *hal, int scl_freq, i2c_sclk_t src_clk); + +/** + * @brief Get I2C txFIFO writeable length + * + * @param hal Context of the HAL layer + * @param len Pointer to accept the txFIFO writeable length + * + * @return None + */ +void i2c_hal_get_txfifo_cnt(i2c_hal_context_t *hal, uint32_t *len); + +/** + * @brief Check if the I2C is master mode + * + * @param hal Context of the HAL layer + * @param tx_mode Pointer to accept the TX data mode + * @param rx_mode Pointer to accept the RX data mode + * + * @return None + */ +void i2c_hal_get_data_mode(i2c_hal_context_t *hal, i2c_trans_mode_t *tx_mode, i2c_trans_mode_t *rx_mode); + +/** + * @brief I2C hardware FSM reset + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_master_fsm_rst(i2c_hal_context_t *hal); + +/** + * @brief @brief Clear I2C bus + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_master_clr_bus(i2c_hal_context_t *hal); + +/** + * @brief Enable I2C slave TX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_enable_slave_tx_it(i2c_hal_context_t *hal); + +/** + * @brief Disable I2C slave TX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_disable_slave_tx_it(i2c_hal_context_t *hal); + +/** + * @brief Enable I2C slave RX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_enable_slave_rx_it(i2c_hal_context_t *hal); + +/** + * @brief Disable I2C slave RX interrupt + * + * @param hal Context of the HAL layer + * + * @return None + */ +void i2c_hal_disable_slave_rx_it(i2c_hal_context_t *hal); + +/** + * @brief I2C master handle tx interrupt event + * + * @param hal Context of the HAL layer + * @param event Pointer to accept the interrupt event + * + * @return None + */ +void i2c_hal_master_handle_tx_event(i2c_hal_context_t *hal, i2c_intr_event_t *event); + +/** + * @brief I2C master handle rx interrupt event + * + * @param hal Context of the HAL layer + * @param event Pointer to accept the interrupt event + * + * @return None + */ +void i2c_hal_master_handle_rx_event(i2c_hal_context_t *hal, i2c_intr_event_t *event); + +/** + * @brief I2C slave handle interrupt event + * + * @param hal Context of the HAL layer + * @param event Pointer to accept the interrupt event + * + * @return None + */ +void i2c_hal_slave_handle_event(i2c_hal_context_t *hal, i2c_intr_event_t *event); + +/** + * @brief Synchronize I2C status + * + * @param hal Context of the HAL layer + * + * @return None + * + */ +void i2c_hal_update_config(i2c_hal_context_t *hal); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/i2c_types.h b/tools/sdk/esp32c3/include/hal/include/hal/i2c_types.h new file mode 100644 index 00000000..3d5864dc --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/i2c_types.h @@ -0,0 +1,124 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/soc_caps.h" + +/** + * @brief I2C port number, can be I2C_NUM_0 ~ (I2C_NUM_MAX-1). + */ +typedef int i2c_port_t; + +typedef enum{ + I2C_MODE_SLAVE = 0, /*!< I2C slave mode */ + I2C_MODE_MASTER, /*!< I2C master mode */ + I2C_MODE_MAX, +} i2c_mode_t; + +typedef enum { + I2C_MASTER_WRITE = 0, /*!< I2C write data */ + I2C_MASTER_READ, /*!< I2C read data */ +} i2c_rw_t; + +typedef enum { + I2C_DATA_MODE_MSB_FIRST = 0, /*!< I2C data msb first */ + I2C_DATA_MODE_LSB_FIRST = 1, /*!< I2C data lsb first */ + I2C_DATA_MODE_MAX +} i2c_trans_mode_t; + +typedef enum { + I2C_ADDR_BIT_7 = 0, /*!< I2C 7bit address for slave mode */ + I2C_ADDR_BIT_10, /*!< I2C 10bit address for slave mode */ + I2C_ADDR_BIT_MAX, +} i2c_addr_mode_t; + +typedef enum { + I2C_MASTER_ACK = 0x0, /*!< I2C ack for each byte read */ + I2C_MASTER_NACK = 0x1, /*!< I2C nack for each byte read */ + I2C_MASTER_LAST_NACK = 0x2, /*!< I2C nack for the last byte*/ + I2C_MASTER_ACK_MAX, +} i2c_ack_type_t; + +/** + * @brief I2C clock source, sorting from smallest to largest, + * place them in order. + * This can be expanded in the future use. + */ +typedef enum { + I2C_SCLK_DEFAULT = 0, /*!< I2C source clock not selected*/ +#if SOC_I2C_SUPPORT_APB + I2C_SCLK_APB, /*!< I2C source clock from APB, 80M*/ +#endif +#if SOC_I2C_SUPPORT_XTAL + I2C_SCLK_XTAL, /*!< I2C source clock from XTAL, 40M */ +#endif +#if SOC_I2C_SUPPORT_RTC + I2C_SCLK_RTC, /*!< I2C source clock from 8M RTC, 8M */ +#endif +#if SOC_I2C_SUPPORT_REF_TICK + I2C_SCLK_REF_TICK, /*!< I2C source clock from REF_TICK, 1M */ +#endif + I2C_SCLK_MAX, +} i2c_sclk_t; + +// I2C clk flags for users to use, can be expanded in the future. +#define I2C_SCLK_SRC_FLAG_FOR_NOMAL (0) /*!< Any one clock source that is available for the specified frequency may be choosen*/ +#define I2C_SCLK_SRC_FLAG_AWARE_DFS (1 << 0) /*!< For REF tick clock, it won't change with APB.*/ +#define I2C_SCLK_SRC_FLAG_LIGHT_SLEEP (1 << 1) /*!< For light sleep mode.*/ + +/// Use the highest speed that is available for the clock source picked by clk_flags +#define I2C_CLK_FREQ_MAX (-1) + +/** + * @brief I2C initialization parameters + */ +typedef struct{ + i2c_mode_t mode; /*!< I2C mode */ + int sda_io_num; /*!< GPIO number for I2C sda signal */ + int scl_io_num; /*!< GPIO number for I2C scl signal */ + bool sda_pullup_en; /*!< Internal GPIO pull mode for I2C sda signal*/ + bool scl_pullup_en; /*!< Internal GPIO pull mode for I2C scl signal*/ + + union { + struct { + uint32_t clk_speed; /*!< I2C clock frequency for master mode, (no higher than 1MHz for now) */ + } master; /*!< I2C master config */ + struct { + uint8_t addr_10bit_en; /*!< I2C 10bit address mode enable for slave mode */ + uint16_t slave_addr; /*!< I2C address for slave mode */ + } slave; /*!< I2C slave config */ + }; + uint32_t clk_flags; /*!< Bitwise of ``I2C_SCLK_SRC_FLAG_**FOR_DFS**`` for clk source choice*/ +} i2c_config_t; + +#if CONFIG_IDF_TARGET_ESP32 +typedef enum{ + I2C_CMD_RESTART = 0, /*!dev, status) + +/** + * @brief Clear I2S interrupt status + * + * @param hal Context of the HAL layer + * @param mask interrupt status mask + */ +#define i2s_hal_clear_intr_status(hal, mask) i2s_ll_clear_intr_status((hal)->dev, mask) + +/** + * @brief Get I2S out eof des address + * + * @param hal Context of the HAL layer + * @param addr out eof des address + */ +#define i2s_hal_get_out_eof_des_addr(hal, addr) i2s_ll_get_out_eof_des_addr((hal)->dev, addr) + +/** + * @brief Get I2S in eof des address + * + * @param hal Context of the HAL layer + * @param addr in eof des address + */ +#define i2s_hal_get_in_eof_des_addr(hal, addr) i2s_ll_get_in_eof_des_addr((hal)->dev, addr) + +/** + * @brief Enable I2S rx interrupt + * + * @param hal Context of the HAL layer + */ +#define i2s_hal_enable_rx_intr(hal) i2s_ll_enable_rx_intr((hal)->dev) + +/** + * @brief Disable I2S rx interrupt + * + * @param hal Context of the HAL layer + */ +#define i2s_hal_disable_rx_intr(hal) i2s_ll_disable_rx_intr((hal)->dev) + +/** + * @brief Disable I2S tx interrupt + * + * @param hal Context of the HAL layer + */ +#define i2s_hal_disable_tx_intr(hal) i2s_ll_disable_tx_intr((hal)->dev) + +/** + * @brief Enable I2S tx interrupt + * + * @param hal Context of the HAL layer + */ +#define i2s_hal_enable_tx_intr(hal) i2s_ll_enable_tx_intr((hal)->dev) + +/** + * @brief Set I2S tx mode + * + * @param hal Context of the HAL layer + * @param ch i2s channel + * @param bits bits per sample + */ +void i2s_hal_set_tx_mode(i2s_hal_context_t *hal, i2s_channel_t ch, i2s_bits_per_sample_t bits); + +/** + * @brief Set I2S rx mode + * + * @param hal Context of the HAL layer + * @param ch i2s channel + * @param bits bits per sample + */ +void i2s_hal_set_rx_mode(i2s_hal_context_t *hal, i2s_channel_t ch, i2s_bits_per_sample_t bits); + +/** + * @brief Set I2S out link address + * + * @param hal Context of the HAL layer + * @param addr out link address + */ +#define i2s_hal_set_out_link_addr(hal, addr) i2s_ll_set_out_link_addr((hal)->dev, addr) + +/** + * @brief Set I2S out link address + * + * @param hal Context of the HAL layer + * @param addr out link address + */ +#define i2s_hal_set_out_link_addr(hal, addr) i2s_ll_set_out_link_addr((hal)->dev, addr) + +/** + * @brief Set I2S out link address + * + * @param hal Context of the HAL layer + * @param addr out link address + */ +#define i2s_hal_set_out_link_addr(hal, addr) i2s_ll_set_out_link_addr((hal)->dev, addr) + +/** + * @brief Set I2S in link + * + * @param hal Context of the HAL layer + * @param rx_eof_num in link eof num + * @param addr in link address + */ +void i2s_hal_set_in_link(i2s_hal_context_t *hal, uint32_t rx_eof_num, uint32_t addr); + +/** + * @brief Set I2S clk div + * + * @param hal Context of the HAL layer + * @param div_num i2s clkm div num + * @param div_a i2s clkm div a + * @param div_b i2s clkm div b + * @param tx_bck_div tx bck div num + * @param rx_bck_div rx bck div num + */ +void i2s_hal_set_clk_div(i2s_hal_context_t *hal, int div_num, int div_a, int div_b, int tx_bck_div, int rx_bck_div); + +/** + * @brief Set I2S clock sel + * + * @param hal Context of the HAL layer + * @param sel clock sel + */ +#define i2s_hal_set_clock_sel(hal, sel) i2s_ll_set_clk_sel((hal)->dev, sel) + +/** + * @brief Set I2S tx bits mod + * + * @param hal Context of the HAL layer + * @param bits bit width per sample. + */ +void i2s_hal_set_tx_bits_mod(i2s_hal_context_t *hal, i2s_bits_per_sample_t bits); + +/** + * @brief Set I2S rx bits mod + * + * @param hal Context of the HAL layer + * @param bits bit width per sample. + */ +void i2s_hal_set_rx_bits_mod(i2s_hal_context_t *hal, i2s_bits_per_sample_t bits); + +/** + * @brief Reset I2S TX & RX module, including DMA and FIFO + * + * @param hal Context of the HAL layer + */ +void i2s_hal_reset(i2s_hal_context_t *hal); + +/** + * @brief Start I2S tx + * + * @param hal Context of the HAL layer + */ +void i2s_hal_start_tx(i2s_hal_context_t *hal); + +/** + * @brief Start I2S rx + * + * @param hal Context of the HAL layer + */ +void i2s_hal_start_rx(i2s_hal_context_t *hal); + +/** + * @brief Stop I2S tx + * + * @param hal Context of the HAL layer + */ +void i2s_hal_stop_tx(i2s_hal_context_t *hal); + +/** + * @brief Stop I2S rx + * + * @param hal Context of the HAL layer + */ +void i2s_hal_stop_rx(i2s_hal_context_t *hal); + +/** + * @brief Config I2S param + * + * @param hal Context of the HAL layer + * @param i2s_config I2S configurations - see i2s_config_t struct + */ +void i2s_hal_config_param(i2s_hal_context_t *hal, const i2s_config_t *i2s_config); + +/** + * @brief Enable I2S sig loopback + * + * @param hal Context of the HAL layer + */ +#define i2s_hal_enable_sig_loopback(hal) i2s_ll_set_sig_loopback((hal)->dev, 1) + +/** + * @brief Enable I2S master mode + * + * @param hal Context of the HAL layer + */ +void i2s_hal_enable_master_mode(i2s_hal_context_t *hal); + +/** + * @brief Enable I2S slave mode + * + * @param hal Context of the HAL layer + */ +void i2s_hal_enable_slave_mode(i2s_hal_context_t *hal); + +/** + * @brief Init the I2S hal and set the I2S to the default configuration. This function should be called first before other hal layer function is called + * + * @param hal Context of the HAL layer + * @param i2s_num The uart port number, the max port number is (I2S_NUM_MAX -1) + */ +void i2s_hal_init(i2s_hal_context_t *hal, int i2s_num); + +#if SOC_I2S_SUPPORTS_PDM +/** + * @brief Set I2S tx pdm + * + * @param hal Context of the HAL layer + * @param fp tx pdm fp + * @param fs tx pdm fs + */ +void i2s_hal_tx_pdm_cfg(i2s_hal_context_t *hal, uint32_t fp, uint32_t fs); + +/** + * @brief Get I2S tx pdm + * + * @param hal Context of the HAL layer + * @param dsr rx pdm dsr + */ +void i2s_hal_rx_pdm_cfg(i2s_hal_context_t *hal, uint32_t dsr); + +/** + * @brief Get I2S tx pdm configuration + * + * @param hal Context of the HAL layer + * @param fp Pointer to receive tx PDM fp configuration + * @param fs Pointer to receive tx PDM fs configuration + */ +void i2s_hal_get_tx_pdm(i2s_hal_context_t *hal, uint32_t *fp, uint32_t *fs); + +/** + * @brief Get I2S rx pdm configuration + * + * @param hal Context of the HAL layer + * @param dsr rx pdm dsr + */ +void i2s_hal_get_rx_pdm(i2s_hal_context_t *hal, uint32_t *dsr); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/i2s_types.h b/tools/sdk/esp32c3/include/hal/include/hal/i2s_types.h new file mode 100644 index 00000000..2b41b1b4 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/i2s_types.h @@ -0,0 +1,204 @@ +// Copyright 2015-2020 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. + +#pragma once + +#include +#include +#include +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief I2S port number, the max port number is (I2S_NUM_MAX -1). + */ +typedef enum { + I2S_NUM_0 = 0, /*!< I2S port 0 */ +#if SOC_I2S_NUM > 1 + I2S_NUM_1 = 1, /*!< I2S port 1 */ +#endif + I2S_NUM_MAX, /*!< I2S port max */ +} i2s_port_t; + +/** + * @brief I2S bit width per sample. + * + */ +typedef enum { + I2S_BITS_PER_SAMPLE_8BIT = 8, /*!< I2S bits per sample: 8-bits*/ + I2S_BITS_PER_SAMPLE_16BIT = 16, /*!< I2S bits per sample: 16-bits*/ + I2S_BITS_PER_SAMPLE_24BIT = 24, /*!< I2S bits per sample: 24-bits*/ + I2S_BITS_PER_SAMPLE_32BIT = 32, /*!< I2S bits per sample: 32-bits*/ +} i2s_bits_per_sample_t; + +/** + * @brief I2S channel. + * + */ +typedef enum { + I2S_CHANNEL_MONO = 1, /*!< I2S 1 channel (mono)*/ + I2S_CHANNEL_STEREO = 2 /*!< I2S 2 channel (stereo)*/ +} i2s_channel_t; + +/** + * @brief I2S communication standard format + * + */ +typedef enum { + // In order to keep compatibility, remain the old definitions and introduce new definitions, + I2S_COMM_FORMAT_STAND_I2S = 0X01, /*!< I2S communication I2S Philips standard, data launch at second BCK*/ + I2S_COMM_FORMAT_STAND_MSB = 0X03, /*!< I2S communication MSB alignment standard, data launch at first BCK*/ + I2S_COMM_FORMAT_STAND_PCM_SHORT = 0x04, /*!< PCM Short standard, also known as DSP mode. The period of synchronization signal (WS) is 1 bck cycle.*/ + I2S_COMM_FORMAT_STAND_PCM_LONG = 0x0C, /*!< PCM Long standard. The period of synchronization signal (WS) is channel_bit*bck cycles.*/ + I2S_COMM_FORMAT_STAND_MAX, /*!< standard max*/ + + //old definition will be removed in the future. + I2S_COMM_FORMAT_I2S __attribute__((deprecated)) = 0x01, /*!< I2S communication format I2S, correspond to `I2S_COMM_FORMAT_STAND_I2S`*/ + I2S_COMM_FORMAT_I2S_MSB __attribute__((deprecated)) = 0x01, /*!< I2S format MSB, (I2S_COMM_FORMAT_I2S |I2S_COMM_FORMAT_I2S_MSB) correspond to `I2S_COMM_FORMAT_STAND_I2S`*/ + I2S_COMM_FORMAT_I2S_LSB __attribute__((deprecated)) = 0x02, /*!< I2S format LSB, (I2S_COMM_FORMAT_I2S |I2S_COMM_FORMAT_I2S_LSB) correspond to `I2S_COMM_FORMAT_STAND_MSB`*/ + I2S_COMM_FORMAT_PCM __attribute__((deprecated)) = 0x04, /*!< I2S communication format PCM, correspond to `I2S_COMM_FORMAT_STAND_PCM_SHORT`*/ + I2S_COMM_FORMAT_PCM_SHORT __attribute__((deprecated)) = 0x04, /*!< PCM Short, (I2S_COMM_FORMAT_PCM | I2S_COMM_FORMAT_PCM_SHORT) correspond to `I2S_COMM_FORMAT_STAND_PCM_SHORT`*/ + I2S_COMM_FORMAT_PCM_LONG __attribute__((deprecated)) = 0x08, /*!< PCM Long, (I2S_COMM_FORMAT_PCM | I2S_COMM_FORMAT_PCM_LONG) correspond to `I2S_COMM_FORMAT_STAND_PCM_LONG`*/ +} i2s_comm_format_t; + +/** + * @brief I2S channel format type + */ +typedef enum { + I2S_CHANNEL_FMT_RIGHT_LEFT = 0x00, + I2S_CHANNEL_FMT_ALL_RIGHT, + I2S_CHANNEL_FMT_ALL_LEFT, + I2S_CHANNEL_FMT_ONLY_RIGHT, + I2S_CHANNEL_FMT_ONLY_LEFT, +} i2s_channel_fmt_t; + +/** + * @brief I2S Mode, defaut is I2S_MODE_MASTER | I2S_MODE_TX + * + * @note PDM and built-in DAC functions are only supported on I2S0 for current ESP32 chip. + * + */ +typedef enum { + I2S_MODE_MASTER = 1, /*!< Master mode*/ + I2S_MODE_SLAVE = 2, /*!< Slave mode*/ + I2S_MODE_TX = 4, /*!< TX mode*/ + I2S_MODE_RX = 8, /*!< RX mode*/ +#if SOC_I2S_SUPPORTS_ADC_DAC + I2S_MODE_DAC_BUILT_IN = 16, /*!< Output I2S data to built-in DAC, no matter the data format is 16bit or 32 bit, the DAC module will only take the 8bits from MSB*/ + I2S_MODE_ADC_BUILT_IN = 32, /*!< Input I2S data from built-in ADC, each data can be 12-bit width at most*/ +#endif +#if SOC_I2S_SUPPORTS_PDM + I2S_MODE_PDM = 64, /*!< PDM mode*/ +#endif +} i2s_mode_t; + +/** + * @brief I2S source clock + * + */ +typedef enum { + I2S_CLK_D2CLK = 0, /*!< Clock from PLL_D2_CLK(160M)*/ + I2S_CLK_APLL, /*!< Clock from APLL*/ +} i2s_clock_src_t; + + +/** + * @brief I2S configuration parameters for i2s_param_config function + * + */ +typedef struct { + i2s_mode_t mode; /*!< I2S work mode*/ + int sample_rate; /*!< I2S sample rate*/ + i2s_bits_per_sample_t bits_per_sample; /*!< I2S bits per sample*/ + i2s_channel_fmt_t channel_format; /*!< I2S channel format */ + i2s_comm_format_t communication_format; /*!< I2S communication format */ + int intr_alloc_flags; /*!< Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info */ + int dma_buf_count; /*!< I2S DMA Buffer Count */ + int dma_buf_len; /*!< I2S DMA Buffer Length */ + bool use_apll; /*!< I2S using APLL as main I2S clock, enable it to get accurate clock */ + bool tx_desc_auto_clear; /*!< I2S auto clear tx descriptor if there is underflow condition (helps in avoiding noise in case of data unavailability) */ + int fixed_mclk; /*!< I2S using fixed MCLK output. If use_apll = true and fixed_mclk > 0, then the clock output for i2s is fixed and equal to the fixed_mclk value.*/ +} i2s_config_t; + +/** + * @brief I2S event types + * + */ +typedef enum { + I2S_EVENT_DMA_ERROR, + I2S_EVENT_TX_DONE, /*!< I2S DMA finish sent 1 buffer*/ + I2S_EVENT_RX_DONE, /*!< I2S DMA finish received 1 buffer*/ + I2S_EVENT_MAX, /*!< I2S event max index*/ +} i2s_event_type_t; + +/** + * @brief I2S DAC mode for i2s_set_dac_mode. + * + * @note PDM and built-in DAC functions are only supported on I2S0 for current ESP32 chip. + */ +typedef enum { + I2S_DAC_CHANNEL_DISABLE = 0, /*!< Disable I2S built-in DAC signals*/ + I2S_DAC_CHANNEL_RIGHT_EN = 1, /*!< Enable I2S built-in DAC right channel, maps to DAC channel 1 on GPIO25*/ + I2S_DAC_CHANNEL_LEFT_EN = 2, /*!< Enable I2S built-in DAC left channel, maps to DAC channel 2 on GPIO26*/ + I2S_DAC_CHANNEL_BOTH_EN = 0x3, /*!< Enable both of the I2S built-in DAC channels.*/ + I2S_DAC_CHANNEL_MAX = 0x4, /*!< I2S built-in DAC mode max index*/ +} i2s_dac_mode_t; + +/** + * @brief Event structure used in I2S event queue + * + */ +typedef struct { + i2s_event_type_t type; /*!< I2S event type */ + size_t size; /*!< I2S data size for I2S_DATA event*/ +} i2s_event_t; + +/** + * @brief I2S pin number for i2s_set_pin + * + */ +typedef struct { + int bck_io_num; /*!< BCK in out pin*/ + int ws_io_num; /*!< WS in out pin*/ + int data_out_num; /*!< DATA out pin*/ + int data_in_num; /*!< DATA in pin*/ +} i2s_pin_config_t; + +#if SOC_I2S_SUPPORTS_PDM +/** + * @brief I2S PDM RX downsample mode + */ +typedef enum { + I2S_PDM_DSR_8S = 0, /*!< downsampling number is 8 for PDM RX mode*/ + I2S_PDM_DSR_16S, /*!< downsampling number is 16 for PDM RX mode*/ + I2S_PDM_DSR_MAX, +} i2s_pdm_dsr_t; + +/** + * @brief PDM PCM convter enable/disable. + * + */ +typedef enum { + PDM_PCM_CONV_ENABLE, /*!< Enable PDM PCM convert*/ + PDM_PCM_CONV_DISABLE, /*!< Disable PDM PCM convert*/ +} pdm_pcm_conv_t; +#endif + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_hal.h new file mode 100644 index 00000000..a7c47e6a --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_hal.h @@ -0,0 +1,207 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include "hal/interrupt_controller_types.h" +#include "hal/interrupt_controller_ll.h" +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef SOC_CPU_HAS_FLEXIBLE_INTC +/** + * @brief Gets target platform interrupt descriptor table + * + * @return Address of interrupt descriptor table + */ +__attribute__((pure)) const int_desc_t *interrupt_controller_hal_desc_table(void); +#endif + +/** + * @brief Gets the interrupt type given an interrupt number. + * + * @param interrupt_number Interrupt number 0 to 31 + * @return interrupt type + */ +__attribute__((pure)) int_type_t interrupt_controller_hal_desc_type(int interrupt_number); + +/** + * @brief Gets the interrupt level given an interrupt number. + * + * @param interrupt_number Interrupt number 0 to 31 + * @return interrupt level bitmask + */ +__attribute__((pure)) int interrupt_controller_hal_desc_level(int interrupt_number); + +/** + * @brief Gets the cpu flags given the interrupt number and target cpu. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param cpu_number CPU number between 0 and SOC_CPU_CORES_NUM - 1 + * @return flags for that interrupt number + */ +__attribute__((pure)) int_desc_flag_t interrupt_controller_hal_desc_flags(int interrupt_number, int cpu_number); + +/** + * @brief Gets the interrupt type given an interrupt number. + * + * @param interrupt_number Interrupt number 0 to 31 + * @return interrupt type + */ +static inline int_type_t interrupt_controller_hal_get_type(int interrupt_number) +{ + return interrupt_controller_hal_desc_type(interrupt_number); +} + +/** + * @brief Gets the interrupt level given an interrupt number. + * + * @param interrupt_number Interrupt number 0 to 31 + * @return interrupt level bitmask + */ +static inline int interrupt_controller_hal_get_level(int interrupt_number) +{ + return interrupt_controller_hal_desc_level(interrupt_number); +} + +#ifdef SOC_CPU_HAS_FLEXIBLE_INTC +/** + * @brief Set the type of an interrupt in the controller. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param type interrupt type as edge or level triggered + */ +static inline void interrupt_controller_hal_set_int_type(int intr, int_type_t type) +{ + intr_cntrl_ll_set_int_type(intr, type); +} + +/** + * @brief Sets the interrupt level int the interrupt controller. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param level priority between 1 (lowest) to 7 (highest) + */ +static inline void interrupt_controller_hal_set_int_level(int intr, int level) +{ + intr_cntrl_ll_set_int_level(intr, level); +} +#endif + +/** + * @brief Gets the cpu flags given the interrupt number and target cpu. + * + * @param interrupt_number Interrupt number 0 to 31 + * @param cpu_number CPU number between 0 and SOC_CPU_CORES_NUM - 1 + * @return flags for that interrupt number + */ +static inline uint32_t interrupt_controller_hal_get_cpu_desc_flags(int interrupt_number, int cpu_number) +{ + return interrupt_controller_hal_desc_flags(interrupt_number, cpu_number); +} + +/** + * @brief enable interrupts specified by the mask + * + * @param mask bitmask of interrupts that needs to be enabled + */ +static inline void interrupt_controller_hal_enable_interrupts(uint32_t mask) +{ + intr_cntrl_ll_enable_interrupts(mask); +} + +/** + * @brief disable interrupts specified by the mask + * + * @param mask bitmask of interrupts that needs to be disabled + */ +static inline void interrupt_controller_hal_disable_interrupts(uint32_t mask) +{ + intr_cntrl_ll_disable_interrupts(mask); +} + +/** + * @brief checks if given interrupt number has a valid handler + * + * @param intr interrupt number ranged from 0 to 31 + * @param cpu cpu number ranged betweeen 0 to SOC_CPU_CORES_NUM - 1 + * @return true for valid handler, false otherwise + */ +static inline bool interrupt_controller_hal_has_handler(int intr, int cpu) +{ + return intr_cntrl_ll_has_handler(intr, cpu); +} + +/** + * @brief sets interrupt handler and optional argument of a given interrupt number + * + * @param intr interrupt number ranged from 0 to 31 + * @param handler handler invoked when an interrupt occurs + * @param arg optional argument to pass to the handler + */ +static inline void interrupt_controller_hal_set_int_handler(uint8_t intr, interrupt_handler_t handler, void *arg) +{ + intr_cntrl_ll_set_int_handler(intr, handler, arg); +} + +/** + * @brief Gets argument passed to handler of a given interrupt number + * + * @param intr interrupt number ranged from 0 to 31 + * + * @return argument used by handler of passed interrupt number + */ +static inline void * interrupt_controller_hal_get_int_handler_arg(uint8_t intr) +{ + return intr_cntrl_ll_get_int_handler_arg(intr); +} + +/** + * @brief Disables interrupts that are not located in iram + * + * @param newmask mask of interrupts needs to be disabled + * @return oldmask where to store old interrupts state + */ +static inline uint32_t interrupt_controller_hal_disable_int_mask(uint32_t newmask) +{ + return intr_cntrl_ll_disable_int_mask(newmask); +} + +/** + * @brief Enables interrupts that are not located in iram + * + * @param newmask mask of interrupts needs to be disabled + */ +static inline void interrupt_controller_hal_enable_int_mask(uint32_t newmask) +{ + intr_cntrl_ll_enable_int_mask(newmask); +} + +/** + * @brief Acknowledge an edge-trigger interrupt by clearing its pending flag + * + * @param intr interrupt number ranged from 0 to 31 + */ +static inline void interrupt_controller_hal_edge_int_acknowledge(int intr) +{ + intr_cntrl_ll_edge_int_acknowledge(intr); +} + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_types.h b/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_types.h new file mode 100644 index 00000000..528b0eb3 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/interrupt_controller_types.h @@ -0,0 +1,46 @@ +// Copyright 2020 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. + +#pragma once + +#include "soc/soc_caps.h" +#include "soc/soc.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + INTDESC_NORMAL=0, + INTDESC_RESVD, + INTDESC_SPECIAL, +} int_desc_flag_t; + +typedef enum { + INTTP_LEVEL=0, + INTTP_EDGE, + INTTP_NA, +} int_type_t; + +typedef struct { + int level; + int_type_t type; + int_desc_flag_t cpuflags[SOC_CPU_CORES_NUM]; +} int_desc_t; + +typedef void (*interrupt_handler_t)(void *arg); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/lcd_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/lcd_hal.h new file mode 100644 index 00000000..a6bcba16 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/lcd_hal.h @@ -0,0 +1,37 @@ +// Copyright 2021 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. + +/******************************************************************************* + * NOTICE + * The HAL is not public api, don't use in application code. + * See readme.md in soc/README.md + ******************************************************************************/ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/lcd_cam_struct.h" + +typedef struct { + lcd_cam_dev_t *dev; +} lcd_hal_context_t; + +void lcd_hal_init(lcd_hal_context_t *hal, int id); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/ledc_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/ledc_hal.h new file mode 100644 index 00000000..2afa5477 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/ledc_hal.h @@ -0,0 +1,388 @@ +// Copyright 2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for LEDC. +// There is no parameter check in the hal layer, so the caller must ensure the correctness of the parameters. + +#pragma once + +#include "hal/ledc_ll.h" +#include "hal/ledc_types.h" + +/** + * Context that should be maintained by both the driver and the HAL + */ +typedef struct { + ledc_dev_t *dev; + ledc_mode_t speed_mode; +} ledc_hal_context_t; + +/** + * @brief Set LEDC low speed timer clock + * + * @param hal Context of the HAL layer + * @param slow_clk_sel LEDC low speed timer clock source + * + * @return None + */ +#define ledc_hal_set_slow_clk_sel(hal, slow_clk_sel) ledc_ll_set_slow_clk_sel((hal)->dev, slow_clk_sel) + +/** + * @brief Get LEDC low speed timer clock + * + * @param hal Context of the HAL layer + * @param slow_clk_sel LEDC low speed timer clock source + * + * @return None + */ +#define ledc_hal_get_slow_clk_sel(hal, slow_clk_sel) ledc_ll_get_slow_clk_sel((hal)->dev, slow_clk_sel) + +/** + * @brief Update LEDC low speed timer + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +#define ledc_hal_ls_timer_update(hal, timer_sel) ledc_ll_ls_timer_update((hal)->dev, (hal)->speed_mode, timer_sel) + +/** + * @brief Reset LEDC timer + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +#define ledc_hal_timer_rst(hal, timer_sel) ledc_ll_timer_rst((hal)->dev, (hal)->speed_mode, timer_sel) + +/** + * @brief Pause LEDC timer + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +#define ledc_hal_timer_pause(hal, timer_sel) ledc_ll_timer_pause((hal)->dev, (hal)->speed_mode, timer_sel) + +/** + * @brief Resume LEDC timer + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +#define ledc_hal_timer_resume(hal, timer_sel) ledc_ll_timer_resume((hal)->dev, (hal)->speed_mode, timer_sel) + +/** + * @brief Set LEDC timer clock divider + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clock_divider Timer clock divide value, the timer clock is divided from the selected clock source + * + * @return None + */ +#define ledc_hal_set_clock_divider(hal, timer_sel, clock_divider) ledc_ll_set_clock_divider((hal)->dev, (hal)->speed_mode, timer_sel, clock_divider) + +/** + * @brief Get LEDC timer clock divider + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clock_divider Timer clock divide value, the timer clock is divided from the selected clock source + * + * @return None + */ +#define ledc_hal_get_clock_divider(hal, timer_sel, clock_divider) ledc_ll_get_clock_divider((hal)->dev, (hal)->speed_mode, timer_sel, clock_divider) + +/** + * @brief Set LEDC timer clock source + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clk_src Timer clock source + * + * @return None + */ +#define ledc_hal_set_clock_source(hal, timer_sel, clk_src) ledc_ll_set_clock_source((hal)->dev, (hal)->speed_mode, timer_sel, clk_src) + +/** + * @brief Get LEDC timer clock source + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clk_src Pointer to accept the timer clock source + * + * @return None + */ +#define ledc_hal_get_clock_source(hal, timer_sel, clk_src) ledc_ll_get_clock_source((hal)->dev, (hal)->speed_mode, timer_sel, clk_src) + +/** + * @brief Set LEDC duty resolution + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param duty_resolution Resolution of duty setting in number of bits. The range of duty values is [0, (2**duty_resolution)] + * + * @return None + */ +#define ledc_hal_set_duty_resolution(hal, timer_sel, duty_resolution) ledc_ll_set_duty_resolution((hal)->dev, (hal)->speed_mode, timer_sel, duty_resolution) + +/** + * @brief Get LEDC duty resolution + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param duty_resolution Pointer to accept the resolution of duty setting in number of bits. + * + * @return None + */ +#define ledc_hal_get_duty_resolution(hal, timer_sel, duty_resolution) ledc_ll_get_duty_resolution((hal)->dev, (hal)->speed_mode, timer_sel, duty_resolution) + +/** + * @brief Get LEDC max duty + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param max_duty Pointer to accept the max duty + * + * @return None + */ +#define ledc_hal_get_max_duty(hal, channel_num, max_duty) ledc_ll_get_max_duty((hal)->dev, (hal)->speed_mode, channel_num, max_duty) + +/** + * @brief Get LEDC hpoint value + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param hpoint_val Pointer to accept the LEDC hpoint value(max: 0xfffff) + * + * @return None + */ +#define ledc_hal_get_hpoint(hal, channel_num, hpoint_val) ledc_ll_get_hpoint((hal)->dev, (hal)->speed_mode, channel_num, hpoint_val) + +/** + * @brief Set LEDC the integer part of duty value + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_val LEDC duty value, the range of duty setting is [0, (2**duty_resolution)] + * + * @return None + */ +#define ledc_hal_set_duty_int_part(hal, channel_num, duty_val) ledc_ll_set_duty_int_part((hal)->dev, (hal)->speed_mode, channel_num, duty_val) + +/** + * @brief Set the output enable + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param sig_out_en The output enable status + * + * @return None + */ +#define ledc_hal_set_sig_out_en(hal, channel_num, sig_out_en) ledc_ll_set_sig_out_en((hal)->dev, (hal)->speed_mode, channel_num, sig_out_en) + +/** + * @brief Set the duty start + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_start The duty start + * + * @return None + */ +#define ledc_hal_set_duty_start(hal, channel_num, duty_start) ledc_ll_set_duty_start((hal)->dev, (hal)->speed_mode, channel_num, duty_start) + +/** + * @brief Set output idle level + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param idle_level The output idle level + * + * @return None + */ +#define ledc_hal_set_idle_level(hal, channel_num, idle_level) ledc_ll_set_idle_level((hal)->dev, (hal)->speed_mode, channel_num, idle_level) + +/** + * @brief Set fade end interrupt enable + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param fade_end_intr_en The fade end interrupt enable status + * + * @return None + */ +#define ledc_hal_set_fade_end_intr(hal, channel_num, fade_end_intr_en) ledc_ll_set_fade_end_intr((hal)->dev, (hal)->speed_mode, channel_num, fade_end_intr_en) + +/** + * @brief Set timer index of the specified channel + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * + * @return None + */ +#define ledc_hal_bind_channel_timer(hal, channel_num, timer_sel) ledc_ll_bind_channel_timer((hal)->dev, (hal)->speed_mode, channel_num, timer_sel) + +/** + * @brief Get timer index of the specified channel + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param timer_sel Pointer to accept the LEDC timer index + * + * @return None + */ +#define ledc_hal_get_channel_timer(hal, channel_num, timer_sel) ledc_ll_get_channel_timer((hal)->dev, (hal)->speed_mode, channel_num, timer_sel) + +/** + * @brief Init the LEDC hal. This function should be called first before other hal layer function is called + * + * @param hal Context of the HAL layer + * @param speed_mode speed_mode Select the LEDC speed_mode, high-speed mode and low-speed mod + * + * @return None + */ +void ledc_hal_init(ledc_hal_context_t *hal, ledc_mode_t speed_mode); + +/** + * @brief Update channel configure when select low speed mode + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * + * @return None + */ +void ledc_hal_ls_channel_update(ledc_hal_context_t *hal, ledc_channel_t channel_num); + +/** + * @brief Set LEDC hpoint value + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param hpoint_val LEDC hpoint value(max: 0xfffff) + * + * @return None + */ +void ledc_hal_set_hpoint(ledc_hal_context_t *hal, ledc_channel_t channel_num, uint32_t hpoint_val); + +/** + * @brief Get LEDC duty value + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_val Pointer to accept the LEDC duty value + * + * @return None + */ +void ledc_hal_get_duty(ledc_hal_context_t *hal, ledc_channel_t channel_num, uint32_t *duty_val); + +/** + * @brief Set LEDC duty change direction + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_direction LEDC duty change direction, increase or decrease + * + * @return None + */ +void ledc_hal_set_duty_direction(ledc_hal_context_t *hal, ledc_channel_t channel_num, ledc_duty_direction_t duty_direction); + +/** + * @brief Set the number of increased or decreased times + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_num The number of increased or decreased times + * + * @return None + */ +void ledc_hal_set_duty_num(ledc_hal_context_t *hal, ledc_channel_t channel_num, uint32_t duty_num); + +/** + * @brief Set the duty cycles of increase or decrease + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_cycle The duty cycles + * + * @return None + */ +void ledc_hal_set_duty_cycle(ledc_hal_context_t *hal, ledc_channel_t channel_num, uint32_t duty_cycle); + +/** + * @brief Set the step scale of increase or decrease + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param duty_scale The step scale + * + * @return None + */ +void ledc_hal_set_duty_scale(ledc_hal_context_t *hal, ledc_channel_t channel_num, uint32_t duty_scale); + +/** + * @brief Get interrupt status of the specified channel + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * @param intr_status Pointer to accept the interrupt status + * + * @return None + */ +void ledc_hal_get_fade_end_intr_status(ledc_hal_context_t *hal, uint32_t *intr_status); + +/** + * @brief Clear interrupt status of the specified channel + * + * @param hal Context of the HAL layer + * @param channel_num LEDC channel index (0-7), select from ledc_channel_t + * + * @return None + */ +void ledc_hal_clear_fade_end_intr_status(ledc_hal_context_t *hal, ledc_channel_t channel_num); + +/** + * @brief Get clock config of LEDC timer + * + * @param hal Context of the HAL layer + * @param timer_sel LEDC timer index (0-3), select from ledc_timer_t + * @param clk_cfg Pointer to accept clock config + * + * @return None + */ +void ledc_hal_get_clk_cfg(ledc_hal_context_t *hal, ledc_timer_t timer_sel, ledc_clk_cfg_t *clk_cfg); + +/** + * @brief Config low speed timer clock source with clock config + *s + * @param hal Context of the HAL layer + * @param clk_cfg clock config + * + * @return None + */ +void ledc_hal_set_slow_clk(ledc_hal_context_t *hal, ledc_clk_cfg_t clk_cfg); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/ledc_types.h b/tools/sdk/esp32c3/include/hal/include/hal/ledc_types.h new file mode 100644 index 00000000..fa05ef41 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/ledc_types.h @@ -0,0 +1,157 @@ +// Copyright 2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "soc/soc_caps.h" + +typedef enum { +#if SOC_LEDC_SUPPORT_HS_MODE + LEDC_HIGH_SPEED_MODE = 0, /*!< LEDC high speed speed_mode */ +#endif + LEDC_LOW_SPEED_MODE, /*!< LEDC low speed speed_mode */ + LEDC_SPEED_MODE_MAX, /*!< LEDC speed limit */ +} ledc_mode_t; + +typedef enum { + LEDC_INTR_DISABLE = 0, /*!< Disable LEDC interrupt */ + LEDC_INTR_FADE_END, /*!< Enable LEDC interrupt */ + LEDC_INTR_MAX, +} ledc_intr_type_t; + +typedef enum { + LEDC_DUTY_DIR_DECREASE = 0, /*!< LEDC duty decrease direction */ + LEDC_DUTY_DIR_INCREASE = 1, /*!< LEDC duty increase direction */ + LEDC_DUTY_DIR_MAX, +} ledc_duty_direction_t; + +typedef enum { + LEDC_SLOW_CLK_RTC8M = 0, /*!< LEDC low speed timer clock source is 8MHz RTC clock*/ + LEDC_SLOW_CLK_APB, /*!< LEDC low speed timer clock source is 80MHz APB clock*/ +#if SOC_LEDC_SUPPORT_XTAL_CLOCK + LEDC_SLOW_CLK_XTAL, /*!< LEDC low speed timer clock source XTAL clock*/ +#endif +} ledc_slow_clk_sel_t; + +typedef enum { + LEDC_AUTO_CLK = 0, /*!< The driver will automatically select the source clock(REF_TICK or APB) based on the giving resolution and duty parameter when init the timer*/ + LEDC_USE_REF_TICK, /*!< LEDC timer select REF_TICK clock as source clock*/ + LEDC_USE_APB_CLK, /*!< LEDC timer select APB clock as source clock*/ + LEDC_USE_RTC8M_CLK, /*!< LEDC timer select RTC8M_CLK as source clock. Only for low speed channels and this parameter must be the same for all low speed channels*/ +#if SOC_LEDC_SUPPORT_XTAL_CLOCK + LEDC_USE_XTAL_CLK, /*!< LEDC timer select XTAL clock as source clock*/ +#endif +} ledc_clk_cfg_t; + +/* Note: Setting numeric values to match ledc_clk_cfg_t values are a hack to avoid collision with + LEDC_AUTO_CLK in the driver, as these enums have very similar names and user may pass + one of these by mistake. */ +typedef enum { + LEDC_REF_TICK = LEDC_USE_REF_TICK, /*!< LEDC timer clock divided from reference tick (1Mhz) */ + LEDC_APB_CLK = LEDC_USE_APB_CLK, /*!< LEDC timer clock divided from APB clock (80Mhz) */ +} ledc_clk_src_t; + + +typedef enum { + LEDC_TIMER_0 = 0, /*!< LEDC timer 0 */ + LEDC_TIMER_1, /*!< LEDC timer 1 */ + LEDC_TIMER_2, /*!< LEDC timer 2 */ + LEDC_TIMER_3, /*!< LEDC timer 3 */ + LEDC_TIMER_MAX, +} ledc_timer_t; + +typedef enum { + LEDC_CHANNEL_0 = 0, /*!< LEDC channel 0 */ + LEDC_CHANNEL_1, /*!< LEDC channel 1 */ + LEDC_CHANNEL_2, /*!< LEDC channel 2 */ + LEDC_CHANNEL_3, /*!< LEDC channel 3 */ + LEDC_CHANNEL_4, /*!< LEDC channel 4 */ + LEDC_CHANNEL_5, /*!< LEDC channel 5 */ +#if SOC_LEDC_CHANNEL_NUM > 6 + LEDC_CHANNEL_6, /*!< LEDC channel 6 */ + LEDC_CHANNEL_7, /*!< LEDC channel 7 */ +#endif + LEDC_CHANNEL_MAX, +} ledc_channel_t; + +typedef enum { + LEDC_TIMER_1_BIT = 1, /*!< LEDC PWM duty resolution of 1 bits */ + LEDC_TIMER_2_BIT, /*!< LEDC PWM duty resolution of 2 bits */ + LEDC_TIMER_3_BIT, /*!< LEDC PWM duty resolution of 3 bits */ + LEDC_TIMER_4_BIT, /*!< LEDC PWM duty resolution of 4 bits */ + LEDC_TIMER_5_BIT, /*!< LEDC PWM duty resolution of 5 bits */ + LEDC_TIMER_6_BIT, /*!< LEDC PWM duty resolution of 6 bits */ + LEDC_TIMER_7_BIT, /*!< LEDC PWM duty resolution of 7 bits */ + LEDC_TIMER_8_BIT, /*!< LEDC PWM duty resolution of 8 bits */ + LEDC_TIMER_9_BIT, /*!< LEDC PWM duty resolution of 9 bits */ + LEDC_TIMER_10_BIT, /*!< LEDC PWM duty resolution of 10 bits */ + LEDC_TIMER_11_BIT, /*!< LEDC PWM duty resolution of 11 bits */ + LEDC_TIMER_12_BIT, /*!< LEDC PWM duty resolution of 12 bits */ + LEDC_TIMER_13_BIT, /*!< LEDC PWM duty resolution of 13 bits */ + LEDC_TIMER_14_BIT, /*!< LEDC PWM duty resolution of 14 bits */ +#if SOC_LEDC_TIMER_BIT_WIDE_NUM > 14 + LEDC_TIMER_15_BIT, /*!< LEDC PWM duty resolution of 15 bits */ + LEDC_TIMER_16_BIT, /*!< LEDC PWM duty resolution of 16 bits */ + LEDC_TIMER_17_BIT, /*!< LEDC PWM duty resolution of 17 bits */ + LEDC_TIMER_18_BIT, /*!< LEDC PWM duty resolution of 18 bits */ + LEDC_TIMER_19_BIT, /*!< LEDC PWM duty resolution of 19 bits */ + LEDC_TIMER_20_BIT, /*!< LEDC PWM duty resolution of 20 bits */ +#endif + LEDC_TIMER_BIT_MAX, +} ledc_timer_bit_t; + +typedef enum { + LEDC_FADE_NO_WAIT = 0, /*!< LEDC fade function will return immediately */ + LEDC_FADE_WAIT_DONE, /*!< LEDC fade function will block until fading to the target duty */ + LEDC_FADE_MAX, +} ledc_fade_mode_t; + +/** + * @brief Configuration parameters of LEDC channel for ledc_channel_config function + */ +typedef struct { + int gpio_num; /*!< the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 */ + ledc_mode_t speed_mode; /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */ + ledc_channel_t channel; /*!< LEDC channel (0 - 7) */ + ledc_intr_type_t intr_type; /*!< configure interrupt, Fade interrupt enable or Fade interrupt disable */ + ledc_timer_t timer_sel; /*!< Select the timer source of channel (0 - 3) */ + uint32_t duty; /*!< LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)] */ + int hpoint; /*!< LEDC channel hpoint value, the max value is 0xfffff */ +} ledc_channel_config_t; + +/** + * @brief Configuration parameters of LEDC Timer timer for ledc_timer_config function + */ +typedef struct { + ledc_mode_t speed_mode; /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */ + union { + ledc_timer_bit_t duty_resolution; /*!< LEDC channel duty resolution */ + ledc_timer_bit_t bit_num __attribute__((deprecated)); /*!< Deprecated in ESP-IDF 3.0. This is an alias to 'duty_resolution' for backward compatibility with ESP-IDF 2.1 */ + }; + ledc_timer_t timer_num; /*!< The timer source of channel (0 - 3) */ + uint32_t freq_hz; /*!< LEDC timer frequency (Hz) */ + ledc_clk_cfg_t clk_cfg; /*!< Configure LEDC source clock. + For low speed channels and high speed channels, you can specify the source clock using LEDC_USE_REF_TICK, LEDC_USE_APB_CLK or LEDC_AUTO_CLK. + For low speed channels, you can also specify the source clock using LEDC_USE_RTC8M_CLK, in this case, all low speed channel's source clock must be RTC8M_CLK*/ +} ledc_timer_config_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_hal.h new file mode 100644 index 00000000..cfe0ba3d --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_hal.h @@ -0,0 +1,328 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for MCPWM (common part) + +/* + * MCPWM HAL usages: + * + * Initialization: + * 1. Fill the parameters in `mcpwm_hal_context_t`. + * 2. Call `mcpwm_hal_init` to initialize the context. + * 3. Call `mcpwm_hal_hw_init` to initialize the hardware. + * + * Basic PWM: + * 1. Update parameters for the timers, comparators and generators. + * 2. Call `mcpwm_hal_timer_update_basic` to update the timer used. + * 3. Call `mcpwm_hal_operator_update_basic` to update all the parameters of a operator. + * + * Alternatively, if only the comparator is updated (duty rate), call + * `mcpwm_hal_operator_update_comparator` to update the comparator parameters; if only the + * generator is updated (output style), call `mcpwm_hal_operator_update_generator` to update the + * generator parameters. + * + * 4. At any time, call `mcpwm_hal_timer_start` to start the timer (so that PWM output will toggle + * according to settings), or call `mcpwm_hal_timer_stop` to stop the timer (so that the PWM output + * will be kept as called). + * + * Timer settings: + * - Sync: Call `mcpwm_hal_timer_enable_sync` to enable the sync for the timer, and call + * `mcpwm_hal_timer_disable_sync` to disable it. + * + * Operator settings: + * - Carrier: Call `mcpwm_hal_operator_enable_carrier` to enable carrier for an operator, and call + * `mcpwm_hal_operator_disable_carrier` to disable it. + * + * - Deadzone: Call `mcpwm_hal_operator_update_deadzone` to update settings of deadzone for an operator. + * + * Fault handling settings: + * 1. Call `mcpwm_hal_fault_init` to initialize an fault signal to be detected. + * 2. Call `mcpwm_hal_operator_update_fault` to update the behavior of an operator when fault is + * detected. + * 3. If the operator selects oneshot mode to handle the fault event, call + * `mcpwm_hal_fault_oneshot_clear` to clear that fault event after the fault is handled properly. + * 4. Call `mcpwm_hal_fault_disable` to deinitialize the fault signal when it's no longer used. + * + * Capture: + * 1. Call `mcpwm_hal_capture_enable` to enable the capture for one capture signal. + * 2. Call `mcpwm_hal_capture_get_result` to get the last captured result. + * 3. Call `mcpwm_hal_capture_disable` to disable the capture for a signal. + */ + + +#pragma once + +#include +#include "hal/mcpwm_ll.h" + +#define MCPWM_BASE_CLK (2 * APB_CLK_FREQ) //2*APB_CLK_FREQ 160Mhz + +/// Configuration of HAL that used only once. +typedef struct { + int host_id; ///< Which MCPWM peripheral to use, 0-1. +} mcpwm_hal_init_config_t; + +/// Configuration of each generator (output of operator) +typedef struct { + mcpwm_duty_type_t duty_type; ///< How the generator output + int comparator; ///< for mode `MCPWM_DUTY_MODE_*`, which comparator it refers to. +} mcpwm_hal_generator_config_t; + +/// Configuration of each operator +typedef struct { + mcpwm_hal_generator_config_t gen[SOC_MCPWM_GENERATORS_PER_OPERATOR]; ///< Configuration of the generators + float duty[SOC_MCPWM_COMPARATORS_PER_OPERATOR]; ///< Duty rate for each comparator, 10 means 10%. + int timer; ///< The timer this operator is using +} mcpwm_hal_operator_config_t; + +/// Configuration of each timer +typedef struct { + uint32_t timer_prescale; ///< The prescale from the MCPWM main clock to the timer clock, TIMER_FREQ=(MCPWM_FREQ/(timer_prescale+1)) + uint32_t freq; ///< Frequency desired, will be updated to actual value after the `mcpwm_hal_timer_update_freq` is called. + mcpwm_counter_type_t count_mode; ///< Counting mode +} mcpwm_hal_timer_config_t; + +typedef struct { + mcpwm_dev_t *dev; ///< Beginning address of the MCPWM peripheral registers. Call `mcpwm_hal_init` to initialize it. + uint32_t prescale; ///< Prescale from the 160M clock to MCPWM main clock. + mcpwm_hal_timer_config_t timer[SOC_MCPWM_TIMERS_PER_GROUP]; ///< Configuration of the timers + mcpwm_hal_operator_config_t op[SOC_MCPWM_OPERATORS_PER_GROUP]; ///< Configuration of the operators +} mcpwm_hal_context_t; + +/// Configuration of the carrier +typedef struct { + bool inverted; ///< Whether to invert the output + uint8_t duty; ///< Duty of the carrier, 0-7. Duty rate = duty/8. + uint8_t oneshot_pulse_width; ///< oneshot pulse width, in carrier periods. 0 to disable. 0-15. + uint32_t period; ///< Prescale from the MCPWM main clock to the carrier clock. CARRIER_FREQ=(MCPWM_FREQ/(period+1)/8.) +} mcpwm_hal_carrier_conf_t; + +/// Configuration of the deadzone +typedef struct { + mcpwm_deadtime_type_t mode; ///< Deadzone mode, `MCPWM_DEADTIME_BYPASS` to disable. + uint32_t fed; ///< Delay on falling edge. By MCPWM main clock. + uint32_t red; ///< Delay on rising edge. By MCPWM main clock. +} mcpwm_hal_deadzone_conf_t; + +/// Configuration of the fault handling for each operator +typedef struct { + uint32_t cbc_enabled_mask; ///< Whether the cycle-by-cycle fault handling is enabled on each fault signal. BIT(n) stands for signal n. + uint32_t ost_enabled_mask; ///< Whether the oneshot fault handling is enabled on each on each fault signal. BIT(n) stands for signal n. + mcpwm_output_action_t action_on_fault[SOC_MCPWM_GENERATORS_PER_OPERATOR]; ///< Action to perform on each generator when any one of the fault signal triggers. +} mcpwm_hal_fault_conf_t; + +/// Configuration of the synchronization of each clock +typedef struct { + mcpwm_sync_signal_t sync_sig; ///< Sync signal to use + uint32_t reload_permillage; ///< Reload permillage when the sync is triggered. 100 means the timer will be reload to (period * 100)/1000=10% period value. +} mcpwm_hal_sync_config_t; + +/// Configuration of the capture feature on each capture signal +typedef struct { + mcpwm_capture_on_edge_t cap_edge; ///< Whether the edges is captured, bitwise. + uint32_t prescale; ///< Prescale of the input signal. +} mcpwm_hal_capture_config_t; + +/** + * @brief Initialize the internal state of the HAL. Call after settings are set and before other functions are called. + * + * @note Since There are several individual parts (timers + operators, captures), this funciton is + * allowed to called several times. + * + * @param hal Context of the HAL layer. + * @param init_config Configuration for the HAL to be used only once. + */ +void mcpwm_hal_init(mcpwm_hal_context_t *hal, const mcpwm_hal_init_config_t *init_config); + +/** + * @brief Initialize the hardware, call after `mcpwm_hal_init` and before other functions. + * + * @param hal Context of the HAL layer. + */ +void mcpwm_hal_hw_init(mcpwm_hal_context_t *hal); + +/** + * @brief Start a timer + * + * @param hal Context of the HAL layer. + * @param timer Timer to start, 0-2. + */ +void mcpwm_hal_timer_start(mcpwm_hal_context_t *hal, int timer); + +/** + * @brief Stop a timer. + * + * @param hal Context of the HAL layer. + * @param timer Timer to stop, 0-2. + */ +void mcpwm_hal_timer_stop(mcpwm_hal_context_t *hal, int timer); + +/** + * @brief Update the basic parameters of a timer. + * + * @note This will influence the duty rate and count mode of each operator relies on this timer. + * Call `mcpwm_hal_operator_update_basic` for each of the operator that relies on this timer after + * to update the duty rate and generator output. + * + * @param hal Context of the HAL layer. + * @param timer Timer to update, 0-2. + */ +void mcpwm_hal_timer_update_basic(mcpwm_hal_context_t *hal, int timer); + +/** + * @brief Start the synchronization for a timer. + * + * @param hal Context of the HAL layer. + * @param timer Timer to enable, 0-2. + * @param sync_conf Configuration of the sync operation. + */ +void mcpwm_hal_timer_enable_sync(mcpwm_hal_context_t *hal, int timer, const mcpwm_hal_sync_config_t *sync_conf); + +/** + * @brief Stop the synchronization for a timer. + * + * @param hal Context of the HAL layer. + * @param timer Timer to disable sync, 0-2. + */ +void mcpwm_hal_timer_disable_sync(mcpwm_hal_context_t *hal, int timer); + +/** + * @brief Update the basic settings (duty, output mode) for an operator. + * + * Will call `mcpwm_hal_operator_update_comparator` and `mcpwm_hal_operator_update_generator` + * recursively to update each of their duty and output mode. + * + * @param hal Context of the HAL layer. + * @param op Operator to update, 0-2. + */ +void mcpwm_hal_operator_update_basic(mcpwm_hal_context_t *hal, int op); + +/** + * @brief Update a comparator (duty) for an operator. + * + * @param hal Context of the HAL layer. + * @param op Operator to update, 0-2. + * @param cmp Comparator to update, 0-1. + */ +void mcpwm_hal_operator_update_comparator(mcpwm_hal_context_t *hal, int op, int cmp); + +/** + * @brief Update a generator (output mode) for an operator. + * + * @param hal Context of the HAL layer. + * @param op Operator to update, 0-2. + * @param cmp Comparator to update, 0-1. + */ +void mcpwm_hal_operator_update_generator(mcpwm_hal_context_t *hal, int op, int gen_num); + +/** + * @brief Enable the carrier for an operator. + * + * @param hal Context of the HAL layer. + * @param op Operator to enable carrier, 0-2. + * @param carrier_conf Configuration of the carrier. + */ +void mcpwm_hal_operator_enable_carrier(mcpwm_hal_context_t *hal, int op, const mcpwm_hal_carrier_conf_t *carrier_conf); + +/** + * @brief Disable the carrier for an operator. + * + * @param hal Context of the HAL layer. + * @param op Operator to disable carrier, 0-2. + */ +void mcpwm_hal_operator_disable_carrier(mcpwm_hal_context_t *hal, int op); + +/** + * @brief Update the deadzone for an operator. + * + * @param hal Context of the HAL layer. + * @param op Operator to update the deadzone, 0-2. + * @param deadzone Configuration of the deadzone. Set member `mode` to `MCPWM_DEADTIME_BYPASS` will bypass the deadzone. + */ +void mcpwm_hal_operator_update_deadzone(mcpwm_hal_context_t *hal, int op, const mcpwm_hal_deadzone_conf_t *deadzone); + +/** + * @brief Enable one of the fault signal. + * + * @param hal Context of the HAL layer. + * @param fault_sig The signal to enable, 0-2. + * @param level The active level for the fault signal, true for high and false for low. + */ +void mcpwm_hal_fault_init(mcpwm_hal_context_t *hal, int fault_sig, bool level); + +/** + * @brief Configure how the operator behave to the fault signals. + * + * Call after the fault signal is enabled by `mcpwm_hal_fault_init`. + * + * @param hal Context of the HAL layer. + * @param op Operator to configure, 0-2. + * @param fault_conf Configuration of the behavior of the operator when fault. Clear member `cbc_enabled_mask` and `ost_enabled_mask` will disable the fault detection of this operator. + */ +void mcpwm_hal_operator_update_fault(mcpwm_hal_context_t *hal, int op, const mcpwm_hal_fault_conf_t *fault_conf); + +/** + * @brief Clear the oneshot fault status for an operator. + * + * @param hal Context of the HAL layer. + * @param op The operator to clear oneshot fault status, 0-2. + */ +void mcpwm_hal_fault_oneshot_clear(mcpwm_hal_context_t *hal, int op); + +/** + * @brief Disable one of the fault signal. + * + * @param hal Context of the HAL layer. + * @param fault_sig The fault signal to disable, 0-2. + */ +void mcpwm_hal_fault_disable(mcpwm_hal_context_t *hal, int fault_sig); + +/** + * @brief Enable one of the capture signal. + * + * @param hal Context of the HAL layer. + * @param cap_sig Capture signal to enable, 0-2. + * @param conf Configuration on how to capture the signal. + */ +void mcpwm_hal_capture_enable(mcpwm_hal_context_t *hal, int cap_sig, const mcpwm_hal_capture_config_t *conf); + +/** + * @brief Get the capture result. + * + * @note The output value will always be updated with the register value, no matter event triggered or not. + * + * @param hal Context of the HAL layer. + * @param cap_sig Signal to get capture result, 0-2. + * @param out_count Output of the captured counter. + * @param out_edge Output of the captured edge. + * @return + * - ESP_OK: if a signal is captured + * - ESP_ERR_NOT_FOUND: if no capture event happened. + */ +esp_err_t mcpwm_hal_capture_get_result(mcpwm_hal_context_t *hal, int cap_sig, uint32_t *out_count, + mcpwm_capture_on_edge_t *out_edge); + +/** + * @brief Disable one of the capture signal. + * + * @param hal Context of the HAL layer. + * @param cap_sig The signal to capture, 0-2. + */ +void mcpwm_hal_capture_disable(mcpwm_hal_context_t *hal, int cap_sig); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_types.h b/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_types.h new file mode 100644 index 00000000..aac08da0 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/mcpwm_types.h @@ -0,0 +1,87 @@ +// Copyright 2015-2019 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. + +#pragma once + +/// Interrupts for MCPWM +typedef enum { + MCPWM_LL_INTR_CAP0 = BIT(27), ///< Capture 0 happened + MCPWM_LL_INTR_CAP1 = BIT(28), ///< Capture 1 happened + MCPWM_LL_INTR_CAP2 = BIT(29), ///< Capture 2 happened +} mcpwm_intr_t; + +/** + * @brief Select type of MCPWM counter + */ +typedef enum { + MCPWM_UP_COUNTER = 1, /*! + +#include "esp_err.h" + +#include "hal/mpu_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Specify the type of access allowed on a memory region. + * + * @param id index to the region table; on targets not SOC_MPU_CONFIGURABLE_REGIONS_SUPPORTED, + * the region divisions is predefined in hardware which is likely reflected in LL implementation. + * @param access type of access allowed + */ +void mpu_hal_set_region_access(int id, mpu_access_t access); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/mpu_types.h b/tools/sdk/esp32c3/include/hal/include/hal/mpu_types.h new file mode 100644 index 00000000..cc7da62a --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/mpu_types.h @@ -0,0 +1,34 @@ +// Copyright 2020 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. +#pragma once + +#include +#include "soc/soc_caps.h" + +#if SOC_MPU_CONFIGURABLE_REGIONS_SUPPORTED +typedef void** mpu_region_table_t; +#endif + +typedef enum { + MPU_REGION_ILLEGAL, +#if SOC_MPU_REGION_RO_SUPPORTED + MPU_REGION_RO, // read-only +#endif +#if SOC_MPU_REGION_WO_SUPPORTED + MPU_REGION_WO, // write-only +#endif + MPU_REGION_RW, // read-write + MPU_REGION_X, // executable + MPU_REGION_RWX // read-write-executable +} mpu_access_t; diff --git a/tools/sdk/esp32c3/include/hal/include/hal/pcnt_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/pcnt_hal.h new file mode 100644 index 00000000..8d2253e4 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/pcnt_hal.h @@ -0,0 +1,223 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for PCNT. +// There is no parameter check in the hal layer, so the caller must ensure the correctness of the parameters. + +#pragma once + +#include +#include "soc/pcnt_periph.h" +#include "hal/pcnt_types.h" +#include "hal/pcnt_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Context that should be maintained by both the driver and the HAL + */ + +typedef struct { + pcnt_dev_t *dev; +} pcnt_hal_context_t; + +/** + * @brief Set PCNT counter mode + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param channel PCNT channel number + * @param pos_mode Counter mode when detecting positive edge + * @param neg_mode Counter mode when detecting negative edge + * @param hctrl_mode Counter mode when control signal is high level + * @param lctrl_mode Counter mode when control signal is low level + */ +#define pcnt_hal_set_mode(hal, unit, channel, pos_mode, neg_mode, hctrl_mode, lctrl_mode) pcnt_ll_set_mode((hal)->dev, unit, channel, pos_mode, neg_mode, hctrl_mode, lctrl_mode) + +/** + * @brief Get pulse counter value + * + * @param hal Context of the HAL layer + * @param unit Pulse Counter unit number + * @param count Pointer to accept counter value + */ +#define pcnt_hal_get_counter_value(hal, unit, count) pcnt_ll_get_counter_value((hal)->dev, unit, count) + +/** + * @brief Pause PCNT counter of PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + */ +#define pcnt_hal_counter_pause(hal, unit) pcnt_ll_counter_pause((hal)->dev, unit) + +/** + * @brief Resume counting for PCNT counter + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number, select from unit_t + */ +#define pcnt_hal_counter_resume(hal, unit) pcnt_ll_counter_resume((hal)->dev, unit) + +/** + * @brief Clear and reset PCNT counter value to zero + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number, select from unit_t + */ +#define pcnt_hal_counter_clear(hal, unit) pcnt_ll_counter_clear((hal)->dev, unit) + +/** + * @brief Enable PCNT interrupt for PCNT unit + * @note + * Each Pulse counter unit has five watch point events that share the same interrupt. + * Configure events with pcnt_event_enable() and pcnt_event_disable() + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + */ +#define pcnt_hal_intr_enable(hal, unit) pcnt_ll_intr_enable((hal)->dev, unit) + +/** + * @brief Disable PCNT interrupt for PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + */ +#define pcnt_hal_intr_disable(hal, unit) pcnt_ll_intr_disable((hal)->dev, unit) + +/** + * @brief Get PCNT interrupt status + * + * @param hal Context of the HAL layer + * @param mask The interrupt status mask to be cleared. Pointer to accept value interrupt status mask. + */ +#define pcnt_hal_get_intr_status(hal, mask) pcnt_ll_get_intr_status((hal)->dev, mask) + +/** + * @brief Clear PCNT interrupt status + * + * @param hal Context of the HAL layer + * @param mask The interrupt status mask to be cleared. + */ +#define pcnt_hal_clear_intr_status(hal, mask) pcnt_ll_clear_intr_status((hal)->dev, mask) + +/** + * @brief Enable PCNT event of PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param evt_type Watch point event type. + * All enabled events share the same interrupt (one interrupt per pulse counter unit). + */ +#define pcnt_hal_event_enable(hal, unit, evt_type) pcnt_ll_event_enable((hal)->dev, unit, evt_type) + +/** + * @brief Disable PCNT event of PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param evt_type Watch point event type. + * All enabled events share the same interrupt (one interrupt per pulse counter unit). + */ +#define pcnt_hal_event_disable(hal, unit, evt_type) pcnt_ll_event_disable((hal)->dev, unit, evt_type) + +/** + * @brief Set PCNT event value of PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param evt_type Watch point event type. + * All enabled events share the same interrupt (one interrupt per pulse counter unit). + * + * @param value Counter value for PCNT event + */ +#define pcnt_hal_set_event_value(hal, unit, evt_type, value) pcnt_ll_set_event_value((hal)->dev, unit, evt_type, value) + +/** + * @brief Get PCNT event value of PCNT unit + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param evt_type Watch point event type. + * All enabled events share the same interrupt (one interrupt per pulse counter unit). + * @param value Pointer to accept counter value for PCNT event + */ +#define pcnt_hal_get_event_value(hal, unit, evt_type, value) pcnt_ll_get_event_value((hal)->dev, unit, evt_type, value) + +/** + * @brief Get PCNT event status + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @return event status word + */ +#define pcnt_hal_get_event_status(hal, unit) pcnt_ll_get_event_status((hal)->dev, unit) + +/** + * @brief Set PCNT filter value + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param filter_val PCNT signal filter value, counter in APB_CLK cycles. + * Any pulses lasting shorter than this will be ignored when the filter is enabled. + * @note + * filter_val is a 10-bit value, so the maximum filter_val should be limited to 1023. + */ +#define pcnt_hal_set_filter_value(hal, unit, filter_val) pcnt_ll_set_filter_value((hal)->dev, unit, filter_val) + +/** + * @brief Get PCNT filter value + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + * @param filter_val Pointer to accept PCNT filter value. + */ +#define pcnt_hal_get_filter_value(hal, unit, filter_val) pcnt_ll_get_filter_value((hal)->dev, unit, filter_val) + +/** + * @brief Enable PCNT input filter + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + */ +#define pcnt_hal_filter_enable(hal, unit) pcnt_ll_filter_enable((hal)->dev, unit) + +/** + * @brief Disable PCNT input filter + * + * @param hal Context of the HAL layer + * @param unit PCNT unit number + */ +#define pcnt_hal_filter_disable(hal, unit) pcnt_ll_filter_disable((hal)->dev, unit) + +/** + * @brief Init the PCNT hal and set the PCNT to the default configuration. This function should be called first before other hal layer function is called + * + * @param hal Context of the HAL layer + * @param pcnt_num The uart port number, the max port number is (PCNT_NUM_MAX -1) + */ +void pcnt_hal_init(pcnt_hal_context_t *hal, int pcnt_num); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/pcnt_types.h b/tools/sdk/esp32c3/include/hal/include/hal/pcnt_types.h new file mode 100644 index 00000000..6f09177b --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/pcnt_types.h @@ -0,0 +1,111 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/soc_caps.h" + +#define PCNT_PIN_NOT_USED (-1) /*!< When selected for a pin, this pin will not be used */ + +/** + * @brief PCNT port number, the max port number is (PCNT_PORT_MAX - 1). + */ +typedef enum { + PCNT_PORT_0 = 0, /*!< PCNT port 0 */ + PCNT_PORT_MAX, /*!< PCNT port max */ +} pcnt_port_t; + +/** + * @brief Selection of all available PCNT units + */ +typedef enum { + PCNT_UNIT_0 = 0, /*!< PCNT unit 0 */ + PCNT_UNIT_1 = 1, /*!< PCNT unit 1 */ + PCNT_UNIT_2 = 2, /*!< PCNT unit 2 */ + PCNT_UNIT_3 = 3, /*!< PCNT unit 3 */ +#if SOC_PCNT_UNIT_NUM > 4 + PCNT_UNIT_4 = 4, /*!< PCNT unit 4 */ + PCNT_UNIT_5 = 5, /*!< PCNT unit 5 */ + PCNT_UNIT_6 = 6, /*!< PCNT unit 6 */ + PCNT_UNIT_7 = 7, /*!< PCNT unit 7 */ +#endif + PCNT_UNIT_MAX, +} pcnt_unit_t; + +/** + * @brief Selection of available modes that determine the counter's action depending on the state of the control signal's input GPIO + * @note Configuration covers two actions, one for high, and one for low level on the control input + */ +typedef enum { + PCNT_MODE_KEEP = 0, /*!< Control mode: won't change counter mode*/ + PCNT_MODE_REVERSE = 1, /*!< Control mode: invert counter mode(increase -> decrease, decrease -> increase) */ + PCNT_MODE_DISABLE = 2, /*!< Control mode: Inhibit counter(counter value will not change in this condition) */ + PCNT_MODE_MAX +} pcnt_ctrl_mode_t; + +/** + * @brief Selection of available modes that determine the counter's action on the edge of the pulse signal's input GPIO + * @note Configuration covers two actions, one for positive, and one for negative edge on the pulse input + */ +typedef enum { + PCNT_COUNT_DIS = 0, /*!< Counter mode: Inhibit counter(counter value will not change in this condition) */ + PCNT_COUNT_INC = 1, /*!< Counter mode: Increase counter value */ + PCNT_COUNT_DEC = 2, /*!< Counter mode: Decrease counter value */ + PCNT_COUNT_MAX +} pcnt_count_mode_t; + +/** + * @brief Selection of channels available for a single PCNT unit + */ +typedef enum { + PCNT_CHANNEL_0 = 0x00, /*!< PCNT channel 0 */ + PCNT_CHANNEL_1 = 0x01, /*!< PCNT channel 1 */ + PCNT_CHANNEL_MAX, +} pcnt_channel_t; + +/** + * @brief Selection of counter's events the may trigger an interrupt + */ +typedef enum { + PCNT_EVT_THRES_1 = BIT(2), /*!< PCNT watch point event: threshold1 value event */ + PCNT_EVT_THRES_0 = BIT(3), /*!< PCNT watch point event: threshold0 value event */ + PCNT_EVT_L_LIM = BIT(4), /*!< PCNT watch point event: Minimum counter value */ + PCNT_EVT_H_LIM = BIT(5), /*!< PCNT watch point event: Maximum counter value */ + PCNT_EVT_ZERO = BIT(6), /*!< PCNT watch point event: counter value zero event */ + PCNT_EVT_MAX +} pcnt_evt_type_t; + +/** + * @brief Pulse Counter configuration for a single channel + */ +typedef struct { + int pulse_gpio_num; /*!< Pulse input GPIO number, if you want to use GPIO16, enter pulse_gpio_num = 16, a negative value will be ignored */ + int ctrl_gpio_num; /*!< Control signal input GPIO number, a negative value will be ignored */ + pcnt_ctrl_mode_t lctrl_mode; /*!< PCNT low control mode */ + pcnt_ctrl_mode_t hctrl_mode; /*!< PCNT high control mode */ + pcnt_count_mode_t pos_mode; /*!< PCNT positive edge count mode */ + pcnt_count_mode_t neg_mode; /*!< PCNT negative edge count mode */ + int16_t counter_h_lim; /*!< Maximum counter value */ + int16_t counter_l_lim; /*!< Minimum counter value */ + pcnt_unit_t unit; /*!< PCNT unit number */ + pcnt_channel_t channel; /*!< the PCNT channel */ +} pcnt_config_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/rmt_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/rmt_hal.h new file mode 100644 index 00000000..49b3f4c6 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/rmt_hal.h @@ -0,0 +1,112 @@ +// Copyright 2019 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. +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "soc/soc_caps.h" +#include "soc/rmt_struct.h" + +/** + * @brief HAL context type of RMT driver + * + */ +typedef struct { + rmt_dev_t *regs; /*!< RMT Register base address */ + rmt_mem_t *mem; /*!< RMT Memory base address */ +} rmt_hal_context_t; + +#define RMT_MEM_OWNER_SW (0) /*!< RMT Memory ownership belongs to software side */ +#define RMT_MEM_OWNER_HW (1) /*!< RMT Memory ownership belongs to hardware side */ + +/** + * @brief Initialize the RMT HAL driver + * + * @param hal: RMT HAL context + */ +void rmt_hal_init(rmt_hal_context_t *hal); + +/** + * @brief Reset RMT TX Channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + */ +void rmt_hal_tx_channel_reset(rmt_hal_context_t *hal, uint32_t channel); + +/** + * @brief Reset RMT TX Channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + */ +void rmt_hal_rx_channel_reset(rmt_hal_context_t *hal, uint32_t channel); + +/** + * @brief Set counter clock for RMT channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + * @param base_clk_hz: base clock for RMT internal channel (counter clock will divide from it) + * @param counter_clk_hz: target counter clock + */ +void rmt_hal_tx_set_channel_clock(rmt_hal_context_t *hal, uint32_t channel, uint32_t base_clk_hz, uint32_t counter_clk_hz); + +/** + * @brief Set carrier clock for RMT channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + * @param base_clk_hz: base clock for RMT carrier generation (carrier clock will divide from it) + * @param carrier_clk_hz: target carrier clock + * @param carrier_clk_duty: duty ratio of carrier clock + */ +void rmt_hal_set_carrier_clock(rmt_hal_context_t *hal, uint32_t channel, uint32_t base_clk_hz, uint32_t carrier_clk_hz, float carrier_clk_duty); + +/** + * @brief Set filter threshold for RMT Receive channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + * @param base_clk_hz: base clock for RMT receive filter + * @param thres_us: threshold of RMT receive filter, in us + */ +void rmt_hal_set_rx_filter_thres(rmt_hal_context_t *hal, uint32_t channel, uint32_t base_clk_hz, uint32_t thres_us); + +/** + * @brief Set idle threshold for RMT Receive channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + * @param base_clk_hz: base clock for RMT receive channel + * @param thres_us: IDLE threshold for RMT receive channel + */ +void rmt_hal_set_rx_idle_thres(rmt_hal_context_t *hal, uint32_t channel, uint32_t base_clk_hz, uint32_t thres_us); + +/** + * @brief Receive a frame from RMT channel + * + * @param hal: RMT HAL context + * @param channel: RMT channel number + * @param buf: buffer to store received RMT frame + * @return number of items that get received + */ +uint32_t rmt_hal_receive(rmt_hal_context_t *hal, uint32_t channel, rmt_item32_t *buf); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/rmt_types.h b/tools/sdk/esp32c3/include/hal/include/hal/rmt_types.h new file mode 100644 index 00000000..28b5bf59 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/rmt_types.h @@ -0,0 +1,127 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/soc_caps.h" + +/** +* @brief RMT channel ID +* +*/ +typedef enum { + RMT_CHANNEL_0, /*!< RMT channel number 0 */ + RMT_CHANNEL_1, /*!< RMT channel number 1 */ + RMT_CHANNEL_2, /*!< RMT channel number 2 */ + RMT_CHANNEL_3, /*!< RMT channel number 3 */ +#if SOC_RMT_CHANNELS_PER_GROUP > 4 + RMT_CHANNEL_4, /*!< RMT channel number 4 */ + RMT_CHANNEL_5, /*!< RMT channel number 5 */ + RMT_CHANNEL_6, /*!< RMT channel number 6 */ + RMT_CHANNEL_7, /*!< RMT channel number 7 */ +#endif + RMT_CHANNEL_MAX /*!< Number of RMT channels */ +} rmt_channel_t; + +/** + * @brief RMT Internal Memory Owner + * + */ +typedef enum { + RMT_MEM_OWNER_TX, /*!< RMT RX mode, RMT transmitter owns the memory block*/ + RMT_MEM_OWNER_RX, /*!< RMT RX mode, RMT receiver owns the memory block*/ + RMT_MEM_OWNER_MAX, +} rmt_mem_owner_t; + +/** + * @brief Clock Source of RMT Channel + * + */ +typedef enum { +#if SOC_RMT_SUPPORT_REF_TICK + RMT_BASECLK_REF = 0, /*!< RMT source clock is REF_TICK, 1MHz by default */ +#endif + RMT_BASECLK_APB = 1, /*!< RMT source clock is APB CLK, 80Mhz by default */ +#if SOC_RMT_SUPPORT_XTAL + RMT_BASECLK_XTAL = 3, /*!< RMT source clock is XTAL clock, 40Mhz by default */ +#endif + RMT_BASECLK_MAX, +} rmt_source_clk_t; + +/** + * @brief RMT Data Mode + * + * @note We highly recommended to use MEM mode not FIFO mode since there will be some gotcha in FIFO mode. + * + */ +typedef enum { + RMT_DATA_MODE_FIFO, /* +#if !CONFIG_IDF_TARGET_ESP32C3 +#include "soc/soc_caps.h" +#include "hal/rtc_io_ll.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED +/** + * Select the rtcio function. + * + * @note The RTC function must be selected before the pad analog function is enabled. + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param func Select pin function. + */ +#define rtcio_hal_function_select(rtcio_num, func) rtcio_ll_function_select(rtcio_num, func) + +/** + * Enable rtcio output. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_output_enable(rtcio_num) rtcio_ll_output_enable(rtcio_num) + +/** + * Disable rtcio output. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_output_disable(rtcio_num) rtcio_ll_output_disable(rtcio_num) + +/** + * Set RTCIO output level. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param level 0: output low; ~0: output high. + */ +#define rtcio_hal_set_level(rtcio_num, level) rtcio_ll_set_level(rtcio_num, level) + +/** + * Enable rtcio input. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_input_enable(rtcio_num) rtcio_ll_input_enable(rtcio_num) + +/** + * Disable rtcio input. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_input_disable(rtcio_num) rtcio_ll_input_disable(rtcio_num) + +/** + * Get RTCIO input level. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @return 0: input low; ~0: input high. + */ +#define rtcio_hal_get_level(rtcio_num) rtcio_ll_get_level(rtcio_num) + +/** + * @brief Set RTC GPIO pad drive capability. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param strength Drive capability of the pad. Range: 0 ~ 3. + */ +#define rtcio_hal_set_drive_capability(rtcio_num, strength) rtcio_ll_set_drive_capability(rtcio_num, strength) + +/** + * @brief Get RTC GPIO pad drive capability. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @return Drive capability of the pad. Range: 0 ~ 3. + */ +#define rtcio_hal_get_drive_capability(rtcio_num) rtcio_ll_get_drive_capability(rtcio_num) + +/** + * Set RTCIO output level. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param level 0: output low; ~0: output high. + */ +#define rtcio_hal_set_level(rtcio_num, level) rtcio_ll_set_level(rtcio_num, level) + +/** + * Get RTCIO input level. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @return 0: input low; ~0: input high. + */ +#define rtcio_hal_get_level(rtcio_num) rtcio_ll_get_level(rtcio_num) + +/** + * Set RTC IO direction. + * + * Configure RTC IO direction, such as output only, input only, + * output and input. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param mode IO direction. + */ +void rtcio_hal_set_direction(int rtcio_num, rtc_gpio_mode_t mode); + +/** + * Set RTC IO direction in deep sleep or disable sleep status. + * + * NOTE: ESP32 support INPUT_ONLY mode. + * ESP32S2 support INPUT_ONLY, OUTPUT_ONLY, INPUT_OUTPUT mode. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param mode IO direction. + */ +void rtcio_hal_set_direction_in_sleep(int rtcio_num, rtc_gpio_mode_t mode); + +/** + * RTC GPIO pullup enable. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_pullup_enable(rtcio_num) rtcio_ll_pullup_enable(rtcio_num) + +/** + * RTC GPIO pullup disable. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_pullup_disable(rtcio_num) rtcio_ll_pullup_disable(rtcio_num) + +/** + * RTC GPIO pulldown enable. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_pulldown_enable(rtcio_num) rtcio_ll_pulldown_enable(rtcio_num) + +/** + * RTC GPIO pulldown disable. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_pulldown_disable(rtcio_num) rtcio_ll_pulldown_disable(rtcio_num) + +#endif // SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + +#if SOC_RTCIO_HOLD_SUPPORTED + +/** + * Enable force hold function for RTC IO pad. + * + * Enabling HOLD function will cause the pad to lock current status, such as, + * input/output enable, input/output value, function, drive strength values. + * This function is useful when going into light or deep sleep mode to prevent + * the pin configuration from changing. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_hold_enable(rtcio_num) rtcio_ll_force_hold_enable(rtcio_num) + +/** + * Disable hold function on an RTC IO pad + * + * @note If disable the pad hold, the status of pad maybe changed in sleep mode. + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_hold_disable(rtcio_num) rtcio_ll_force_hold_disable(rtcio_num) + +/** + * Enable force hold function for RTC IO pads. + * + * Enabling HOLD function will cause the pad to lock current status, such as, + * input/output enable, input/output value, function, drive strength values. + * This function is useful when going into light or deep sleep mode to prevent + * the pin configuration from changing. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_hold_all() rtcio_ll_force_hold_all() + +/** + * Disable hold function on an RTC IO pads. + * + * @note If disable the pad hold, the status of pad maybe changed in sleep mode. + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_unhold_all() rtcio_ll_force_unhold_all() +#endif // SOC_RTCIO_HOLD_SUPPORTED + +#if SOC_RTCIO_WAKE_SUPPORTED + +/** + * Enable wakeup function and set wakeup type from light sleep status for rtcio. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param type Wakeup on high level or low level. + */ +#define rtcio_hal_wakeup_enable(rtcio_num, type) rtcio_ll_wakeup_enable(rtcio_num, type) + +/** + * Disable wakeup function from light sleep status for rtcio. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +#define rtcio_hal_wakeup_disable(rtcio_num) rtcio_ll_wakeup_disable(rtcio_num) + +/** + * Set specific logic level on an RTC IO pin as a wakeup trigger. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + * @param level Logic level (0) + */ +#define rtcio_hal_ext0_set_wakeup_pin(rtcio_num, level) rtcio_ll_ext0_set_wakeup_pin(rtcio_num, level) + +#endif + +#if SOC_RTCIO_HOLD_SUPPORTED || SOC_RTCIO_INPUT_OUTPUT_SUPPORTED + +/** + * Helper function to disconnect internal circuits from an RTC IO + * This function disables input, output, pullup, pulldown, and enables + * hold feature for an RTC IO. + * Use this function if an RTC IO needs to be disconnected from internal + * circuits in deep sleep, to minimize leakage current. + * + * In particular, for ESP32-WROVER module, call + * rtc_gpio_isolate(GPIO_NUM_12) before entering deep sleep, to reduce + * deep sleep current. + * + * @param rtcio_num The index of rtcio. 0 ~ SOC_RTCIO_PIN_COUNT. + */ +void rtcio_hal_isolate(int rtc_num); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/rtc_io_types.h b/tools/sdk/esp32c3/include/hal/include/hal/rtc_io_types.h new file mode 100644 index 00000000..9f010aef --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/rtc_io_types.h @@ -0,0 +1,25 @@ +// Copyright 2019 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. + +#pragma once + +/** RTCIO output/input mode type. */ +typedef enum { + RTC_GPIO_MODE_INPUT_ONLY , /*!< Pad input */ + RTC_GPIO_MODE_OUTPUT_ONLY, /*!< Pad output */ + RTC_GPIO_MODE_INPUT_OUTPUT, /*!< Pad input + output */ + RTC_GPIO_MODE_DISABLED, /*!< Pad (output + input) disable */ + RTC_GPIO_MODE_OUTPUT_OD, /*!< Pad open-drain output */ + RTC_GPIO_MODE_INPUT_OUTPUT_OD, /*!< Pad input + open-drain output */ +} rtc_gpio_mode_t; diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_hal.h new file mode 100644 index 00000000..5b252ea9 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_hal.h @@ -0,0 +1,528 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for SDIO slave (common part) + +// SDIO slave HAL usages: + +/* +Architecture: + +The whole SDIO slave peripheral consists of three parts: the registers (including the interrupt +control and shared registers), a send FIFO, and a receive FIFO. The document +``esp_slave_protocol.rst`` describes the functionality of the peripheral in detail. An SDIO host +will only ever access one of the three parts at any one time, thus the hardware functionality of +the SDIO slave peripheral are completely independent. Likewise, this HAL is organized in such a +fashion as to correspond to the three independent parts. + +The shared registers are quite simple: the slave can directly access them from the internal data +bus, while the host can access them by CMD52/53 with the correct address. As for the interrupts: +when an SDIO host interrupts the SDIO slave peripheral (by writing a command), the corresponding +bit in the interrupt register will be set; when the SDIO slave peripheral needs to interrupt the +host, it write some register to cause the host interrupt bit being set, and the slave hardware +will output the interrupt signal on the DAT1 line. + +For the FIFOs, the peripheral provides counters as registers so that the host can always know whether the slave +is ready to send/receive data. The HAL resets the counters during initialization, and the host should somehow +inform the slave to reset the counters again if it should reboot (or lose the counter value for some reasons). +Then the host can read/write the FIFOs by CMD53 commands according to the counters. + +In order to avoid copying data to/from the FIFOs or memory buffers each time, the HAL layer +contains a descriptor queue (implemented as linked-list) that allows descriptors of memory +buffers to be queued for transmission/reception. Once a buffer is queued, the HAL takes ownership +of the buffer until some "finish" functions successfully return, indicating the +transmission/reception of that buffer is complete. The ISR is invoked multiple times to iterate +through the queued descriptors, and also to signal to the upper layer if a buffer has been +freed. + +The HAL is used as below: + +- Receiving part: + + 1. Call `sdio_slave_hal_recv_start` to start the receiving DMA. + + If there are already buffers loaded, the receiving will start from those buffers first. + + 2. Call `sdio_slave_hal_recv_init_desc` with a `sdio_slave_hal_recv_desc_t` and the buffer address to + associate the descriptor with the buffer. + + The HAL initialize this descriptors with the determined length and maybe some extra data. + + 3. Call `sdio_slave_hal_load_buf` with the initialized descriptor of the buffer to load a + receiving buffer to the HAL. + + When the DMA is started, the descriptors is loaded onto the DMA linked-list, and the + counter of receiving buffers is increased so that the host will know this by the + receiving interrupt. The hardware will automatically go through the linked list and write + data into the buffers loaded on the list. + + 4. (Optional, mandatory only when interrupt enabled) Call `sdio_slave_hal_recv_done` to check + and clear the receiving interrupt bits. + + 5. Call `sdio_slave_hal_recv_has_next_item` to check whether there are finished buffers. + + 6. Call `sdio_slave_hal_recv_unload_desc` for the same times as + `sdio_slave_hal_recv_has_next_item` successfully returns. + + 7. (Optional) Call `sdio_slave_hal_recv_reset_counter` to reset the counter to current loaded + but not used buffers if you want to reset the counter only. This is available only when + the DMA is stopped. + + 8. (Optional) Call `sdio_slave_hal_recv_flush_one_buffer` (recursively) if you want to + discard data of one (or more) buffers and load them again. This is available only when + the DMA is stopped. + + 9. (Optional when deinitialization) Call `sdio_slave_hal_recv_unload_desc` recursively to get + all the buffers loaded to the HAL, no matter they are used or not. Don't do this when the + DMA is not stopped. + +- Sending part: + + The sending driver is slightly different, since we are not using the re-start feature. + (TODO: re-write this part if the stitch mode is released) + + 1. Call `sdio_slave_hal_send_start` to start the sending DMA. + + If there is already any data queued, it will ne ready to be sent to host now. + + 2. Call `sdio_slave_hal_send_queue` to queue the data to send. + + If the interrupt is enabled, the ISR will be invoked. + + 3. (Required if interrupt enabled) Call `` to clear the interrupt bits used by the SW + invoking logic. + + 4. Call `sdio_slave_hal_send_new_packet_if_exist` to check and send new packet (if there is + data queued). + + 5. Call `sdio_slave_hal_send_eof_happened` to check whether the previous packet is done. + + It will also clear the interrupt status bit for this event. + + 6. Call `sdio_slave_hal_send_get_next_finished_arg` recursively to get the arguments for the + finished buffers. + + 7. (Optional when deinitialization) Call `sdio_slave_hal_send_flush_next_buffer` recursively + to get all buffers queued, regardless sent or not. Don't do this when the DMA is not stopped. + + 8. (Optional) Call `sdio_slave_hal_send_reset_counter` to reset the counter to current loaded + but not sent buffers if you want to reset the counter only. Don't do this when the DMA is not + stopped. + + Note a counter should be used when performing step 2 and 6, to make sure that the queue size + is enough. + +- Host part: + + 1. Call `sdio_slave_hal_hostint_set_ena` and `sdio_slave_hal_hostint_get_ena` to + enable/disable the interrupt sent to master. Note that the host can also modify the same + registers at the same time. Try to avoid using them outside the initialization process. + + 2. Call `sdio_slave_hal_hostint_send` and `sdio_slave_hal_hostint_clear` to trigger general + purpose interrupts or cancel all kinds of interrupts send to the host. These interrupts are + set/cleared in a concurrent-safe way, so the slave can call these functions safely. + + 3. Call `sdio_slave_hal_slvint_fetch_clear` to fetch the general purpose interrupts sent by + the host to the slave. These interrupts will also be cleared after the calls. + + 4. Call `sdio_slave_hal_host_get_reg` and `sdio_slave_hal_host_set_reg` to read/write the + general purpose shared between the host and slave. Note that these registers are also not + concurrent-safe. Try not to write to the same register from two directions at the same time. +*/ + +#pragma once +#include +#include "soc/lldesc.h" +#include "hal/sdio_slave_types.h" +#include "hal/sdio_slave_ll.h" + +/// Space used for each sending descriptor. Should initialize the sendbuf accoring to this size. +#define SDIO_SLAVE_SEND_DESC_SIZE sizeof(sdio_slave_hal_send_desc_t) + + +/// Status of the sending part +typedef enum { + STATE_IDLE = 1, + STATE_WAIT_FOR_START = 2, + STATE_SENDING = 3, + STATE_GETTING_RESULT = 4, + STATE_GETTING_UNSENT_DESC = 5, +} send_state_t; + +typedef struct { + uint8_t* data; ///< Address of the buffer + size_t size; ///< Size of the buffer, but can only queue (size/SDIO_SLAVE_SEND_DESC_SIZE)-1 descriptors + uint8_t* write_ptr; + uint8_t* read_ptr; + uint8_t* free_ptr; +} sdio_ringbuf_t; + +// Append two extra words to be used by the HAL. +// Should Initialize the member `data` of `send_desc_queue` of the HAL context +// with size of this desc * N. + +/// DMA descriptor with extra fields +typedef struct sdio_slave_hal_send_desc_s { + lldesc_t dma_desc; ///< Used by Hardware, has pointer linking to next desc + uint32_t pkt_len; ///< Accumulated length till this descriptor + void* arg; ///< Holding arguments indicating this buffer */ +} sdio_slave_hal_send_desc_t; + +/// Descriptor used by the receiving part, call `sdio_slave_hal_recv_init_desc` +/// to initialize it before use. +typedef lldesc_t sdio_slave_hal_recv_desc_t; +#define sdio_slave_hal_recv_desc_s lldesc_s +typedef STAILQ_HEAD(recv_stailq_head_s, sdio_slave_hal_recv_desc_s) sdio_slave_hal_recv_stailq_t; + + +/** HAL context structure. Call `sdio_slave_hal_init` to initialize it and + * configure required members before actually use the HAL. + */ +typedef struct { + /// Hardware registers for this SDIO slave peripheral, configured by + /// `sdio_slave_hal_init` + struct { + slc_dev_t* slc; + host_dev_t* host; + hinf_dev_t* hinf; + }; + sdio_slave_sending_mode_t sending_mode; /**< Sending mode, should be manually configured before using the HAL. + * see `sdio_slave_sending_mode_t`. + */ + sdio_slave_timing_t timing; /**< Timing mode (launch edge and latch edge settings). Should be manually + * configured before using the HAL. `SDIO_SLAVE_TIMING_PSEND_PSAMPLE` is + * recommended by default. + */ + int send_queue_size; /**< Max buffers that can be queued before sending. Should be manually + * configured before using the HAL. + */ + size_t recv_buffer_size; /**< The size of each buffer. The host and slave should share a + * pre-negotiated value. Should be manually configured before using + * the HAL. + */ + sdio_ringbuf_t send_desc_queue; /**< The ring buffer used to hold queued descriptors. Should be manually + * initialized before using the HAL. + */ + //Internal status, no need to touch. + send_state_t send_state; // Current state of sending part. + uint32_t tail_pkt_len; // The accumulated send length of the tail packet. + sdio_slave_hal_send_desc_t* in_flight_head; // The head of linked list in-flight. + sdio_slave_hal_send_desc_t* in_flight_end; // The end of linked list in-flight. + sdio_slave_hal_send_desc_t* in_flight_next; // The header of linked list to be sent next time. + sdio_slave_hal_send_desc_t* returned_desc; // The last returned descriptor + + sdio_slave_hal_recv_stailq_t recv_link_list; // Linked list of buffers ready to hold data and the buffers already hold data. + volatile sdio_slave_hal_recv_desc_t* recv_cur_ret; // Next desc to return, NULL if all loaded descriptors are returned. +} sdio_slave_context_t ; + +/** + * Initialize the HAL, should provide buffers to the context and configure the + * members before this funciton is called. + * + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_init(sdio_slave_context_t *hal); + +/** + * Initialize the SDIO slave peripheral hardware. + * + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_hw_init(sdio_slave_context_t *hal); + +/** + * Set the IO ready for host to read. + * + * @param hal Context of the HAL layer. + * @param ready true to tell the host the slave is ready, otherwise false. + */ +void sdio_slave_hal_set_ioready(sdio_slave_context_t *hal, bool ready); + +/*--------------------------------------------------------------------------- + * Send + *--------------------------------------------------------------------------*/ + +/** + * The hardware sending DMA starts. If there is existing data, send them. + * + * @param hal Context of the HAL layer. + */ +esp_err_t sdio_slave_hal_send_start(sdio_slave_context_t *hal); + +/** + * Stops hardware sending DMA. + * + * @note The data in the queue, as well as the counter are not touched. + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_send_stop(sdio_slave_context_t *hal); + +/** + * Put some data into the sending queue. + * + * @note The caller should keeps the buffer, until the `arg` is returned by + * `sdio_slave_hal_send_get_next_finished_arg`. + * @note The caller should count to ensure there is enough space in the queue. + * The initial queue size is sizeof(sendbuf.data)/sizeof(sdio_slave_hal_send_desc_t)-1, + * Will decrease by one when this function successfully returns. + * Released only by `sdio_slave_hal_send_get_next_finished_arg` or + * `sdio_slave_hal_send_flush_next_buffer`. + * + * @note The HAL is not thread-safe. The caller should use a spinlock to ensure + * the `sdio_slave_hal_send_queue` and ... are not called at the same time. + * + * @param hal Context of the HAL layer. + * @param addr Address of data in the memory to send. + * @param len Length of data to send. + * @param arg Argument indicating this sending. + * @return Always ESP_OK. + */ +esp_err_t sdio_slave_hal_send_queue(sdio_slave_context_t *hal, uint8_t *addr, size_t len, void *arg); + +/** + * The ISR should call this, to handle the SW invoking event. + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_send_handle_isr_invoke(sdio_slave_context_t *hal); + +/** + * Check whether there is no in-flight transactions, and send new packet if there + * is new packets queued. + * + * @param hal Context of the HAL layer. + * @return + * - ESP_OK: The DMA starts to send a new packet. + * - ESP_ERR_NOT_FOUND: No packet waiting to be sent. + * - ESP_ERR_INVALID_STATE: There is packet in-flight. + */ +esp_err_t sdio_slave_hal_send_new_packet_if_exist(sdio_slave_context_t *hal); + +/** + * Check whether the sending EOF has happened and clear the interrupt. + * + * Call `sdio_slave_hal_send_get_next_finished_arg` recursively to retrieve arguments of finished + * buffers. + * + * @param hal Context of the HAL layer. + * @return true if happened, otherwise false. + */ +bool sdio_slave_hal_send_eof_happened(sdio_slave_context_t *hal); + +/** + * Get the arguments of finished packets. Call recursively until all finished + * arguments are all retrieved. + * + * @param hal Context of the HAL layer. + * @param out_arg Output argument of the finished buffer. + * @param out_returned_cnt Released queue size to be queued again. + * @return + * - ESP_OK: if one argument retrieved. + * - ESP_ERR_NOT_FOUND: All the arguments of the finished buffers are retrieved. + */ +esp_err_t sdio_slave_hal_send_get_next_finished_arg(sdio_slave_context_t *hal, void **out_arg, uint32_t* out_returned_cnt); + +/** + * Flush one buffer in the queue, no matter sent, canceled or not sent yet. + * + * Call recursively to clear the whole queue before deinitialization. + * + * @note Only call when the DMA is stopped! + * @param hal Context of the HAL layer. + * @param out_arg Argument indiciating the buffer to send + * @param out_return_cnt Space in the queue released after this descriptor is flushed. + * @return + * - ESP_ERR_INVALID_STATE: This function call be called only when the DMA is stopped. + * - ESP_ERR_NOT_FOUND: if no buffer in the queue + * - ESP_OK: if a buffer is successfully flushed and returned. + */ +esp_err_t sdio_slave_hal_send_flush_next_buffer(sdio_slave_context_t *hal, void **out_arg, uint32_t *out_return_cnt); + +/** + * Walk through all the unsent buffers and reset the counter to the accumulated length of them. The data will be kept. + * + * @note Only call when the DMA is stopped! + * @param hal Context of the HAL layer. + * @return + * - ESP_ERR_INVALID_STATE: this function call be called only when the DMA is stopped + * - ESP_OK: if success + */ +esp_err_t sdio_slave_hal_send_reset_counter(sdio_slave_context_t *hal); + + +/*--------------------------------------------------------------------------- + * Receive + *--------------------------------------------------------------------------*/ +/** + * Start the receiving DMA. + * + * @note If there are already some buffers loaded, will receive from them first. + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_recv_start(sdio_slave_context_t *hal); + +/** + * Stop the receiving DMA. + * + * @note Data and the counter will not be touched. You can still call + * `sdio_slave_hal_recv_has_next_item` to get the received buffer. + * And unused buffers loaded to the HAL will still be in the `loaded` + * state in the HAL, until returned by `sdio_slave_hal_recv_unload_desc`. + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_recv_stop(sdio_slave_context_t* hal); + +/** + * Associate the buffer to the descriptor given. The descriptor may also be initialized with some + * other data. + * + * @param hal Context of the HAL layer. + * @param desc Descriptor to associate with the buffer + * @param start Start address of the buffer + */ +void sdio_slave_hal_recv_init_desc(sdio_slave_context_t *hal, sdio_slave_hal_recv_desc_t *desc, uint8_t *start); + +/** + * Load the buffer to the HAL to be used to receive data. + * + * @note Loaded buffers will be returned to the upper layer only when: + * 1. Returned by `sdio_slave_hal_recv_has_next_item` when receiving to that buffer successfully + * done. + * 2. Returned by `sdio_slave_hal_recv_unload_desc` unconditionally. + * @param hal Context of the HAL layer. + * @param desc Descriptor to load to the HAL to receive. + */ +void sdio_slave_hal_load_buf(sdio_slave_context_t *hal, sdio_slave_hal_recv_desc_t *desc); + +/** + * Check and clear the interrupt indicating a buffer has finished receiving. + * + * @param hal Context of the HAL layer. + * @return true if interrupt triggered, otherwise false. + */ +bool sdio_slave_hal_recv_done(sdio_slave_context_t* hal); + +/** + * Call this function recursively to check whether there is any buffer that has + * finished receiving. + * + * Will walk through the linked list to find a newer finished buffer. For each successful return, + * it means there is one finished buffer. You can one by `sdio_slave_hal_recv_unload_desc`. You can + * also call `sdio_slave_hal_recv_has_next_item` several times continuously before you call the + * `sdio_slave_hal_recv_unload_desc` for the same times. + * + * @param hal Context of the HAL layer. + * @return true if there is + */ +bool sdio_slave_hal_recv_has_next_item(sdio_slave_context_t* hal); + +/** + * Unconditionally remove and return the first descriptor loaded to the HAL. + * + * Unless during de-initialization, `sdio_slave_hal_recv_has_next_item` should have succeed for the + * same times as this function is called, to ensure the returned descriptor has finished its + * receiving job. + * + * @param hal Context of the HAL layer. + * @return The removed descriptor, NULL means the linked-list is empty. + */ +sdio_slave_hal_recv_desc_t *sdio_slave_hal_recv_unload_desc(sdio_slave_context_t *hal); + +/** + * Walk through all the unused buffers and reset the counter to the number of + * them. + * + * @note Only call when the DMA is stopped! + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_recv_reset_counter(sdio_slave_context_t *hal); + +/** + * Walk through all the used buffers, clear the finished flag and appended them + * back to the end of the unused list, waiting to receive then. + * + * @note You will lose all the received data in the buffer. + * @note Only call when the DMA is stopped! + * @param hal Context of the HAL layer. + */ +void sdio_slave_hal_recv_flush_one_buffer(sdio_slave_context_t *hal); + + +/*--------------------------------------------------------------------------- + * Host + *--------------------------------------------------------------------------*/ + +/** + * Enable some of the interrupts for the host. + * + * @note May have concurrency issue wit the host or other tasks, suggest only use it during + * initialization. + * @param hal Context of the HAL layer. + * @param mask Bitwise mask for the interrupts to enable. + */ +void sdio_slave_hal_hostint_set_ena(sdio_slave_context_t *hal, const sdio_slave_hostint_t *mask); + +/** + * Get the enabled interrupts. + * + * @param hal Context of the HAL layer. + * @param out_int_mask Output of the enabled interrupts + */ +void sdio_slave_hal_hostint_get_ena(sdio_slave_context_t *hal, sdio_slave_hostint_t *out_int_mask); + +/** + * Send general purpose interrupt (slave send to host). + * @param hal Context of the HAL layer. + * @param mask Interrupts to send, only `SDIO_SLAVE_HOSTINT_BIT*` are allowed. + */ +void sdio_slave_hal_hostint_send(sdio_slave_context_t *hal, const sdio_slave_hostint_t *mask); + +/** + * Cleared the specified interrupts for the host. + * + * @param hal Context of the HAL layer. + * @param mask Interrupts to clear. + */ +void sdio_slave_hal_hostint_clear(sdio_slave_context_t *hal, const sdio_slave_hostint_t *mask); + + +/** + * Fetch the interrupt (host send to slave) status bits and clear all of them. + * @param hal Context of the HAL layer. + * @param out_int_mask Output interrupt status + */ +void sdio_slave_hal_slvint_fetch_clear(sdio_slave_context_t *hal, sdio_slave_ll_slvint_t *out_int_mask); + +/** + * Get the value of a shared general purpose register. + * + * @param hal Context of the HAL layer. + * @param pos Position of the register, 4 bytes share a word. 0-63 except 24-27. + * @return The register value. + */ +uint8_t sdio_slave_hal_host_get_reg(sdio_slave_context_t *hal, int pos); + +/** + * Set the value of shared general purpose register. + * + * @param hal Context of the HAL layer. + * @param pos Position of the register, 4 bytes share a word. 0-63 except 24-27. + * @param reg Value to set. + */ +void sdio_slave_hal_host_set_reg(sdio_slave_context_t *hal, int pos, uint8_t reg); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_ll.h b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_ll.h new file mode 100644 index 00000000..77fe8783 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_ll.h @@ -0,0 +1,481 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The LL layer for ESP32 SDIO slave register operations +// It's strange but `tx_*` regs for host->slave transfers while `rx_*` regs for slave->host transfers +// To reduce ambiguity, we call (host->slave, tx) transfers receiving and (slave->host, rx) transfers receiving + +#pragma once + +#include "hal/sdio_slave_hal.h" +#include "soc/slc_struct.h" +#include "soc/slc_reg.h" +#include "soc/host_struct.h" +#include "soc/host_reg.h" +#include "soc/hinf_struct.h" +#include "soc/lldesc.h" + +/// Get address of the only SLC registers for ESP32 +#define sdio_slave_ll_get_slc(ID) (&SLC) +/// Get address of the only HOST registers for ESP32 +#define sdio_slave_ll_get_host(ID) (&HOST) +/// Get address of the only HINF registers for ESP32 +#define sdio_slave_ll_get_hinf(ID) (&HINF) + + +/// Mask of general purpose interrupts sending from the host. +typedef enum { + SDIO_SLAVE_LL_SLVINT_0 = BIT(0), ///< General purpose interrupt bit 0. + SDIO_SLAVE_LL_SLVINT_1 = BIT(1), + SDIO_SLAVE_LL_SLVINT_2 = BIT(2), + SDIO_SLAVE_LL_SLVINT_3 = BIT(3), + SDIO_SLAVE_LL_SLVINT_4 = BIT(4), + SDIO_SLAVE_LL_SLVINT_5 = BIT(5), + SDIO_SLAVE_LL_SLVINT_6 = BIT(6), + SDIO_SLAVE_LL_SLVINT_7 = BIT(7), +} sdio_slave_ll_slvint_t; + +/** + * Initialize the hardware. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_init(slc_dev_t *slc) +{ + slc->slc0_int_ena.val = 0; + + slc->conf0.slc0_rx_auto_wrback = 1; + slc->conf0.slc0_token_auto_clr = 0; + slc->conf0.slc0_rx_loop_test = 0; + slc->conf0.slc0_tx_loop_test = 0; + + slc->conf1.slc0_rx_stitch_en = 0; + slc->conf1.slc0_tx_stitch_en = 0; + slc->conf1.slc0_len_auto_clr = 0; + + slc->rx_dscr_conf.slc0_token_no_replace = 1; +} + +/** + * Set the timing for the communication + * + * @param host Address of the host registers + * @param timing Timing configuration to set + */ +static inline void sdio_slave_ll_set_timing(host_dev_t *host, sdio_slave_timing_t timing) +{ + switch(timing) { + case SDIO_SLAVE_TIMING_PSEND_PSAMPLE: + host->conf.frc_sdio20 = 0x1f; + host->conf.frc_sdio11 = 0; + host->conf.frc_pos_samp = 0x1f; + host->conf.frc_neg_samp = 0; + break; + case SDIO_SLAVE_TIMING_PSEND_NSAMPLE: + host->conf.frc_sdio20 = 0x1f; + host->conf.frc_sdio11 = 0; + host->conf.frc_pos_samp = 0; + host->conf.frc_neg_samp = 0x1f; + break; + case SDIO_SLAVE_TIMING_NSEND_PSAMPLE: + host->conf.frc_sdio20 = 0; + host->conf.frc_sdio11 = 0x1f; + host->conf.frc_pos_samp = 0x1f; + host->conf.frc_neg_samp = 0; + break; + case SDIO_SLAVE_TIMING_NSEND_NSAMPLE: + host->conf.frc_sdio20 = 0; + host->conf.frc_sdio11 = 0x1f; + host->conf.frc_pos_samp = 0; + host->conf.frc_neg_samp = 0x1f; + break; + } +} + +/** + * Set the HS supported bit to be read by the host. + * + * @param hinf Address of the hinf registers + * @param hs true if supported, otherwise false. + */ +static inline void sdio_slave_ll_enable_hs(hinf_dev_t *hinf, bool hs) +{ + if (hs) { + hinf->cfg_data1.sdio_ver = 0x232; + hinf->cfg_data1.highspeed_enable = 1; + } +} + +/** + * Set the IO Ready bit to be read by the host. + * + * @param hinf Address of the hinf registers + * @param ready true if ready, otherwise false. + */ +static inline void sdio_slave_ll_set_ioready(hinf_dev_t *hinf, bool ready) +{ + hinf->cfg_data1.sdio_ioready1 = (ready ? 1 : 0); //set IO ready to 1 to stop host from using +} + +/*--------------------------------------------------------------------------- + * Send + *--------------------------------------------------------------------------*/ +/** + * Reset the sending DMA. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_send_reset(slc_dev_t *slc) +{ + //reset to flush previous packets + slc->conf0.slc0_rx_rst = 1; + slc->conf0.slc0_rx_rst = 0; +} + +/** + * Start the sending DMA with the given descriptor. + * + * @param slc Address of the SLC registers + * @param desc Descriptor to send + */ +static inline void sdio_slave_ll_send_start(slc_dev_t *slc, const lldesc_t *desc) +{ + slc->slc0_rx_link.addr = (uint32_t)desc; + slc->slc0_rx_link.start = 1; +} + +/** + * Write the PKT_LEN register to be written by the host to a certain value. + * + * @param slc Address of the SLC registers + * @param len Length to write + */ +static inline void sdio_slave_ll_send_write_len(slc_dev_t *slc, uint32_t len) +{ + slc->slc0_len_conf.val = FIELD_TO_VALUE2(SLC_SLC0_LEN_WDATA, len) | FIELD_TO_VALUE2(SLC_SLC0_LEN_WR, 1); +} + +/** + * Read the value of PKT_LEN register. The register may keep the same until read + * by the host. + * + * @param host Address of the host registers + * @return The value of PKT_LEN register. + */ +static inline uint32_t sdio_slave_ll_send_read_len(host_dev_t *host) +{ + return host->pkt_len.reg_slc0_len; +} + +/** + * Enable the rx_done interrupt. (sending) + * + * @param slc Address of the SLC registers + * @param ena true if enable, otherwise false. + */ +static inline void sdio_slave_ll_send_part_done_intr_ena(slc_dev_t *slc, bool ena) +{ + slc->slc0_int_ena.rx_done = (ena ? 1 : 0); +} + +/** + * Clear the rx_done interrupt. (sending) + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_send_part_done_clear(slc_dev_t *slc) +{ + slc->slc0_int_clr.rx_done = 1; +} + +/** + * Check whether the hardware is ready for the SW to use rx_done to invoke + * the ISR. + * + * @param slc Address of the SLC registers + * @return true if ready, otherwise false. + */ +static inline bool sdio_slave_ll_send_invoker_ready(slc_dev_t *slc) +{ + return slc->slc0_int_raw.rx_done; +} + +/** + * Stop the sending DMA. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_send_stop(slc_dev_t *slc) +{ + slc->slc0_rx_link.stop = 1; +} + +/** + * Enable the sending interrupt (rx_eof). + * + * @param slc Address of the SLC registers + * @param ena true to enable, false to disable + */ +static inline void sdio_slave_ll_send_intr_ena(slc_dev_t *slc, bool ena) +{ + slc->slc0_int_ena.rx_eof = (ena? 1: 0); +} + +/** + * Clear the sending interrupt (rx_eof). + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_send_intr_clr(slc_dev_t *slc) +{ + slc->slc0_int_clr.rx_eof = 1; +} + +/** + * Check whether the sending is done. + * + * @param slc Address of the SLC registers + * @return true if done, otherwise false + */ +static inline bool sdio_slave_ll_send_done(slc_dev_t *slc) +{ + return slc->slc0_int_st.rx_eof != 0; +} + +/** + * Clear the host interrupt indicating the slave having packet to be read. + * + * @param host Address of the host registers + */ +static inline void sdio_slave_ll_send_hostint_clr(host_dev_t *host) +{ + host->slc0_int_clr.rx_new_packet = 1; +} + +/*--------------------------------------------------------------------------- + * Receive + *--------------------------------------------------------------------------*/ +/** + * Enable the receiving interrupt. + * + * @param slc Address of the SLC registers + * @param ena + */ +static inline void sdio_slave_ll_recv_intr_ena(slc_dev_t *slc, bool ena) +{ + slc->slc0_int_ena.tx_done = (ena ? 1 : 0); +} + +/** + * Start receiving DMA with the given descriptor. + * + * @param slc Address of the SLC registers + * @param desc Descriptor of the receiving buffer. + */ +static inline void sdio_slave_ll_recv_start(slc_dev_t *slc, lldesc_t *desc) +{ + slc->slc0_tx_link.addr = (uint32_t)desc; + slc->slc0_tx_link.start = 1; +} + +/** + * Increase the receiving buffer counter by 1. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_size_inc(slc_dev_t *slc) +{ + // fields wdata and inc_more should be written by the same instruction. + slc->slc0_token1.val = FIELD_TO_VALUE2(SLC_SLC0_TOKEN1_WDATA, 1) | FIELD_TO_VALUE2(SLC_SLC0_TOKEN1_INC_MORE, 1); +} + +/** + * Reset the receiving buffer. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_size_reset(slc_dev_t *slc) +{ + slc->slc0_token1.val = FIELD_TO_VALUE2(SLC_SLC0_TOKEN1_WDATA, 0) | FIELD_TO_VALUE2(SLC_SLC0_TOKEN1_WR, 1); +} + +/** + * Check whether there is a receiving finished event. + * + * @param slc Address of the SLC registers + * @return + */ +static inline bool sdio_slave_ll_recv_done(slc_dev_t *slc) +{ + return slc->slc0_int_raw.tx_done != 0; +} + +/** + * Clear the receiving finished interrupt. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_done_clear(slc_dev_t *slc) +{ + slc->slc0_int_clr.tx_done = 1; +} + +/** + * Restart the DMA. Call after you modified the next pointer of the tail descriptor to the appended + * descriptor. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_restart(slc_dev_t *slc) +{ + slc->slc0_tx_link.restart = 1; +} + +/** + * Reset the receiving DMA. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_reset(slc_dev_t *slc) +{ + slc->conf0.slc0_tx_rst = 1; + slc->conf0.slc0_tx_rst = 0; +} + +/** + * Stop the receiving DMA. + * + * @param slc Address of the SLC registers + */ +static inline void sdio_slave_ll_recv_stop(slc_dev_t *slc) +{ + slc->slc0_tx_link.stop = 1; +} + +/*--------------------------------------------------------------------------- + * Host + *--------------------------------------------------------------------------*/ +/** + * Get the address of the shared general purpose register. Internal. + * + * @param host Address of the host registers + * @param pos Position of the register, 0-63 except 24-27. + * @return address of the register. + */ +static inline intptr_t sdio_slave_ll_host_get_w_reg(host_dev_t* host, int pos) +{ + return (intptr_t )&(host->conf_w0) + pos + (pos>23?4:0) + (pos>31?12:0); +} + +/** + * Get the value of the shared general purpose register. + * + * @param host Address of the host registers + * @param pos Position of the register, 0-63, except 24-27. + * @return value of the register. + */ +static inline uint8_t sdio_slave_ll_host_get_reg(host_dev_t *host, int pos) +{ + return *(uint8_t*)sdio_slave_ll_host_get_w_reg(host, pos); +} + +/** + * Set the value of the shared general purpose register. + * + * @param host Address of the host registers + * @param pos Position of the register, 0-63, except 24-27. + * @param reg Value to set. + */ +static inline void sdio_slave_ll_host_set_reg(host_dev_t* host, int pos, uint8_t reg) +{ + uint32_t* addr = (uint32_t*)(sdio_slave_ll_host_get_w_reg(host, pos) & (~3)); + uint32_t shift = (pos % 4) * 8; + *addr &= ~(0xff << shift); + *addr |= ((uint32_t)reg << shift); +} + +/** + * Get the interrupt enable bits for the host. + * + * @param host Address of the host registers + * @return Enabled interrupts + */ +static inline sdio_slave_hostint_t sdio_slave_ll_host_get_intena(host_dev_t* host) +{ + return host->slc0_func1_int_ena.val; +} + +/** + * Set the interrupt enable bits for the host. + * + * @param host Address of the host registers + * @param mask Mask of interrupts to enable + */ +static inline void sdio_slave_ll_host_set_intena(host_dev_t *host, const sdio_slave_hostint_t *mask) +{ + host->slc0_func1_int_ena.val = (*mask); +} + +/** + * Clear the interrupt bits for the host. + * @param host Address of the host registers + * @param mask Mask of interrupts to clear. + */ +static inline void sdio_slave_ll_host_intr_clear(host_dev_t* host, const sdio_slave_hostint_t *mask) +{ + host->slc0_int_clr.val = (*mask); +} + +/** + * Send general purpose interrupts to the host. + * @param slc Address of the SLC registers + * @param mask Mask of interrupts to seend to host + */ +static inline void sdio_slave_ll_host_send_int(slc_dev_t *slc, const sdio_slave_hostint_t *mask) +{ + //use registers in SLC to trigger, rather than write HOST registers directly + //other interrupts than tohost interrupts are not supported yet + slc->intvec_tohost.slc0_intvec = (*mask); +} + +/** + * Enable some of the slave interrups (send from host) + * + * @param slc Address of the SLC registers + * @param mask Mask of interrupts to enable, all those set to 0 will be disabled. + */ +static inline void sdio_slave_ll_slvint_set_ena(slc_dev_t *slc, const sdio_slave_ll_slvint_t *mask) +{ + //other interrupts are not enabled + slc->slc0_int_ena.val = (slc->slc0_int_ena.val & (~0xff)) | ((*mask) & 0xff); +} + +/** + * Fetch the slave interrupts (send from host) and clear them. + * + * @param slc Address of the SLC registers + * @param out_slv_int Output of the slave interrupts fetched and cleared. + */ +static inline void sdio_slave_ll_slvint_fetch_clear(slc_dev_t *slc, sdio_slave_ll_slvint_t *out_slv_int) +{ + sdio_slave_ll_slvint_t slv_int = slc->slc0_int_st.val & 0xff; + *out_slv_int = slv_int; + slc->slc0_int_clr.val = slv_int; +} diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_types.h b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_types.h new file mode 100644 index 00000000..60e08456 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sdio_slave_types.h @@ -0,0 +1,47 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "soc/soc.h" + +/// Mask of interrupts sending to the host. +typedef enum { + SDIO_SLAVE_HOSTINT_BIT0 = BIT(0), ///< General purpose interrupt bit 0. + SDIO_SLAVE_HOSTINT_BIT1 = BIT(1), + SDIO_SLAVE_HOSTINT_BIT2 = BIT(2), + SDIO_SLAVE_HOSTINT_BIT3 = BIT(3), + SDIO_SLAVE_HOSTINT_BIT4 = BIT(4), + SDIO_SLAVE_HOSTINT_BIT5 = BIT(5), + SDIO_SLAVE_HOSTINT_BIT6 = BIT(6), + SDIO_SLAVE_HOSTINT_BIT7 = BIT(7), + SDIO_SLAVE_HOSTINT_SEND_NEW_PACKET = BIT(23), ///< New packet available +} sdio_slave_hostint_t; + + +/// Timing of SDIO slave +typedef enum { + SDIO_SLAVE_TIMING_PSEND_PSAMPLE = 0,/**< Send at posedge, and sample at posedge. Default value for HS mode. + * Normally there's no problem using this to work in DS mode. + */ + SDIO_SLAVE_TIMING_NSEND_PSAMPLE ,///< Send at negedge, and sample at posedge. Default value for DS mode and below. + SDIO_SLAVE_TIMING_PSEND_NSAMPLE, ///< Send at posedge, and sample at negedge + SDIO_SLAVE_TIMING_NSEND_NSAMPLE, ///< Send at negedge, and sample at negedge +} sdio_slave_timing_t; + +/// Configuration of SDIO slave mode +typedef enum { + SDIO_SLAVE_SEND_STREAM = 0, ///< Stream mode, all packets to send will be combined as one if possible + SDIO_SLAVE_SEND_PACKET = 1, ///< Packet mode, one packets will be sent one after another (only increase packet_len if last packet sent). +} sdio_slave_sending_mode_t; diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sha_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/sha_hal.h new file mode 100644 index 00000000..775063a4 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sha_hal.h @@ -0,0 +1,90 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in soc/include/hal/readme.md + ******************************************************************************/ + +#pragma once + +#include +#include +#include "soc/soc_caps.h" +#include "soc/lldesc.h" +#include "hal/sha_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Hashes a single message block + * + * @param sha_type SHA algorithm to hash with + * @param data_block Input message to be hashed + * @param block_word_len Length of the input message + * @param first_block Is this the first block in a message or a continuation? + */ +void sha_hal_hash_block(esp_sha_type sha_type, const void *data_block, size_t block_word_len, bool first_block); + +/** + * @brief Polls and waits until the SHA engine is idle + * + */ +void sha_hal_wait_idle(void); + +/** + * @brief Reads the current message digest from the SHA engine + * + * @param sha_type SHA algorithm used + * @param digest_state Output buffer to which to read message digest to + */ +void sha_hal_read_digest(esp_sha_type sha_type, void *digest_state); + +#if SOC_SHA_SUPPORT_RESUME +/** + * @brief Writes the message digest to the SHA engine + * + * @param sha_type The SHA algorithm type + * @param digest_state Message digest to be written to SHA engine + */ +void sha_hal_write_digest(esp_sha_type sha_type, void *digest_state); +#endif + +#if SOC_SHA_SUPPORT_DMA +/** + * @brief Hashes a number of message blocks using DMA + * + * @param sha_type SHA algorithm to hash with + * @param num_blocks Number of blocks to hash + * @param first_block Is this the first block in a message or a continuation? + */ +void sha_hal_hash_dma(esp_sha_type sha_type, size_t num_blocks, bool first_block); +#endif + +#if SOC_SHA_SUPPORT_SHA512_T +/** + * @brief Calculates and sets the initial digiest for SHA512_t + * + * @param t_string + * @param t_len + */ +void sha_hal_sha512_init_hash(uint32_t t_string, uint8_t t_len); +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sha_types.h b/tools/sdk/esp32c3/include/hal/include/hal/sha_types.h new file mode 100644 index 00000000..3b8807fa --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sha_types.h @@ -0,0 +1,41 @@ +// Copyright 2020 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. + +#pragma once + +#include "sdkconfig.h" + +/* Use enum from rom for backwards compatibility */ +#if CONFIG_IDF_TARGET_ESP32 +#include "esp32/rom/sha.h" +typedef enum SHA_TYPE esp_sha_type; +#elif CONFIG_IDF_TARGET_ESP32S2 +#include "esp32s2/rom/sha.h" +typedef SHA_TYPE esp_sha_type; +#elif CONFIG_IDF_TARGET_ESP32S3 +#include "esp32s3/rom/sha.h" +typedef SHA_TYPE esp_sha_type; +#elif CONFIG_IDF_TARGET_ESP32C3 +#include "esp32c3/rom/sha.h" +typedef SHA_TYPE esp_sha_type; +#endif + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_hal.h new file mode 100644 index 00000000..4deeec9b --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_hal.h @@ -0,0 +1,71 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for SIGMADELTA. +// There is no parameter check in the hal layer, so the caller must ensure the correctness of the parameters. + +#pragma once + +#include "soc/sigmadelta_periph.h" +#include "hal/sigmadelta_types.h" +#include "hal/sigmadelta_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * Context that should be maintained by both the driver and the HAL + */ + +typedef struct { + gpio_sd_dev_t *dev; +} sigmadelta_hal_context_t; + +/** + * @brief Set Sigma-delta channel duty. + * + * @param hal Context of the HAL layer + * @param channel Sigma-delta channel number + * @param duty Sigma-delta duty of one channel, the value ranges from -128 to 127, recommended range is -90 ~ 90. + * The waveform is more like a random one in this range. + */ +#define sigmadelta_hal_set_duty(hal, channel, duty) sigmadelta_ll_set_duty((hal)->dev, channel, duty) + +/** + * @brief Set Sigma-delta channel's clock pre-scale value. + * + * @param hal Context of the HAL layer + * @param channel Sigma-delta channel number + * @param prescale The divider of source clock, ranges from 0 to 255 + */ +#define sigmadelta_hal_set_prescale(hal, channel, prescale) sigmadelta_ll_set_prescale((hal)->dev, channel, prescale) + +/** + * @brief Init the SIGMADELTA hal and set the SIGMADELTA to the default configuration. This function should be called first before other hal layer function is called + * + * @param hal Context of the HAL layer + * @param sigmadelta_num The uart port number, the max port number is (SIGMADELTA_NUM_MAX -1) + */ +void sigmadelta_hal_init(sigmadelta_hal_context_t *hal, int sigmadelta_num); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_types.h b/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_types.h new file mode 100644 index 00000000..81023905 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/sigmadelta_types.h @@ -0,0 +1,62 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "soc/soc_caps.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief SIGMADELTA port number, the max port number is (SIGMADELTA_NUM_MAX -1). + */ +typedef enum { + SIGMADELTA_PORT_0, /*!< SIGMADELTA port 0 */ + SIGMADELTA_PORT_MAX, /*!< SIGMADELTA port max */ +} sigmadelta_port_t; + +_Static_assert(SIGMADELTA_PORT_MAX == SOC_SIGMADELTA_NUM, "Sigma-delta port num incorrect."); + +/** + * @brief Sigma-delta channel list + */ +typedef enum { + SIGMADELTA_CHANNEL_0, /*!< Sigma-delta channel 0 */ + SIGMADELTA_CHANNEL_1, /*!< Sigma-delta channel 1 */ + SIGMADELTA_CHANNEL_2, /*!< Sigma-delta channel 2 */ + SIGMADELTA_CHANNEL_3, /*!< Sigma-delta channel 3 */ +#if SOC_SIGMADELTA_CHANNEL_NUM > 4 + SIGMADELTA_CHANNEL_4, /*!< Sigma-delta channel 4 */ + SIGMADELTA_CHANNEL_5, /*!< Sigma-delta channel 5 */ + SIGMADELTA_CHANNEL_6, /*!< Sigma-delta channel 6 */ + SIGMADELTA_CHANNEL_7, /*!< Sigma-delta channel 7 */ +#endif + SIGMADELTA_CHANNEL_MAX, /*!< Sigma-delta channel max */ +} sigmadelta_channel_t; + +/** + * @brief Sigma-delta configure struct + */ +typedef struct { + sigmadelta_channel_t channel; /*!< Sigma-delta channel number */ + int8_t sigmadelta_duty; /*!< Sigma-delta duty, duty ranges from -128 to 127. */ + uint8_t sigmadelta_prescale; /*!< Sigma-delta prescale, prescale ranges from 0 to 255. */ + uint8_t sigmadelta_gpio; /*!< Sigma-delta output io number, refer to gpio.h for more details. */ +} sigmadelta_config_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/soc_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/soc_hal.h new file mode 100644 index 00000000..f39cf49f --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/soc_hal.h @@ -0,0 +1,75 @@ +// Copyright 2020 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. + +#pragma once + +#include +#include + +#include "esp_err.h" + +#include "soc/soc_caps.h" +#include "hal/cpu_hal.h" +#include "hal/soc_ll.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if SOC_CPU_CORES_NUM > 1 +// Utility functions for multicore targets +#define __SOC_HAL_PERFORM_ON_OTHER_CORES(action) { \ + for (uint32_t i = 0, cur = cpu_hal_get_core_id(); i < SOC_CPU_CORES_NUM; i++) { \ + if (i != cur) { \ + action(i); \ + } \ + } \ + } + +#define SOC_HAL_STALL_OTHER_CORES() __SOC_HAL_PERFORM_ON_OTHER_CORES(soc_hal_stall_core); +#define SOC_HAL_UNSTALL_OTHER_CORES() __SOC_HAL_PERFORM_ON_OTHER_CORES(soc_hal_unstall_core); +#define SOC_HAL_RESET_OTHER_CORES() __SOC_HAL_PERFORM_ON_OTHER_CORES(soc_hal_reset_core); + +/** + * Stall the specified CPU core. + * + * @note Has no effect if the core is already stalled - does not return an + * ESP_ERR_INVALID_STATE. + * + * @param core core to stall [0..SOC_CPU_CORES_NUM - 1] + */ +void soc_hal_stall_core(int core); + +/** + * Unstall the specified CPU core. + * + * @note Has no effect if the core is already unstalled - does not return an + * ESP_ERR_INVALID_STATE. + * + * @param core core to unstall [0..SOC_CPU_CORES_NUM - 1] + */ +void soc_hal_unstall_core(int core); + +#endif // SOC_CPU_CORES_NUM > 1 + +/** + * Reset the specified core. + * + * @param core core to reset [0..SOC_CPU_CORES_NUM - 1] + */ +#define soc_hal_reset_core(core) soc_ll_reset_core((core)) + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_hal.h new file mode 100644 index 00000000..51226891 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_hal.h @@ -0,0 +1,258 @@ +// Copyright 2010-2019 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. + +/******************************************************************************* + * NOTICE + * The HAL is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for SPI Flash (common part) + +#pragma once + +#include "hal/spi_flash_ll.h" +#include "hal/spi_types.h" +#include "hal/spi_flash_types.h" +#include "soc/soc_memory_layout.h" + +/* Hardware host-specific constants */ +#define SPI_FLASH_HAL_MAX_WRITE_BYTES 64 +#define SPI_FLASH_HAL_MAX_READ_BYTES 64 + +/** + * Generic driver context structure for all chips using the SPI peripheral. + * Include this into the HEAD of the driver data for other driver + * implementations that also use the SPI peripheral. + */ +typedef struct { + spi_flash_host_inst_t inst; ///< Host instance, containing host data and function pointer table. May update with the host (hardware version). + spi_dev_t *spi; ///< Pointer to SPI peripheral registers (SP1, SPI2 or SPI3). Set before initialisation. + int cs_num; ///< Which cs pin is used, 0-2. + struct { + uint8_t extra_dummy; ///< Pre-calculated extra dummy used for compensation + uint8_t reserved1; ///< Reserved, set to 0. + uint8_t cs_hold; ///< CS hold time config used by the host + uint8_t reserved2; ///< Reserved, set to 0. + }; + spi_flash_ll_clock_reg_t clock_conf; ///< Pre-calculated clock configuration value + esp_flash_io_mode_t base_io_mode; ///< Default IO mode mask for common commands + uint32_t flags; ///< Flags for configurations with one set of driver code. (e.g. QPI mode, auto-suspend mode, 64-bit address mode, etc.) +#define SPI_FLASH_HOST_CONTEXT_FLAG_AUTO_SUSPEND BIT(0) ///< When the auto-suspend is setup in configuration. +#define SPI_FLASH_HOST_CONTEXT_FLAG_AUTO_RESUME BIT(1) ///< Setup auto-resume feature. + spi_flash_sus_cmd_conf sus_cfg; ///< To store suspend command/mask information. +} spi_flash_hal_context_t; +_Static_assert(sizeof(spi_flash_hal_context_t) == 36, "size of spi_flash_hal_context_t incorrect. Please check data compatibility with the ROM"); + +/// Configuration structure for the SPI driver. +typedef struct { + spi_host_device_t host_id; ///< SPI peripheral ID. + int cs_num; ///< Which cs pin is used, 0-(SOC_SPI_PERIPH_CS_NUM-1). + bool iomux; ///< Whether the IOMUX is used, used for timing compensation. + int input_delay_ns; ///< Input delay on the MISO pin after the launch clock, used for timing compensation. + esp_flash_speed_t speed;///< SPI flash clock speed to work at. + uint32_t cs_hold; ///< CS hold time config used by the host + bool auto_sus_en; ///< Auto suspend feature enable bit 1: enable, 0: disable. +} spi_flash_hal_config_t; + +/** + * Configure SPI flash hal settings. + * + * @param data Buffer to hold configured data, the buffer should be in DRAM to be available when cache disabled + * @param cfg Configurations to set + * + * @return + * - ESP_OK: success + * - ESP_ERR_INVALID_ARG: the data buffer is not in the DRAM. + */ +esp_err_t spi_flash_hal_init(spi_flash_hal_context_t *data_out, const spi_flash_hal_config_t *cfg); + +/** + * Configure the device-related register before transactions. + * + * @param host The driver context. + * + * @return always return ESP_OK. + */ +esp_err_t spi_flash_hal_device_config(spi_flash_host_inst_t *host); + +/** + * Send an user-defined spi transaction to the device. + * + * @note This is usually used when the memspi interface doesn't support some + * particular commands. Since this function supports timing compensation, it is + * also used to receive some data when the frequency is high. + * + * @param host The driver context. + * @param trans The transaction to send, also holds the received data. + * + * @return always return ESP_OK. + */ +esp_err_t spi_flash_hal_common_command(spi_flash_host_inst_t *host, spi_flash_trans_t *trans); + +/** + * Erase whole flash chip by using the erase chip (C7h) command. + * + * @param host The driver context. + */ +void spi_flash_hal_erase_chip(spi_flash_host_inst_t *host); + +/** + * Erase a specific sector by its start address through the sector erase (20h) + * command. For 24bit address only. + * + * @param host The driver context. + * @param start_address Start address of the sector to erase. + */ +void spi_flash_hal_erase_sector(spi_flash_host_inst_t *host, uint32_t start_address); + +/** + * Erase a specific 64KB block by its start address through the 64KB block + * erase (D8h) command. For 24bit address only. + * + * @param host The driver context. + * @param start_address Start address of the block to erase. + */ +void spi_flash_hal_erase_block(spi_flash_host_inst_t *host, uint32_t start_address); + +/** + * Program a page of the flash using the page program (02h) command. For 24bit address only. + * + * @param host The driver context. + * @param address Address of the page to program + * @param buffer Data to program + * @param length Size of the buffer in bytes, no larger than ``SPI_FLASH_HAL_MAX_WRITE_BYTES`` (64) bytes. + */ +void spi_flash_hal_program_page(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length); + +/** + * Read from the flash. Call ``spi_flash_hal_configure_host_read_mode`` to + * configure the read command before calling this function. + * + * @param host The driver context. + * @param buffer Buffer to store the read data + * @param address Address to read + * @param length Length to read, no larger than ``SPI_FLASH_HAL_MAX_READ_BYTES`` (64) bytes. + * + * @return always return ESP_OK. + */ +esp_err_t spi_flash_hal_read(spi_flash_host_inst_t *host, void *buffer, uint32_t address, uint32_t read_len); + +/** + * @brief Send the write enable (06h) or write disable (04h) command to the flash chip. + * + * @param driver The driver context. + * @param wp true to enable the write protection, otherwise false. + * + * @return always return ESP_OK. + */ +esp_err_t spi_flash_hal_set_write_protect(spi_flash_host_inst_t *host, bool wp); + +/** + * Check whether the SPI host is idle and can perform other operations. + * + * @param host The driver context. + * + * @return 0:busy, 1:idle, 2:suspended. + */ +uint32_t spi_flash_hal_check_status(spi_flash_host_inst_t *host); + +/** + * @brief Configure the SPI host hardware registers for the specified io mode. + * + * Note that calling this configures SPI host registers, so if running any + * other commands as part of set_io_mode() then these must be run before + * calling this function. + * + * The command value, address length and dummy cycles are configured according + * to the format of read commands: + * + * - command: 8 bits, value set. + * - address: 24 bits + * - dummy: cycles to compensate the input delay + * - out & in data: 0 bits. + * + * The following commands still need to: + * + * - Read data: set address value and data (length and contents), no need + * to touch command and dummy phases. + * - Common read: set command value, address value (or length to 0 if not used) + * - Common write: set command value, address value (or length to 0 if not + * used), disable dummy phase, and set output data. + * + * @param host The driver context + * @param io_mode The HW read mode to use + * @param addr_bitlen Length of the address phase, in bits + * @param dummy_cyclelen_base Base cycles of the dummy phase, some extra dummy cycles may be appended to compensate the timing. + * @param command Actual reading command to send to flash chip on the bus. + * + * @return always return ESP_OK. + */ +esp_err_t spi_flash_hal_configure_host_io_mode(spi_flash_host_inst_t *host, uint32_t command, uint32_t addr_bitlen, + int dummy_cyclelen_base, esp_flash_io_mode_t io_mode); + +/** + * Poll until the last operation is done. + * + * @param host The driver context. + */ +void spi_flash_hal_poll_cmd_done(spi_flash_host_inst_t *host); + +/** + * Check whether the given buffer can be used as the write buffer directly. If 'chip' is connected to the main SPI bus, we can only write directly from + * regions that are accessible ith cache disabled. * + * + * @param host The driver context + * @param p The buffer holding data to send. + * + * @return True if the buffer can be used to send data, otherwise false. + */ +bool spi_flash_hal_supports_direct_write(spi_flash_host_inst_t *host, const void *p); + +/** + * Check whether the given buffer can be used as the read buffer directly. If 'chip' is connected to the main SPI bus, we can only read directly from + * regions that are accessible ith cache disabled. * + * + * @param host The driver context + * @param p The buffer to hold the received data. + * + * @return True if the buffer can be used to receive data, otherwise false. + */ +bool spi_flash_hal_supports_direct_read(spi_flash_host_inst_t *host, const void *p); + +/** + * @brief Resume flash chip status from suspend. + * + * @param host The driver context. + * + */ +void spi_flash_hal_resume(spi_flash_host_inst_t *host); + +/** + * @brief Set the flash into suspend status manually. + * + * @param host The driver context. + * + */ +void spi_flash_hal_suspend(spi_flash_host_inst_t *host); + +/** + * To setup for reading flash suspend status register + * + * @param host The driver context. + * @param sus_conf Flash chip suspend feature configuration, mainly for command config, may vary from chip to chip. + * + * @return Always ESP_OK + */ +esp_err_t spi_flash_hal_setup_read_suspend(spi_flash_host_inst_t *host, const spi_flash_sus_cmd_conf *sus_conf); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_types.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_types.h new file mode 100644 index 00000000..ed68d24f --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_flash_types.h @@ -0,0 +1,215 @@ +// Copyright 2010-2019 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. + +#pragma once + +#include +#include +#include "esp_flash_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** Definition of a common transaction. Also holds the return value. */ +typedef struct { + uint8_t reserved; ///< Reserved, must be 0. + uint8_t mosi_len; ///< Output data length, in bytes + uint8_t miso_len; ///< Input data length, in bytes + uint8_t address_bitlen; ///< Length of address in bits, set to 0 if command does not need an address + uint32_t address; ///< Address to perform operation on + const uint8_t *mosi_data; ///< Output data to salve + uint8_t *miso_data; ///< [out] Input data from slave, little endian + uint32_t flags; ///< Flags for this transaction. Set to 0 for now. +#define SPI_FLASH_TRANS_FLAG_CMD16 BIT(0) ///< Send command of 16 bits +#define SPI_FLASH_TRANS_FLAG_IGNORE_BASEIO BIT(1) ///< Not applying the basic io mode configuration for this transaction +#define SPI_FLASH_TRANS_FLAG_BYTE_SWAP BIT(2) ///< Used for DTR mode, to swap the bytes of a pair of rising/falling edge + uint16_t command; ///< Command to send + uint8_t dummy_bitlen; ///< Basic dummy bits to use +} spi_flash_trans_t; + +/** + * @brief SPI flash clock speed values, always refer to them by the enum rather + * than the actual value (more speed may be appended into the list). + * + * A strategy to select the maximum allowed speed is to enumerate from the + * ``ESP_FLSH_SPEED_MAX-1`` or highest frequency supported by your flash, and + * decrease the speed until the probing success. + */ +typedef enum { + ESP_FLASH_5MHZ = 0, ///< The flash runs under 5MHz + ESP_FLASH_10MHZ, ///< The flash runs under 10MHz + ESP_FLASH_20MHZ, ///< The flash runs under 20MHz + ESP_FLASH_26MHZ, ///< The flash runs under 26MHz + ESP_FLASH_40MHZ, ///< The flash runs under 40MHz + ESP_FLASH_80MHZ, ///< The flash runs under 80MHz + ESP_FLASH_SPEED_MAX, ///< The maximum frequency supported by the host is ``ESP_FLASH_SPEED_MAX-1``. +} esp_flash_speed_t; + +///Lowest speed supported by the driver, currently 5 MHz +#define ESP_FLASH_SPEED_MIN ESP_FLASH_5MHZ + +// These bits are not quite like "IO mode", but are able to be appended into the io mode and used by the HAL. +#define SPI_FLASH_CONFIG_CONF_BITS BIT(31) ///< OR the io_mode with this mask, to enable the dummy output feature or replace the first several dummy bits into address to meet the requirements of conf bits. (Used in DIO/QIO/OIO mode) + +/** @brief Mode used for reading from SPI flash */ +typedef enum { + SPI_FLASH_SLOWRD = 0, ///< Data read using single I/O, some limits on speed + SPI_FLASH_FASTRD, ///< Data read using single I/O, no limit on speed + SPI_FLASH_DOUT, ///< Data read using dual I/O + SPI_FLASH_DIO, ///< Both address & data transferred using dual I/O + SPI_FLASH_QOUT, ///< Data read using quad I/O + SPI_FLASH_QIO, ///< Both address & data transferred using quad I/O + + SPI_FLASH_READ_MODE_MAX, ///< The fastest io mode supported by the host is ``ESP_FLASH_READ_MODE_MAX-1``. +} esp_flash_io_mode_t; + +/// Configuration structure for the flash chip suspend feature. +typedef struct { + uint32_t sus_mask; ///< SUS/SUS1/SUS2 bit in flash register. + struct { + uint32_t cmd_rdsr :8; ///< Read flash status register(2) command. + uint32_t sus_cmd :8; ///< Flash suspend command. + uint32_t res_cmd :8; ///< Flash resume command. + uint32_t reserved :8; ///< Reserved, set to 0. + }; +} spi_flash_sus_cmd_conf; + +///Slowest io mode supported by ESP32, currently SlowRd +#define SPI_FLASH_READ_MODE_MIN SPI_FLASH_SLOWRD + +struct spi_flash_host_driver_s; +typedef struct spi_flash_host_driver_s spi_flash_host_driver_t; + +/** SPI Flash Host driver instance */ +typedef struct { + const struct spi_flash_host_driver_s* driver; ///< Pointer to the implementation function table + // Implementations can wrap this structure into their own ones, and append other data here +} spi_flash_host_inst_t ; + + +/** Host driver configuration and context structure. */ +struct spi_flash_host_driver_s { + /** + * Configure the device-related register before transactions. This saves + * some time to re-configure those registers when we send continuously + */ + esp_err_t (*dev_config)(spi_flash_host_inst_t *host); + /** + * Send an user-defined spi transaction to the device. + */ + esp_err_t (*common_command)(spi_flash_host_inst_t *host, spi_flash_trans_t *t); + /** + * Read flash ID. + */ + esp_err_t (*read_id)(spi_flash_host_inst_t *host, uint32_t *id); + /** + * Erase whole flash chip. + */ + void (*erase_chip)(spi_flash_host_inst_t *host); + /** + * Erase a specific sector by its start address. + */ + void (*erase_sector)(spi_flash_host_inst_t *host, uint32_t start_address); + /** + * Erase a specific block by its start address. + */ + void (*erase_block)(spi_flash_host_inst_t *host, uint32_t start_address); + /** + * Read the status of the flash chip. + */ + esp_err_t (*read_status)(spi_flash_host_inst_t *host, uint8_t *out_sr); + /** + * Disable write protection. + */ + esp_err_t (*set_write_protect)(spi_flash_host_inst_t *host, bool wp); + /** + * Program a page of the flash. Check ``max_write_bytes`` for the maximum allowed writing length. + */ + void (*program_page)(spi_flash_host_inst_t *host, const void *buffer, uint32_t address, uint32_t length); + /** Check whether given buffer can be directly used to write */ + bool (*supports_direct_write)(spi_flash_host_inst_t *host, const void *p); + /** + * Slicer for write data. The `program_page` should be called iteratively with the return value + * of this function. + * + * @param address Beginning flash address to write + * @param len Length request to write + * @param align_addr Output of the aligned address to write to + * @param page_size Physical page size of the flash chip + * @return Length that can be actually written in one `program_page` call + */ + int (*write_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, + uint32_t page_size); + /** + * Read data from the flash. Check ``max_read_bytes`` for the maximum allowed reading length. + */ + esp_err_t (*read)(spi_flash_host_inst_t *host, void *buffer, uint32_t address, uint32_t read_len); + /** Check whether given buffer can be directly used to read */ + bool (*supports_direct_read)(spi_flash_host_inst_t *host, const void *p); + /** + * Slicer for read data. The `read` should be called iteratively with the return value + * of this function. + * + * @param address Beginning flash address to read + * @param len Length request to read + * @param align_addr Output of the aligned address to read + * @param page_size Physical page size of the flash chip + * @return Length that can be actually read in one `read` call + */ + int (*read_data_slicer)(spi_flash_host_inst_t *host, uint32_t address, uint32_t len, uint32_t *align_addr, uint32_t page_size); + /** + * Check the host status, 0:busy, 1:idle, 2:suspended. + */ + uint32_t (*host_status)(spi_flash_host_inst_t *host); + /** + * Configure the host to work at different read mode. Responsible to compensate the timing and set IO mode. + */ + esp_err_t (*configure_host_io_mode)(spi_flash_host_inst_t *host, uint32_t command, + uint32_t addr_bitlen, int dummy_bitlen_base, + esp_flash_io_mode_t io_mode); + /** + * Internal use, poll the HW until the last operation is done. + */ + void (*poll_cmd_done)(spi_flash_host_inst_t *host); + /** + * For some host (SPI1), they are shared with a cache. When the data is + * modified, the cache needs to be flushed. Left NULL if not supported. + */ + esp_err_t (*flush_cache)(spi_flash_host_inst_t* host, uint32_t addr, uint32_t size); + + /** + * Suspend check erase/program operation, reserved for ESP32-C3 and ESP32-S3 spi flash ROM IMPL. + */ + void (*check_suspend)(spi_flash_host_inst_t *host); + + /** + * Resume flash from suspend manually + */ + void (*resume)(spi_flash_host_inst_t *host); + + /** + * Set flash in suspend status manually + */ + void (*suspend)(spi_flash_host_inst_t *host); + + /** + * Suspend feature setup for setting cmd and status register mask. + */ + esp_err_t (*sus_setup)(spi_flash_host_inst_t *host, const spi_flash_sus_cmd_conf *sus_conf); +}; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_hal.h new file mode 100644 index 00000000..ec23ee0d --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_hal.h @@ -0,0 +1,269 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for SPI master (common part) + +// SPI HAL usages: +// 1. initialize the bus +// 2. initialize the DMA descriptors if DMA used +// 3. setup the clock speed (since this takes long time) +// 4. call setup_device to update parameters for the specific device +// 5. call setup_trans to update parameters for the specific transaction +// 6. prepare data to send, and prepare the receiving buffer +// 7. trigger user defined SPI transaction to start +// 8. wait until the user transaction is done +// 9. fetch the received data +// Parameter to be updated only during ``setup_device`` will be highlighted in the +// field comments. + +#pragma once +#include "hal/spi_ll.h" +#include +#include "soc/lldesc.h" +#include "soc/soc_caps.h" + +/** + * Input parameters to the ``spi_hal_cal_clock_conf`` to calculate the timing configuration + */ +typedef struct { + uint32_t half_duplex; ///< Whether half duplex mode is used, device specific + uint32_t no_compensate; ///< No need to add dummy to compensate the timing, device specific + uint32_t clock_speed_hz; ///< Desired frequency. + uint32_t duty_cycle; ///< Desired duty cycle of SPI clock + uint32_t input_delay_ns; /**< Maximum delay between SPI launch clock and the data to be valid. + * This is used to compensate/calculate the maximum frequency allowed. + * Left 0 if not known. + */ + bool use_gpio; ///< True if the GPIO matrix is used, otherwise false +} spi_hal_timing_param_t; + +/** + * Timing configuration structure that should be calculated by + * ``spi_hal_cal_clock_conf`` at initialization and hold. Filled into the + * ``timing_conf`` member of the context of HAL before setup a device. + */ +typedef struct { + spi_ll_clock_val_t clock_reg; ///< Register value used by the LL layer + int timing_dummy; ///< Extra dummy needed to compensate the timing + int timing_miso_delay; ///< Extra miso delay clocks to compensate the timing +} spi_hal_timing_conf_t; + +/** + * DMA configuration structure + * Should be set by driver at initialization + */ +typedef struct { + spi_dma_dev_t *dma_in; ///< Input DMA(DMA -> RAM) peripheral register address + spi_dma_dev_t *dma_out; ///< Output DMA(RAM -> DMA) peripheral register address + bool dma_enabled; ///< Whether the DMA is enabled, do not update after initialization + lldesc_t *dmadesc_tx; /**< Array of DMA descriptor used by the TX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + lldesc_t *dmadesc_rx; /**< Array of DMA descriptor used by the RX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + uint32_t tx_dma_chan; ///< TX DMA channel + uint32_t rx_dma_chan; ///< RX DMA channel + int dmadesc_n; ///< The amount of descriptors of both ``dmadesc_tx`` and ``dmadesc_rx`` that the HAL can use. +} spi_hal_config_t; + +/** + * Transaction configuration structure, this should be assigned by driver each time. + * All these parameters will be updated to the peripheral every transaction. + */ +typedef struct { + uint16_t cmd; ///< Command value to be sent + int cmd_bits; ///< Length (in bits) of the command phase + int addr_bits; ///< Length (in bits) of the address phase + int dummy_bits; ///< Base length (in bits) of the dummy phase. Note when the compensation is enabled, some extra dummy bits may be appended. + int tx_bitlen; ///< TX length, in bits + int rx_bitlen; ///< RX length, in bits + uint64_t addr; ///< Address value to be sent + uint8_t *send_buffer; ///< Data to be sent + uint8_t *rcv_buffer; ///< Buffer to hold the receive data. + spi_ll_io_mode_t io_mode; ///< IO mode of the master +} spi_hal_trans_config_t; + +/** + * Context that should be maintained by both the driver and the HAL. + */ +typedef struct { + /* These two need to be malloced by the driver first */ + lldesc_t *dmadesc_tx; /**< Array of DMA descriptor used by the TX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + lldesc_t *dmadesc_rx; /**< Array of DMA descriptor used by the RX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + + /* Configured by driver at initialization, don't touch */ + spi_dev_t *hw; ///< Beginning address of the peripheral registers. + spi_dma_dev_t *dma_in; ///< Address of the DMA peripheral registers which stores the data received from a peripheral into RAM (DMA -> RAM). + spi_dma_dev_t *dma_out; ///< Address of the DMA peripheral registers which transmits the data from RAM to a peripheral (RAM -> DMA). + bool dma_enabled; ///< Whether the DMA is enabled, do not update after initialization + uint32_t tx_dma_chan; ///< TX DMA channel + uint32_t rx_dma_chan; ///< RX DMA channel + int dmadesc_n; ///< The amount of descriptors of both ``dmadesc_tx`` and ``dmadesc_rx`` that the HAL can use. + + /* Internal parameters, don't touch */ + spi_hal_trans_config_t trans_config; ///< Transaction configuration +} spi_hal_context_t; + +/** + * Device configuration structure, this should be initialised by driver based on different devices respectively. + * All these parameters will be updated to the peripheral only when ``spi_hal_setup_device``. + * They may not get updated when ``spi_hal_setup_trans``. + */ +typedef struct { + int mode; ///< SPI mode, device specific + int cs_setup; ///< Setup time of CS active edge before the first SPI clock, device specific + int cs_hold; ///< Hold time of CS inactive edge after the last SPI clock, device specific + int cs_pin_id; ///< CS pin to use, 0-2, otherwise all the CS pins are not used. Device specific + spi_hal_timing_conf_t timing_conf; /**< This structure holds the pre-calculated timing configuration for the device + * at initialization, device specific + */ + struct { + uint32_t sio : 1; ///< Whether to use SIO mode, device specific + uint32_t half_duplex : 1; ///< Whether half duplex mode is used, device specific + uint32_t tx_lsbfirst : 1; ///< Whether LSB is sent first for TX data, device specific + uint32_t rx_lsbfirst : 1; ///< Whether LSB is received first for RX data, device specific + uint32_t no_compensate : 1; ///< No need to add dummy to compensate the timing, device specific +#if SOC_SPI_SUPPORT_AS_CS + uint32_t as_cs : 1; ///< Whether to toggle the CS while the clock toggles, device specific +#endif + uint32_t positive_cs : 1; ///< Whether the postive CS feature is abled, device specific + };//boolean configurations +} spi_hal_dev_config_t; + +/** + * Init the peripheral and the context. + * + * @param hal Context of the HAL layer. + * @param host_id Index of the SPI peripheral. 0 for SPI1, 1 for HSPI (SPI2) and 2 for VSPI (SPI3). + * @param hal_config Configuration of the hal defined by the upper layer. + */ +void spi_hal_init(spi_hal_context_t *hal, uint32_t host_id, const spi_hal_config_t *hal_config); + +/** + * Deinit the peripheral (and the context if needed). + * + * @param hal Context of the HAL layer. + */ +void spi_hal_deinit(spi_hal_context_t *hal); + +/** + * Setup device-related configurations according to the settings in the context. + * + * @param hal Context of the HAL layer. + * @param hal_dev Device configuration + */ +void spi_hal_setup_device(spi_hal_context_t *hal, const spi_hal_dev_config_t *hal_dev); + +/** + * Setup transaction related configurations according to the settings in the context. + * + * @param hal Context of the HAL layer. + * @param hal_dev Device configuration + * @param hal_trans Transaction configuration + */ +void spi_hal_setup_trans(spi_hal_context_t *hal, const spi_hal_dev_config_t *hal_dev, const spi_hal_trans_config_t *hal_trans); + +/** + * Prepare the data for the current transaction. + * + * @param hal Context of the HAL layer. + * @param hal_dev Device configuration + * @param hal_trans Transaction configuration + */ +void spi_hal_prepare_data(spi_hal_context_t *hal, const spi_hal_dev_config_t *hal_dev, const spi_hal_trans_config_t *hal_trans); + +/** + * Trigger start a user-defined transaction. + * + * @param hal Context of the HAL layer. + */ +void spi_hal_user_start(const spi_hal_context_t *hal); + +/** + * Check whether the transaction is done (trans_done is set). + * + * @param hal Context of the HAL layer. + */ +bool spi_hal_usr_is_done(const spi_hal_context_t *hal); + +/** + * Post transaction operations, mainly fetch data from the buffer. + * + * @param hal Context of the HAL layer. + */ +void spi_hal_fetch_result(const spi_hal_context_t *hal); + +/*---------------------------------------------------------- + * Utils + * ---------------------------------------------------------*/ +/** + * Calculate the configuration of clock and timing. The configuration will be used when ``spi_hal_setup_device``. + * + * It is highly suggested to do this at initialization, since it takes long time. + * + * @param timing_param Input parameters to calculate timing configuration + * @param out_freq Output of the actual frequency, left NULL if not required. + * @param timing_conf Output of the timing configuration. + * + * @return ESP_OK if desired is available, otherwise fail. + */ +esp_err_t spi_hal_cal_clock_conf(const spi_hal_timing_param_t *timing_param, int *out_freq, spi_hal_timing_conf_t *timing_conf); + +/** + * Get the frequency actual used. + * + * @param hal Context of the HAL layer. + * @param fapb APB clock frequency. + * @param hz Desired frequencyc. + * @param duty_cycle Desired duty cycle. + */ +int spi_hal_master_cal_clock(int fapb, int hz, int duty_cycle); + +/** + * Get the timing configuration for given parameters. + * + * @param eff_clk Actual SPI clock frequency + * @param gpio_is_used true if the GPIO matrix is used, otherwise false. + * @param input_delay_ns Maximum delay between SPI launch clock and the data to + * be valid. This is used to compensate/calculate the maximum frequency + * allowed. Left 0 if not known. + * @param dummy_n Dummy cycles required to correctly read the data. + * @param miso_delay_n suggested delay on the MISO line, in APB clocks. + */ +void spi_hal_cal_timing(int eff_clk, bool gpio_is_used, int input_delay_ns, int *dummy_n, int *miso_delay_n); + +/** + * Get the maximum frequency allowed to read if no compensation is used. + * + * @param gpio_is_used true if the GPIO matrix is used, otherwise false. + * @param input_delay_ns Maximum delay between SPI launch clock and the data to + * be valid. This is used to compensate/calculate the maximum frequency + * allowed. Left 0 if not known. + */ +int spi_hal_get_freq_limit(bool gpio_is_used, int input_delay_ns); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hal.h new file mode 100644 index 00000000..ba03c28b --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hal.h @@ -0,0 +1,163 @@ +// Copyright 2015-2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for SPI slave (common part) + +// SPI slave HAL usages: +// 1. initialize the bus +// 2. initialize the DMA descriptors if DMA used +// 3. call setup_device to update parameters for the device +// 4. prepare data to send, and prepare the receiving buffer +// 5. trigger user defined SPI transaction to start +// 6. wait until the user transaction is done +// 7. store the received data and get the length +// 8. check and reset the DMA (if needed) before the next transaction + +#pragma once + +#include +#include "soc/lldesc.h" +#include "soc/spi_struct.h" +#include "soc/soc_caps.h" +#include "hal/spi_ll.h" + +/** + * Context that should be maintained by both the driver and the HAL. + */ +typedef struct { + /* configured by driver at initialization, don't touch */ + spi_dev_t *hw; ///< Beginning address of the peripheral registers. + spi_dma_dev_t *dma_in; ///< Address of the DMA peripheral registers which stores the data received from a peripheral into RAM. + spi_dma_dev_t *dma_out; ///< Address of the DMA peripheral registers which transmits the data from RAM to a peripheral. + /* should be configured by driver at initialization */ + lldesc_t *dmadesc_rx; /**< Array of DMA descriptor used by the TX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + lldesc_t *dmadesc_tx; /**< Array of DMA descriptor used by the RX DMA. + * The amount should be larger than dmadesc_n. The driver should ensure that + * the data to be sent is shorter than the descriptors can hold. + */ + int dmadesc_n; ///< The amount of descriptors of both ``dmadesc_tx`` and ``dmadesc_rx`` that the HAL can use. + uint32_t tx_dma_chan; ///< TX DMA channel + uint32_t rx_dma_chan; ///< RX DMA channel + + /* + * configurations to be filled after ``spi_slave_hal_init``. Updated to + * peripheral registers when ``spi_slave_hal_setup_device`` is called. + */ + struct { + uint32_t rx_lsbfirst : 1; + uint32_t tx_lsbfirst : 1; + uint32_t use_dma : 1; + }; + int mode; + + /* + * Transaction specific (data), all these parameters will be updated to the + * peripheral every transaction. + */ + uint32_t bitlen; ///< Expected maximum length of the transaction, in bits. + const void *tx_buffer; ///< Data to be sent + void *rx_buffer; ///< Buffer to hold the received data. + + /* Other transaction result after one transaction */ + uint32_t rcv_bitlen; ///< Length of the last transaction, in bits. +} spi_slave_hal_context_t; + +typedef struct { + uint32_t host_id; ///< SPI controller ID + spi_dma_dev_t *dma_in; ///< Input DMA(DMA -> RAM) peripheral register address + spi_dma_dev_t *dma_out; ///< Output DMA(RAM -> DMA) peripheral register address +} spi_slave_hal_config_t; + +/** + * Init the peripheral and the context. + * + * @param hal Context of the HAL layer. + * @param host_id Index of the SPI peripheral. 0 for SPI1, 1 for HSPI (SPI2) and 2 for VSPI (SPI3). + */ +void spi_slave_hal_init(spi_slave_hal_context_t *hal, const spi_slave_hal_config_t *hal_config); + +/** + * Deinit the peripheral (and the context if needed). + * + * @param hal Context of the HAL layer. + */ +void spi_slave_hal_deinit(spi_slave_hal_context_t *hal); + +/** + * Setup device-related configurations according to the settings in the context. + * + * @param hal Context of the HAL layer. + */ +void spi_slave_hal_setup_device(const spi_slave_hal_context_t *hal); + +/** + * Prepare the data for the current transaction. + * + * @param hal Context of the HAL layer. + */ +void spi_slave_hal_prepare_data(const spi_slave_hal_context_t *hal); + +/** + * Trigger start a user-defined transaction. + * + * @param hal Context of the HAL layer. + */ +void spi_slave_hal_user_start(const spi_slave_hal_context_t *hal); + +/** + * Check whether the transaction is done (trans_done is set). + * + * @param hal Context of the HAL layer. + */ +bool spi_slave_hal_usr_is_done(spi_slave_hal_context_t* hal); + +/** + * Post transaction operations, fetch data from the buffer and recored the length. + * + * @param hal Context of the HAL layer. + */ +void spi_slave_hal_store_result(spi_slave_hal_context_t *hal); + +/** + * Get the length of last transaction, in bits. Should be called after ``spi_slave_hal_store_result``. + * + * Note that if last transaction is longer than configured before, the return + * value will be truncated to the configured length. + * + * @param hal Context of the HAL layer. + * + * @return Length of the last transaction, in bits. + */ +uint32_t spi_slave_hal_get_rcv_bitlen(spi_slave_hal_context_t *hal); + +/** + * Check whether we need to reset the DMA according to the status of last transactions. + * + * In ESP32, sometimes we may need to reset the DMA for the slave before the + * next transaction. Call this to check it. + * + * @param hal Context of the HAL layer. + * + * @return true if reset is needed, else false. + */ +bool spi_slave_hal_dma_need_reset(const spi_slave_hal_context_t *hal); diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hd_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hd_hal.h new file mode 100644 index 00000000..099139cc --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_slave_hd_hal.h @@ -0,0 +1,318 @@ +// Copyright 2015-2020 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +/* + * The HAL layer for SPI Slave HD mode. + * + * Usage (segment mode): + * - Firstly, initialize the slave with `spi_slave_hd_hal_init` + * + * - Event handling: + * - (Optional) Call ``spi_slave_hd_hal_enable_event_intr`` to enable the used interrupts + * - (Basic) Call ``spi_slave_hd_hal_check_clear_event`` to check whether an event happen, and also + * clear its interrupt. For events: SPI_EV_BUF_TX, SPI_EV_BUF_RX, SPI_EV_BUF_RX, SPI_EV_CMD9, + * SPI_EV_CMDA. + * - (Advanced) Call ``spi_slave_hd_hal_check_disable_event`` to disable the interrupt of an event, + * so that the task can call ``spi_slave_hd_hal_invoke_event_intr`` later to manually invoke the + * ISR. For SPI_EV_SEND, SPI_EV_RECV. + * + * - TXDMA: + * - To send data through DMA, call `spi_slave_hd_hal_txdma` + * - When the operation is done, SPI_EV_SEND will be triggered. + * + * - RXDMA: + * - To receive data through DMA, call `spi_slave_hd_hal_rxdma` + * - When the operation is done, SPI_EV_RECV will be triggered. + * - Call ``spi_slave_hd_hal_rxdma_seg_get_len`` to get the received length + * + * - Shared buffer: + * - Call ``spi_slave_hd_hal_write_buffer`` to write the shared register buffer. When the buffer is + * read by the master (regardless of the read address), SPI_EV_BUF_TX will be triggered + * - Call ``spi_slave_hd_hal_read_buffer`` to read the shared register buffer. When the buffer is + * written by the master (regardless of the written address), SPI_EV_BUF_RX will be triggered. + */ + +#pragma once + +#include +#include "esp_err.h" +#include "hal/spi_ll.h" +#include "hal/spi_types.h" + +/** + * @brief Type of dma descriptor with appended members + * this structure inherits DMA descriptor, with a pointer to the transaction descriptor passed from users. + */ +typedef struct { + lldesc_t desc; ///< DMA descriptor + void *arg; ///< This points to the transaction descriptor user passed in +} spi_slave_hd_hal_desc_append_t; + +/// Configuration of the HAL +typedef struct { + uint32_t host_id; ///< Host ID of the spi peripheral + spi_dma_dev_t *dma_in; ///< Input DMA(DMA -> RAM) peripheral register address + spi_dma_dev_t *dma_out; ///< Output DMA(RAM -> DMA) peripheral register address + bool dma_enabled; ///< DMA enabled or not + uint32_t tx_dma_chan; ///< TX DMA channel used. + uint32_t rx_dma_chan; ///< RX DMA channel used. + bool append_mode; ///< True for DMA append mode, false for segment mode + uint32_t spics_io_num; ///< CS GPIO pin for this device + uint8_t mode; ///< SPI mode (0-3) + uint32_t command_bits; ///< command field bits, multiples of 8 and at least 8. + uint32_t address_bits; ///< address field bits, multiples of 8 and at least 8. + uint32_t dummy_bits; ///< dummy field bits, multiples of 8 and at least 8. + + struct { + uint32_t tx_lsbfirst : 1; ///< Whether TX data should be sent with LSB first. + uint32_t rx_lsbfirst : 1; ///< Whether RX data should be read with LSB first. + }; +} spi_slave_hd_hal_config_t; + +/// Context of the HAL, initialized by :cpp:func:`spi_slave_hd_hal_init`. +typedef struct { + /* These two need to be malloced by the driver first */ + spi_slave_hd_hal_desc_append_t *dmadesc_tx; ///< Head of the TX DMA descriptors. + spi_slave_hd_hal_desc_append_t *dmadesc_rx; ///< Head of the RX DMA descriptors. + + /* address of the hardware */ + spi_dev_t *dev; ///< Beginning address of the peripheral registers. + spi_dma_dev_t *dma_in; ///< Address of the DMA peripheral registers which stores the data received from a peripheral into RAM. + spi_dma_dev_t *dma_out; ///< Address of the DMA peripheral registers which transmits the data from RAM to a peripheral. + bool dma_enabled; ///< DMA enabled or not + uint32_t tx_dma_chan; ///< TX DMA channel used. + uint32_t rx_dma_chan; ///< RX DMA channel used. + bool append_mode; ///< True for DMA append mode, false for segment mode + uint32_t dma_desc_num; ///< Number of the available DMA descriptors. Calculated from ``bus_max_transfer_size``. + spi_slave_hd_hal_desc_append_t *tx_cur_desc; ///< Current TX DMA descriptor that could be linked (set up). + spi_slave_hd_hal_desc_append_t *tx_dma_head; ///< Head of the linked TX DMA descriptors which are not used by hardware + spi_slave_hd_hal_desc_append_t *tx_dma_tail; ///< Tail of the linked TX DMA descriptors which are not used by hardware + spi_slave_hd_hal_desc_append_t tx_dummy_head; ///< Dummy descriptor for ``tx_dma_head`` to start + uint32_t tx_used_desc_cnt; ///< Number of the TX descriptors that have been setup + uint32_t tx_recycled_desc_cnt; ///< Number of the TX descriptors that could be recycled + spi_slave_hd_hal_desc_append_t *rx_cur_desc; ///< Current RX DMA descriptor that could be linked (set up). + spi_slave_hd_hal_desc_append_t *rx_dma_head; ///< Head of the linked RX DMA descriptors which are not used by hardware + spi_slave_hd_hal_desc_append_t *rx_dma_tail; ///< Tail of the linked RX DMA descriptors which are not used by hardware + spi_slave_hd_hal_desc_append_t rx_dummy_head; ///< Dummy descriptor for ``rx_dma_head`` to start + uint32_t rx_used_desc_cnt; ///< Number of the RX descriptors that have been setup + uint32_t rx_recycled_desc_cnt; ///< Number of the RX descriptors that could be recycled + + /* Internal status used by the HAL implementation, initialized as 0. */ + uint32_t intr_not_triggered; + bool tx_dma_started; + bool rx_dma_started; +} spi_slave_hd_hal_context_t; + +/** + * @brief Initialize the hardware and part of the context + * + * @param hal Context of the HAL layer + * @param hal_config Configuration of the HAL + */ +void spi_slave_hd_hal_init(spi_slave_hd_hal_context_t *hal, const spi_slave_hd_hal_config_t *hal_config); + +/** + * @brief Get the size of one DMA descriptor + * + * @param hal Context of the HAL layer + * @param bus_size SPI bus maximum transfer size, in bytes. + * @return Total size needed for all the DMA descriptors + */ +uint32_t spi_slave_hd_hal_get_total_desc_size(spi_slave_hd_hal_context_t *hal, uint32_t bus_size); + +/** + * @brief Get the actual bus size + * + * @param hal Context of the HAL layer + * @return Actual bus transaction size + */ +uint32_t spi_salve_hd_hal_get_max_bus_size(spi_slave_hd_hal_context_t *hal); + +/** + * @brief Check and clear signal of one event + * + * @param hal Context of the HAL layer + * @param ev Event to check + * @return True if event triggered, otherwise false + */ +bool spi_slave_hd_hal_check_clear_event(spi_slave_hd_hal_context_t* hal, spi_event_t ev); + +/** + * @brief Check and clear the interrupt of one event. + * + * @note The event source will be kept, so that the interrupt can be invoked by + * :cpp:func:`spi_slave_hd_hal_invoke_event_intr`. If event not triggered, its interrupt source + * will not be disabled either. + * + * @param hal Context of the HAL layer + * @param ev Event to check and disable + * @return True if event triggered, otherwise false + */ +bool spi_slave_hd_hal_check_disable_event(spi_slave_hd_hal_context_t* hal, spi_event_t ev); + +/** + * @brief Enable to invole the ISR of corresponding event. + * + * @note The function, compared with :cpp:func:`spi_slave_hd_hal_enable_event_intr`, contains a + * workaround to force trigger the interrupt, even if the interrupt source cannot be initialized + * correctly. + * + * @param hal Context of the HAL layer + * @param ev Event (reason) to invoke the ISR + */ +void spi_slave_hd_hal_invoke_event_intr(spi_slave_hd_hal_context_t* hal, spi_event_t ev); + +/** + * @brief Enable the interrupt source of corresponding event. + * + * @param hal Context of the HAL layer + * @param ev Event whose corresponding interrupt source should be enabled. + */ +void spi_slave_hd_hal_enable_event_intr(spi_slave_hd_hal_context_t* hal, spi_event_t ev); + +//////////////////////////////////////////////////////////////////////////////// +// RX DMA +//////////////////////////////////////////////////////////////////////////////// +/** + * @brief Start the RX DMA operation to the specified buffer. + * + * @param hal Context of the HAL layer + * @param[out] out_buf Buffer to receive the data + * @param len Maximul length to receive + */ +void spi_slave_hd_hal_rxdma(spi_slave_hd_hal_context_t *hal, uint8_t *out_buf, size_t len); + +/** + * @brief Get the length of total received data + * + * @param hal Context of the HAL layer + * @return The received length + */ +int spi_slave_hd_hal_rxdma_seg_get_len(spi_slave_hd_hal_context_t *hal); + +//////////////////////////////////////////////////////////////////////////////// +// TX DMA +//////////////////////////////////////////////////////////////////////////////// +/** + * @brief Start the TX DMA operation with the specified buffer + * + * @param hal Context of the HAL layer + * @param data Buffer of data to send + * @param len Size of the buffer, also the maximum length to send + */ +void spi_slave_hd_hal_txdma(spi_slave_hd_hal_context_t *hal, uint8_t *data, size_t len); + +//////////////////////////////////////////////////////////////////////////////// +// Shared buffer +//////////////////////////////////////////////////////////////////////////////// +/** + * @brief Read from the shared register buffer + * + * @param hal Context of the HAL layer + * @param addr Address of the shared regsiter to read + * @param out_data Buffer to store the read data + * @param len Length to read from the shared buffer + */ +void spi_slave_hd_hal_read_buffer(spi_slave_hd_hal_context_t *hal, int addr, uint8_t *out_data, size_t len); + +/** + * @brief Write the shared register buffer + * + * @param hal Context of the HAL layer + * @param addr Address of the shared register to write + * @param data Buffer of the data to write + * @param len Length to write into the shared buffer + */ +void spi_slave_hd_hal_write_buffer(spi_slave_hd_hal_context_t *hal, int addr, uint8_t *data, size_t len); + +/** + * @brief Get the length of previous transaction. + * + * @param hal Context of the HAL layer + * @return The length of previous transaction + */ +int spi_slave_hd_hal_get_rxlen(spi_slave_hd_hal_context_t *hal); + +/** + * @brief Get the address of last transaction + * + * @param hal Context of the HAL layer + * @return The address of last transaction + */ +int spi_slave_hd_hal_get_last_addr(spi_slave_hd_hal_context_t *hal); + +#if CONFIG_IDF_TARGET_ESP32S2 +//Append mode is only supported on ESP32S2 now +//////////////////////////////////////////////////////////////////////////////// +// Append Mode +//////////////////////////////////////////////////////////////////////////////// +/** + * @brief Return the finished TX transaction + * + * @note This API is based on this assumption: the hardware behaviour of current transaction completion is only modified by the its own caller layer. + * This means if some other code changed the hardware behaviour (e.g. clear intr raw bit), or the caller call this API without noticing the HW behaviour, + * this API will go wrong. + * + * @param hal Context of the HAL layer + * @param out_trans Pointer to the caller-defined transaction + * @return 1: Transaction is finished; 0: Transaction is not finished + */ +bool spi_slave_hd_hal_get_tx_finished_trans(spi_slave_hd_hal_context_t *hal, void **out_trans); + +/** + * @brief Return the finished RX transaction + * + * @note This API is based on this assumption: the hardware behaviour of current transaction completion is only modified by the its own caller layer. + * This means if some other code changed the hardware behaviour (e.g. clear intr raw bit), or the caller call this API without noticing the HW behaviour, + * this API will go wrong. + * + * @param hal Context of the HAL layer + * @param out_trans Pointer to the caller-defined transaction + * @param out_len Actual number of bytes of received data + * @return 1: Transaction is finished; 0: Transaction is not finished + */ +bool spi_slave_hd_hal_get_rx_finished_trans(spi_slave_hd_hal_context_t *hal, void **out_trans, size_t *out_len); + +/** + * @brief Load the TX DMA descriptors without stopping the DMA + * + * @param hal Context of the HAL layer + * @param data Buffer of the transaction data + * @param len Length of the data + * @param arg Pointer used by the caller to indicate the tranaction. Will be returned by ``spi_slave_hd_hal_get_tx_finished_trans`` when transaction is finished + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_STATE: Function called in invalid state. + */ +esp_err_t spi_slave_hd_hal_txdma_append(spi_slave_hd_hal_context_t *hal, uint8_t *data, size_t len, void *arg); + +/** + * @brief Load the RX DMA descriptors without stopping the DMA + * + * @param hal Context of the HAL layer + * @param data Buffer of the transaction data + * @param len Length of the data + * @param arg Pointer used by the caller to indicate the tranaction. Will be returned by ``spi_slave_hd_hal_get_rx_finished_trans`` when transaction is finished + * @return + * - ESP_OK: on success + * - ESP_ERR_INVALID_STATE: Function called in invalid state. + */ +esp_err_t spi_slave_hd_hal_rxdma_append(spi_slave_hd_hal_context_t *hal, uint8_t *data, size_t len, void *arg); +#endif //#if CONFIG_IDF_TARGET_ESP32S2 diff --git a/tools/sdk/esp32c3/include/hal/include/hal/spi_types.h b/tools/sdk/esp32c3/include/hal/include/hal/spi_types.h new file mode 100644 index 00000000..ebf4e3b3 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/spi_types.h @@ -0,0 +1,64 @@ +// Copyright 2015-2019 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. + +#pragma once + +#include "esp_attr.h" +#include +#include "soc/soc_caps.h" +#include "sdkconfig.h" + +/** + * @brief Enum with the three SPI peripherals that are software-accessible in it + */ +typedef enum { +//SPI1 can be used as GPSPI only on ESP32 + SPI1_HOST=0, ///< SPI1 + SPI2_HOST=1, ///< SPI2 + SPI3_HOST=2, ///< SPI3 +} spi_host_device_t; + +/// SPI Events +typedef enum { + SPI_EV_BUF_TX = BIT(0), ///< The buffer has sent data to master, Slave HD only + SPI_EV_BUF_RX = BIT(1), ///< The buffer has received data from master, Slave HD only + SPI_EV_SEND = BIT(2), ///< Slave has loaded some data to DMA, and master has received certain number of the data, the number is determined by master. Slave HD only + SPI_EV_RECV = BIT(3), ///< Slave has received certain number of data from master, the number is determined by master. Slave HD only. + SPI_EV_CMD9 = BIT(4), ///< Received CMD9 from master, Slave HD only + SPI_EV_CMDA = BIT(5), ///< Received CMDA from master, Slave HD only + SPI_EV_TRANS = BIT(6), ///< A transaction has done +} spi_event_t; +FLAG_ATTR(spi_event_t) + + +/** @cond */ //Doxy command to hide preprocessor definitions from docs */ + +//alias for different chips +#ifdef CONFIG_IDF_TARGET_ESP32 +#define SPI_HOST SPI1_HOST +#define HSPI_HOST SPI2_HOST +#define VSPI_HOST SPI3_HOST +#elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3 +// SPI_HOST (SPI1_HOST) is not supported by the SPI Master and SPI Slave driver on ESP32-S2 and later +#define SPI_HOST SPI1_HOST +#define FSPI_HOST SPI2_HOST +#define HSPI_HOST SPI3_HOST +#elif CONFIG_IDF_TARGET_ESP32C3 +/* No SPI3_host on C3 */ +#define SPI_HOST SPI1_HOST +#define FSPI_HOST SPI2_HOST +#define HSPI_HOST SPI2_HOST +#endif + +/** @endcond */ diff --git a/tools/sdk/esp32c3/include/hal/include/hal/systimer_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/systimer_hal.h new file mode 100644 index 00000000..1f4eb5c4 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/systimer_hal.h @@ -0,0 +1,92 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include "hal/systimer_types.h" + +/** + * @brief enable systimer counter + */ +void systimer_hal_enable_counter(systimer_counter_id_t counter_id); + +/** + * @brief get current counter value + */ +uint64_t systimer_hal_get_counter_value(systimer_counter_id_t counter_id); + +/** + * @brief get current time (in microseconds) + */ +uint64_t systimer_hal_get_time(systimer_counter_id_t counter_id); + +/* + * @brief set alarm target value (used in one-shot mode) + */ +void systimer_hal_set_alarm_target(systimer_alarm_id_t alarm_id, uint64_t target); + +/** + * @brief set alarm period value (used in period mode) + */ +void systimer_hal_set_alarm_period(systimer_alarm_id_t alarm_id, uint32_t period); + +/** + * @brief get alarm time + */ +uint64_t systimer_hal_get_alarm_value(systimer_alarm_id_t alarm_id); + +/** + * @brief enable alarm interrupt + */ +void systimer_hal_enable_alarm_int(systimer_alarm_id_t alarm_id); + +/** + * @brief select alarm mode + */ +void systimer_hal_select_alarm_mode(systimer_alarm_id_t alarm_id, systimer_alarm_mode_t mode); + +/** + * @brief update systimer step when apb clock gets changed + */ +void systimer_hal_on_apb_freq_update(uint32_t apb_ticks_per_us); + +/** + * @brief move systimer counter value forward or backward + */ +void systimer_hal_counter_value_advance(systimer_counter_id_t counter_id, int64_t time_us); + +/** + * @brief initialize systimer in HAL layer + */ +void systimer_hal_init(void); + +/** + * @brief connect alarm unit to selected counter + */ +void systimer_hal_connect_alarm_counter(systimer_alarm_id_t alarm_id, systimer_counter_id_t counter_id); + +/** + * @brief set if a counter should be stalled when CPU is halted by the debugger + */ +void systimer_hal_counter_can_stall_by_cpu(uint32_t counter_id, uint32_t cpu_id, bool can); + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/systimer_types.h b/tools/sdk/esp32c3/include/hal/include/hal/systimer_types.h new file mode 100644 index 00000000..cf88a00f --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/systimer_types.h @@ -0,0 +1,74 @@ +// Copyright 2020 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "soc/soc_caps.h" + +/* + * @brief The structure of the counter value in systimer + * + */ +typedef struct { + union { + struct { + uint64_t lo : SOC_SYSTIMER_BIT_WIDTH_LO; /*!< Low part of counter value */ + uint64_t hi : SOC_SYSTIMER_BIT_WIDTH_HI; /*!< High part of counter value */ + }; + uint64_t val; /*!< counter value */ + }; +} systimer_counter_value_t; + +/** @cond */ +_Static_assert(sizeof(systimer_counter_value_t) == 8, "systimer_counter_value_t should occupy 8 bytes in memory"); +/** @endcond */ + +/** + * @brief systimer counter ID + * + */ +typedef enum { + SYSTIMER_COUNTER_0, /*!< systimer counter 0 */ +#if SOC_SYSTIMER_COUNTER_NUM > 1 + SYSTIMER_COUNTER_1, /*!< systimer counter 1 */ +#endif +} systimer_counter_id_t; + +/** + * @brief systimer alarm ID + * + */ +typedef enum { + SYSTIMER_ALARM_0, /*!< systimer alarm 0 */ + SYSTIMER_ALARM_1, /*!< systimer alarm 1 */ + SYSTIMER_ALARM_2, /*!< systimer alarm 2 */ +} systimer_alarm_id_t; + +/** + * @brief systimer alarm mode + * + */ +typedef enum { + SYSTIMER_ALARM_MODE_ONESHOT, /*!< systimer alarm oneshot mode */ + SYSTIMER_ALARM_MODE_PERIOD, /*!< systimer alarm period mode */ +} systimer_alarm_mode_t; + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/timer_hal.h b/tools/sdk/esp32c3/include/hal/include/hal/timer_hal.h new file mode 100644 index 00000000..f8c91739 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/timer_hal.h @@ -0,0 +1,330 @@ +// Copyright 2019 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. + +/******************************************************************************* + * NOTICE + * The hal is not public api, don't use in application code. + * See readme.md in hal/include/hal/readme.md + ******************************************************************************/ + +// The HAL layer for Timer Group. +// There is no parameter check in the hal layer, so the caller must ensure the correctness of the parameters. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "soc/soc_caps.h" +#include "hal/timer_ll.h" +#include "hal/timer_types.h" + +/** + * Context that should be maintained by both the driver and the HAL + */ +typedef struct { + timg_dev_t *dev; + timer_idx_t idx; +} timer_hal_context_t; + +/** + * @brief Init the timer hal. This function should be called first before other hal layer function is called + * + * @param hal Context of the HAL layer + * @param group_num The timer group number + * @param timer_num The timer number + * + * @return None + */ +void timer_hal_init(timer_hal_context_t *hal, timer_group_t group_num, timer_idx_t timer_num); + +/** + * @brief Get interrupt status register address and corresponding control bits mask + * + * @param hal Context of the HAL layer + * @param status_reg[out] interrupt status register address + * @param mask_bit[out] control bits mask + */ +void timer_hal_get_status_reg_mask_bit(timer_hal_context_t *hal, uint32_t *status_reg, uint32_t *mask_bit); + +/** + * @brief Set timer clock prescale value + * + * @param hal Context of the HAL layer + * @param divider Prescale value + * + * @return None + */ +#define timer_hal_set_divider(hal, divider) timer_ll_set_divider((hal)->dev, (hal)->idx, divider) + +/** + * @brief Get timer clock prescale value + * + * @param hal Context of the HAL layer + * @param divider Pointer to accept the prescale value + * + * @return None + */ +#define timer_hal_get_divider(hal, divider) timer_ll_get_divider((hal)->dev, (hal)->idx, divider) + +/** + * @brief Load counter value into time-base counter + * + * @param hal Context of the HAL layer + * @param load_val Counter value + * + * @return None + */ +#define timer_hal_set_counter_value(hal, load_val) timer_ll_set_counter_value((hal)->dev, (hal)->idx, load_val) + +/** + * @brief Get counter value from time-base counter + * + * @param hal Context of the HAL layer + * @param timer_val Pointer to accept the counter value + * + * @return None + */ +#define timer_hal_get_counter_value(hal, timer_val) timer_ll_get_counter_value((hal)->dev, (hal)->idx, timer_val) + +/** + * @brief Set counter mode, include increment mode and decrement mode. + * + * @param hal Context of the HAL layer + * @param increase_en True to increment mode, fasle to decrement mode + * + * @return None + */ +#define timer_hal_set_counter_increase(hal, increase_en) timer_ll_set_counter_increase((hal)->dev, (hal)->idx, increase_en) + +/** + * @brief Get counter mode, include increment mode and decrement mode. + * + * @param hal Context of the HAL layer + * @param counter_dir Pointer to accept the counter mode + * + * @return + * - true Increment mode + * - false Decrement mode + */ +#define timer_hal_get_counter_increase(hal) timer_ll_get_counter_increase((hal)->dev, (hal)->idx) + +/** + * @brief Set counter status, enable or disable counter. + * + * @param hal Context of the HAL layer + * @param counter_en True to enable counter, false to disable counter + * + * @return None + */ +#define timer_hal_set_counter_enable(hal, counter_en) timer_ll_set_counter_enable((hal)->dev, (hal)->idx, counter_en) + +/** + * @brief Get counter status. + * + * @param hal Context of the HAL layer + * + * @return + * - true Enable counter + * - false Disable conuter + */ +#define timer_hal_get_counter_enable(hal) timer_ll_get_counter_enable((hal)->dev, (hal)->idx) + +/** + * @brief Set auto reload mode. + * + * @param hal Context of the HAL layer + * @param auto_reload_en True to enable auto reload mode, flase to disable auto reload mode + * + * @return None + */ +#define timer_hal_set_auto_reload(hal, auto_reload_en) timer_ll_set_auto_reload((hal)->dev, (hal)->idx, auto_reload_en) + +/** + * @brief Get auto reload mode. + * + * @param hal Context of the HAL layer + * + * @return + * - true Enable auto reload mode + * - false Disable auto reload mode + */ +#define timer_hal_get_auto_reload(hal) timer_ll_get_auto_reload((hal)->dev, (hal)->idx) + +/** + * @brief Set the counter value to trigger the alarm. + * + * @param hal Context of the HAL layer + * @param alarm_value Counter value to trigger the alarm + * + * @return None + */ +#define timer_hal_set_alarm_value(hal, alarm_value) timer_ll_set_alarm_value((hal)->dev, (hal)->idx, alarm_value) + +/** + * @brief Get the counter value to trigger the alarm. + * + * @param hal Context of the HAL layer + * @param alarm_value Pointer to accept the counter value to trigger the alarm + * + * @return None + */ +#define timer_hal_get_alarm_value(hal, alarm_value) timer_ll_get_alarm_value((hal)->dev, (hal)->idx, alarm_value) + +/** + * @brief Set the alarm status, enable or disable the alarm. + * + * @param hal Context of the HAL layer + * @param alarm_en True to enable alarm, false to disable alarm + * + * @return None + */ +#define timer_hal_set_alarm_enable(hal, alarm_en) timer_ll_set_alarm_enable((hal)->dev, (hal)->idx, alarm_en) + +/** + * @brief Get the alarm status. + * + * @param hal Context of the HAL layer + * + * @return + * - true Enable alarm + * - false Disable alarm + */ +#define timer_hal_get_alarm_enable(hal) timer_ll_get_alarm_enable((hal)->dev, (hal)->idx) + +/** + * @brief Set the level interrupt status, enable or disable the level interrupt. + * + * @param hal Context of the HAL layer + * @param level_int_en True to enable level interrupt, false to disable level interrupt + * + * @return None + */ +#define timer_hal_set_level_int_enable(hal, level_int_en) timer_ll_set_level_int_enable((hal)->dev, (hal)->idx, level_int_en) + +/** + * @brief Get the level interrupt status. + * + * @param hal Context of the HAL layer + * + * @return + * - true Enable level interrupt + * - false Disable level interrupt + */ +#define timer_hal_get_level_int_enable(hal) timer_ll_get_level_int_enable((hal)->dev, (hal)->idx) + +/** + * @brief Set the edge interrupt status, enable or disable the edge interrupt. + * + * @param hal Context of the HAL layer + * @param edge_int_en True to enable edge interrupt, false to disable edge interrupt + * + * @return None + */ +#define timer_hal_set_edge_int_enable(hal, edge_int_en) timer_ll_set_edge_int_enable((hal)->dev, (hal)->idx, edge_int_en) + +/** + * @brief Get the edge interrupt status. + * + * @param hal Context of the HAL layer + * + * @return + * - true Enable edge interrupt + * - false Disable edge interrupt + */ +#define timer_hal_get_edge_int_enable(hal) timer_ll_get_edge_int_enable((hal)->dev, (hal)->idx) + +/** + * @brief Enable timer interrupt. + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define timer_hal_intr_enable(hal) timer_ll_intr_enable((hal)->dev, (hal)->idx) + +/** + * @brief Disable timer interrupt. + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define timer_hal_intr_disable(hal) timer_ll_intr_disable((hal)->dev, (hal)->idx) + +/** + * @brief Clear interrupt status. + * + * @param hal Context of the HAL layer + * + * @return None + */ +#define timer_hal_clear_intr_status(hal) timer_ll_clear_intr_status((hal)->dev, (hal)->idx) + +/** + * @brief Get interrupt status. + * + * @param hal Context of the HAL layer + * @param intr_status Interrupt status + * + * @return None + */ +#define timer_hal_get_intr_status(hal, intr_status) timer_ll_get_intr_status((hal)->dev, intr_status) + +/** + * @brief Get interrupt raw status. + * + * @param group_num Timer group number, 0 for TIMERG0 or 1 for TIMERG1 + * @param intr_raw_status Interrupt raw status + * + * @return None + */ +#define timer_hal_get_intr_raw_status(group_num, intr_raw_status) timer_ll_get_intr_raw_status(group_num, intr_raw_status) + +/** + * @brief Get interrupt status register address. + * + * @param hal Context of the HAL layer + * + * @return Interrupt status register address + */ +#define timer_hal_get_intr_status_reg(hal) timer_ll_get_intr_status_reg((hal)->dev) + +#if SOC_TIMER_GROUP_SUPPORT_XTAL +/** + * @brief Set clock source. + * + * @param hal Context of the HAL layer + * @param use_xtal_en True to use XTAL clock, flase to use APB clock + * + * @return None + */ +#define timer_hal_set_use_xtal(hal, use_xtal_en) timer_ll_set_use_xtal((hal)->dev, (hal)->idx, use_xtal_en) + +/** + * @brief Get clock source. + * + * @param hal Context of the HAL layer + * + * @return + * - true Use XTAL clock + * - false Use APB clock + */ +#define timer_hal_get_use_xtal(hal) timer_ll_get_use_xtal((hal)->dev, (hal)->idx) +#endif + +#ifdef __cplusplus +} +#endif diff --git a/tools/sdk/esp32c3/include/hal/include/hal/timer_types.h b/tools/sdk/esp32c3/include/hal/include/hal/timer_types.h new file mode 100644 index 00000000..962fae04 --- /dev/null +++ b/tools/sdk/esp32c3/include/hal/include/hal/timer_types.h @@ -0,0 +1,135 @@ +// Copyright 2015-2019 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. + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include "esp_attr.h" +#include "soc/soc_caps.h" + +/** + * @brief Selects a Timer-Group out of 2 available groups + */ +typedef enum { + TIMER_GROUP_0 = 0, /*! 1 + TIMER_GROUP_1 = 1, /*! 1 + TIMER_1 = 1, /*!